hls.js 640 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264
  1. (function webpackUniversalModuleDefinition(root, factory) {
  2. if(typeof exports === 'object' && typeof module === 'object')
  3. module.exports = factory();
  4. else if(typeof define === 'function' && define.amd)
  5. define([], factory);
  6. else if(typeof exports === 'object')
  7. exports["Hls"] = factory();
  8. else
  9. root["Hls"] = factory();
  10. })(this, function() {
  11. return /******/ (function(modules) { // webpackBootstrap
  12. /******/ // The module cache
  13. /******/ var installedModules = {};
  14. /******/
  15. /******/ // The require function
  16. /******/ function __webpack_require__(moduleId) {
  17. /******/
  18. /******/ // Check if module is in cache
  19. /******/ if(installedModules[moduleId]) {
  20. /******/ return installedModules[moduleId].exports;
  21. /******/ }
  22. /******/ // Create a new module (and put it into the cache)
  23. /******/ var module = installedModules[moduleId] = {
  24. /******/ i: moduleId,
  25. /******/ l: false,
  26. /******/ exports: {}
  27. /******/ };
  28. /******/
  29. /******/ // Execute the module function
  30. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  31. /******/
  32. /******/ // Flag the module as loaded
  33. /******/ module.l = true;
  34. /******/
  35. /******/ // Return the exports of the module
  36. /******/ return module.exports;
  37. /******/ }
  38. /******/
  39. /******/
  40. /******/ // expose the modules object (__webpack_modules__)
  41. /******/ __webpack_require__.m = modules;
  42. /******/
  43. /******/ // expose the module cache
  44. /******/ __webpack_require__.c = installedModules;
  45. /******/
  46. /******/ // define getter function for harmony exports
  47. /******/ __webpack_require__.d = function(exports, name, getter) {
  48. /******/ if(!__webpack_require__.o(exports, name)) {
  49. /******/ Object.defineProperty(exports, name, {
  50. /******/ configurable: false,
  51. /******/ enumerable: true,
  52. /******/ get: getter
  53. /******/ });
  54. /******/ }
  55. /******/ };
  56. /******/
  57. /******/ // getDefaultExport function for compatibility with non-harmony modules
  58. /******/ __webpack_require__.n = function(module) {
  59. /******/ var getter = module && module.__esModule ?
  60. /******/ function getDefault() { return module['default']; } :
  61. /******/ function getModuleExports() { return module; };
  62. /******/ __webpack_require__.d(getter, 'a', getter);
  63. /******/ return getter;
  64. /******/ };
  65. /******/
  66. /******/ // Object.prototype.hasOwnProperty.call
  67. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  68. /******/
  69. /******/ // __webpack_public_path__
  70. /******/ __webpack_require__.p = "/dist/";
  71. /******/
  72. /******/ // Load entry module and return exports
  73. /******/ return __webpack_require__(__webpack_require__.s = 9);
  74. /******/ })
  75. /************************************************************************/
  76. /******/ ([
  77. /* 0 */
  78. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  79. "use strict";
  80. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return enableLogs; });
  81. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return logger; });
  82. 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; };
  83. function noop() {}
  84. var fakeLogger = {
  85. trace: noop,
  86. debug: noop,
  87. log: noop,
  88. warn: noop,
  89. info: noop,
  90. error: noop
  91. };
  92. var exportedLogger = fakeLogger;
  93. /*globals self: false */
  94. //let lastCallTime;
  95. // function formatMsgWithTimeInfo(type, msg) {
  96. // const now = Date.now();
  97. // const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';
  98. // lastCallTime = now;
  99. // msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';
  100. // return msg;
  101. // }
  102. function formatMsg(type, msg) {
  103. msg = '[' + type + '] > ' + msg;
  104. return msg;
  105. }
  106. function consolePrintFn(type) {
  107. var func = self.console[type];
  108. if (func) {
  109. return function () {
  110. for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
  111. args[_key] = arguments[_key];
  112. }
  113. if (args[0]) {
  114. args[0] = formatMsg(type, args[0]);
  115. }
  116. func.apply(self.console, args);
  117. };
  118. }
  119. return noop;
  120. }
  121. function exportLoggerFunctions(debugConfig) {
  122. for (var _len2 = arguments.length, functions = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  123. functions[_key2 - 1] = arguments[_key2];
  124. }
  125. functions.forEach(function (type) {
  126. exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);
  127. });
  128. }
  129. var enableLogs = function enableLogs(debugConfig) {
  130. if (debugConfig === true || (typeof debugConfig === 'undefined' ? 'undefined' : _typeof(debugConfig)) === 'object') {
  131. exportLoggerFunctions(debugConfig,
  132. // Remove out from list here to hard-disable a log-level
  133. //'trace',
  134. 'debug', 'log', 'info', 'warn', 'error');
  135. // Some browsers don't allow to use bind on console object anyway
  136. // fallback to default if needed
  137. try {
  138. exportedLogger.log();
  139. } catch (e) {
  140. exportedLogger = fakeLogger;
  141. }
  142. } else {
  143. exportedLogger = fakeLogger;
  144. }
  145. };
  146. var logger = exportedLogger;
  147. /***/ }),
  148. /* 1 */
  149. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  150. "use strict";
  151. /* harmony default export */ __webpack_exports__["a"] = ({
  152. // fired before MediaSource is attaching to media element - data: { media }
  153. MEDIA_ATTACHING: 'hlsMediaAttaching',
  154. // fired when MediaSource has been succesfully attached to media element - data: { }
  155. MEDIA_ATTACHED: 'hlsMediaAttached',
  156. // fired before detaching MediaSource from media element - data: { }
  157. MEDIA_DETACHING: 'hlsMediaDetaching',
  158. // fired when MediaSource has been detached from media element - data: { }
  159. MEDIA_DETACHED: 'hlsMediaDetached',
  160. // fired when we buffer is going to be reset - data: { }
  161. BUFFER_RESET: 'hlsBufferReset',
  162. // fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }}
  163. BUFFER_CODECS: 'hlsBufferCodecs',
  164. // fired when sourcebuffers have been created - data: { tracks : tracks }
  165. BUFFER_CREATED: 'hlsBufferCreated',
  166. // fired when we append a segment to the buffer - data: { segment: segment object }
  167. BUFFER_APPENDING: 'hlsBufferAppending',
  168. // 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}
  169. BUFFER_APPENDED: 'hlsBufferAppended',
  170. // fired when the stream is finished and we want to notify the media buffer that there will be no more data - data: { }
  171. BUFFER_EOS: 'hlsBufferEos',
  172. // fired when the media buffer should be flushed - data { startOffset, endOffset }
  173. BUFFER_FLUSHING: 'hlsBufferFlushing',
  174. // fired when the media buffer has been flushed - data: { }
  175. BUFFER_FLUSHED: 'hlsBufferFlushed',
  176. // fired to signal that a manifest loading starts - data: { url : manifestURL}
  177. MANIFEST_LOADING: 'hlsManifestLoading',
  178. // fired after manifest has been loaded - data: { levels : [available quality levels], audioTracks : [ available audio tracks], url : manifestURL, stats : { trequest, tfirst, tload, mtime}}
  179. MANIFEST_LOADED: 'hlsManifestLoaded',
  180. // fired after manifest has been parsed - data: { levels : [available quality levels], firstLevel : index of first quality level appearing in Manifest}
  181. MANIFEST_PARSED: 'hlsManifestParsed',
  182. // fired when a level switch is requested - data: { level : id of new level } // deprecated in favor LEVEL_SWITCHING
  183. LEVEL_SWITCH: 'hlsLevelSwitch',
  184. // fired when a level switch is requested - data: { level : id of new level }
  185. LEVEL_SWITCHING: 'hlsLevelSwitching',
  186. // fired when a level switch is effective - data: { level : id of new level }
  187. LEVEL_SWITCHED: 'hlsLevelSwitched',
  188. // fired when a level playlist loading starts - data: { url : level URL, level : id of level being loaded}
  189. LEVEL_LOADING: 'hlsLevelLoading',
  190. // fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : { trequest, tfirst, tload, mtime} }
  191. LEVEL_LOADED: 'hlsLevelLoaded',
  192. // 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 }
  193. LEVEL_UPDATED: 'hlsLevelUpdated',
  194. // 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 }
  195. LEVEL_PTS_UPDATED: 'hlsLevelPtsUpdated',
  196. // fired to notify that audio track lists has been updated - data: { audioTracks : audioTracks }
  197. AUDIO_TRACKS_UPDATED: 'hlsAudioTracksUpdated',
  198. // fired when an audio track switch occurs - data: { id : audio track id } // deprecated in favor AUDIO_TRACK_SWITCHING
  199. AUDIO_TRACK_SWITCH: 'hlsAudioTrackSwitch',
  200. // fired when an audio track switching is requested - data: { id : audio track id }
  201. AUDIO_TRACK_SWITCHING: 'hlsAudioTrackSwitching',
  202. // fired when an audio track switch actually occurs - data: { id : audio track id }
  203. AUDIO_TRACK_SWITCHED: 'hlsAudioTrackSwitched',
  204. // fired when an audio track loading starts - data: { url : audio track URL, id : audio track id }
  205. AUDIO_TRACK_LOADING: 'hlsAudioTrackLoading',
  206. // fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : { trequest, tfirst, tload, mtime } }
  207. AUDIO_TRACK_LOADED: 'hlsAudioTrackLoaded',
  208. // fired to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks }
  209. SUBTITLE_TRACKS_UPDATED: 'hlsSubtitleTracksUpdated',
  210. // fired when an subtitle track switch occurs - data: { id : subtitle track id }
  211. SUBTITLE_TRACK_SWITCH: 'hlsSubtitleTrackSwitch',
  212. // fired when a subtitle track loading starts - data: { url : subtitle track URL, id : subtitle track id }
  213. SUBTITLE_TRACK_LOADING: 'hlsSubtitleTrackLoading',
  214. // fired when a subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : { trequest, tfirst, tload, mtime } }
  215. SUBTITLE_TRACK_LOADED: 'hlsSubtitleTrackLoaded',
  216. // fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag }
  217. SUBTITLE_FRAG_PROCESSED: 'hlsSubtitleFragProcessed',
  218. // fired when the first timestamp is found - data: { id : demuxer id, initPTS: initPTS, frag : fragment object }
  219. INIT_PTS_FOUND: 'hlsInitPtsFound',
  220. // fired when a fragment loading starts - data: { frag : fragment object }
  221. FRAG_LOADING: 'hlsFragLoading',
  222. // fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded } }
  223. FRAG_LOAD_PROGRESS: 'hlsFragLoadProgress',
  224. // Identifier for fragment load aborting for emergency switch down - data: { frag : fragment object }
  225. FRAG_LOAD_EMERGENCY_ABORTED: 'hlsFragLoadEmergencyAborted',
  226. // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length } }
  227. FRAG_LOADED: 'hlsFragLoaded',
  228. // fired when a fragment has finished decrypting - data: { id : demuxer id, frag: fragment object, payload : fragment payload, stats : { tstart, tdecrypt } }
  229. FRAG_DECRYPTED: 'hlsFragDecrypted',
  230. // 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 }
  231. FRAG_PARSING_INIT_SEGMENT: 'hlsFragParsingInitSegment',
  232. // fired when parsing sei text is completed - data: { id : demuxer id, frag: fragment object, samples : [ sei samples pes ] }
  233. FRAG_PARSING_USERDATA: 'hlsFragParsingUserdata',
  234. // fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] }
  235. FRAG_PARSING_METADATA: 'hlsFragParsingMetadata',
  236. // 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}
  237. FRAG_PARSING_DATA: 'hlsFragParsingData',
  238. // fired when fragment parsing is completed - data: { id : demuxer id, frag: fragment object }
  239. FRAG_PARSED: 'hlsFragParsed',
  240. // fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { id : demuxer id, frag : fragment object, stats : { trequest, tfirst, tload, tparsed, tbuffered, length, bwEstimate } }
  241. FRAG_BUFFERED: 'hlsFragBuffered',
  242. // fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object }
  243. FRAG_CHANGED: 'hlsFragChanged',
  244. // Identifier for a FPS drop event - data: { curentDropped, currentDecoded, totalDroppedFrames }
  245. FPS_DROP: 'hlsFpsDrop',
  246. //triggered when FPS drop triggers auto level capping - data: { level, droppedlevel }
  247. FPS_DROP_LEVEL_CAPPING: 'hlsFpsDropLevelCapping',
  248. // 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 }
  249. ERROR: 'hlsError',
  250. // fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a media to the instance of hls.js to handle mid-rolls for example - data: { }
  251. DESTROYING: 'hlsDestroying',
  252. // fired when a decrypt key loading starts - data: { frag : fragment object }
  253. KEY_LOADING: 'hlsKeyLoading',
  254. // fired when a decrypt key loading is completed - data: { frag : fragment object, payload : key payload, stats : { trequest, tfirst, tload, length } }
  255. KEY_LOADED: 'hlsKeyLoaded',
  256. // fired upon stream controller state transitions - data: { previousState, nextState }
  257. STREAM_STATE_TRANSITION: 'hlsStreamStateTransition'
  258. });
  259. /***/ }),
  260. /* 2 */
  261. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  262. "use strict";
  263. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return ErrorTypes; });
  264. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ErrorDetails; });
  265. var ErrorTypes = {
  266. // Identifier for a network error (loading error / timeout ...)
  267. NETWORK_ERROR: 'networkError',
  268. // Identifier for a media Error (video/parsing/mediasource error)
  269. MEDIA_ERROR: 'mediaError',
  270. // EME (encrypted media extensions) errors
  271. KEY_SYSTEM_ERROR: 'keySystemError',
  272. // Identifier for a mux Error (demuxing/remuxing)
  273. MUX_ERROR: 'muxError',
  274. // Identifier for all other errors
  275. OTHER_ERROR: 'otherError'
  276. };
  277. var ErrorDetails = {
  278. KEY_SYSTEM_NO_KEYS: 'keySystemNoKeys',
  279. KEY_SYSTEM_NO_ACCESS: 'keySystemNoAccess',
  280. KEY_SYSTEM_NO_SESSION: 'keySystemNoSession',
  281. KEY_SYSTEM_LICENSE_REQUEST_FAILED: 'keySystemLicenseRequestFailed',
  282. // Identifier for a manifest load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  283. MANIFEST_LOAD_ERROR: 'manifestLoadError',
  284. // Identifier for a manifest load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  285. MANIFEST_LOAD_TIMEOUT: 'manifestLoadTimeOut',
  286. // Identifier for a manifest parsing error - data: { url : faulty URL, reason : error reason}
  287. MANIFEST_PARSING_ERROR: 'manifestParsingError',
  288. // Identifier for a manifest with only incompatible codecs error - data: { url : faulty URL, reason : error reason}
  289. MANIFEST_INCOMPATIBLE_CODECS_ERROR: 'manifestIncompatibleCodecsError',
  290. // Identifier for a level load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  291. LEVEL_LOAD_ERROR: 'levelLoadError',
  292. // Identifier for a level load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  293. LEVEL_LOAD_TIMEOUT: 'levelLoadTimeOut',
  294. // Identifier for a level switch error - data: { level : faulty level Id, event : error description}
  295. LEVEL_SWITCH_ERROR: 'levelSwitchError',
  296. // Identifier for an audio track load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  297. AUDIO_TRACK_LOAD_ERROR: 'audioTrackLoadError',
  298. // Identifier for an audio track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  299. AUDIO_TRACK_LOAD_TIMEOUT: 'audioTrackLoadTimeOut',
  300. // Identifier for fragment load error - data: { frag : fragment object, response : { code: error code, text: error text }}
  301. FRAG_LOAD_ERROR: 'fragLoadError',
  302. // Identifier for fragment loop loading error - data: { frag : fragment object}
  303. FRAG_LOOP_LOADING_ERROR: 'fragLoopLoadingError',
  304. // Identifier for fragment load timeout error - data: { frag : fragment object}
  305. FRAG_LOAD_TIMEOUT: 'fragLoadTimeOut',
  306. // Identifier for a fragment decryption error event - data: {id : demuxer Id,frag: fragment object, reason : parsing error description }
  307. FRAG_DECRYPT_ERROR: 'fragDecryptError',
  308. // Identifier for a fragment parsing error event - data: { id : demuxer Id, reason : parsing error description }
  309. // will be renamed DEMUX_PARSING_ERROR and switched to MUX_ERROR in the next major release
  310. FRAG_PARSING_ERROR: 'fragParsingError',
  311. // 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 }
  312. REMUX_ALLOC_ERROR: 'remuxAllocError',
  313. // Identifier for decrypt key load error - data: { frag : fragment object, response : { code: error code, text: error text }}
  314. KEY_LOAD_ERROR: 'keyLoadError',
  315. // Identifier for decrypt key load timeout error - data: { frag : fragment object}
  316. KEY_LOAD_TIMEOUT: 'keyLoadTimeOut',
  317. // Triggered when an exception occurs while adding a sourceBuffer to MediaSource - data : { err : exception , mimeType : mimeType }
  318. BUFFER_ADD_CODEC_ERROR: 'bufferAddCodecError',
  319. // Identifier for a buffer append error - data: append error description
  320. BUFFER_APPEND_ERROR: 'bufferAppendError',
  321. // Identifier for a buffer appending error event - data: appending error description
  322. BUFFER_APPENDING_ERROR: 'bufferAppendingError',
  323. // Identifier for a buffer stalled error event
  324. BUFFER_STALLED_ERROR: 'bufferStalledError',
  325. // Identifier for a buffer full event
  326. BUFFER_FULL_ERROR: 'bufferFullError',
  327. // Identifier for a buffer seek over hole event
  328. BUFFER_SEEK_OVER_HOLE: 'bufferSeekOverHole',
  329. // Identifier for a buffer nudge on stall (playback is stuck although currentTime is in a buffered area)
  330. BUFFER_NUDGE_ON_STALL: 'bufferNudgeOnStall',
  331. // Identifier for an internal exception happening inside hls.js while handling an event
  332. INTERNAL_EXCEPTION: 'internalException'
  333. };
  334. /***/ }),
  335. /* 3 */
  336. /***/ (function(module, exports, __webpack_require__) {
  337. // see https://tools.ietf.org/html/rfc1808
  338. /* jshint ignore:start */
  339. (function(root) {
  340. /* jshint ignore:end */
  341. var URL_REGEX = /^((?:[^\/;?#]+:)?)(\/\/[^\/\;?#]*)?(.*?)??(;.*?)?(\?.*?)?(#.*?)?$/;
  342. var FIRST_SEGMENT_REGEX = /^([^\/;?#]*)(.*)$/;
  343. var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
  344. var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/).*?(?=\/)/g;
  345. var URLToolkit = { // jshint ignore:line
  346. // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
  347. // E.g
  348. // With opts.alwaysNormalize = false (default, spec compliant)
  349. // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
  350. // With opts.alwaysNormalize = true (default, not spec compliant)
  351. // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
  352. buildAbsoluteURL: function(baseURL, relativeURL, opts) {
  353. opts = opts || {};
  354. // remove any remaining space and CRLF
  355. baseURL = baseURL.trim();
  356. relativeURL = relativeURL.trim();
  357. if (!relativeURL) {
  358. // 2a) If the embedded URL is entirely empty, it inherits the
  359. // entire base URL (i.e., is set equal to the base URL)
  360. // and we are done.
  361. if (!opts.alwaysNormalize) {
  362. return baseURL;
  363. }
  364. var basePartsForNormalise = this.parseURL(baseURL);
  365. if (!baseParts) {
  366. throw new Error('Error trying to parse base URL.');
  367. }
  368. basePartsForNormalise.path = URLToolkit.normalizePath(basePartsForNormalise.path);
  369. return URLToolkit.buildURLFromParts(basePartsForNormalise);
  370. }
  371. var relativeParts = this.parseURL(relativeURL);
  372. if (!relativeParts) {
  373. throw new Error('Error trying to parse relative URL.');
  374. }
  375. if (relativeParts.scheme) {
  376. // 2b) If the embedded URL starts with a scheme name, it is
  377. // interpreted as an absolute URL and we are done.
  378. if (!opts.alwaysNormalize) {
  379. return relativeURL;
  380. }
  381. relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
  382. return URLToolkit.buildURLFromParts(relativeParts);
  383. }
  384. var baseParts = this.parseURL(baseURL);
  385. if (!baseParts) {
  386. throw new Error('Error trying to parse base URL.');
  387. }
  388. if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
  389. // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
  390. // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
  391. var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
  392. baseParts.netLoc = pathParts[1];
  393. baseParts.path = pathParts[2];
  394. }
  395. if (baseParts.netLoc && !baseParts.path) {
  396. baseParts.path = '/';
  397. }
  398. var builtParts = {
  399. // 2c) Otherwise, the embedded URL inherits the scheme of
  400. // the base URL.
  401. scheme: baseParts.scheme,
  402. netLoc: relativeParts.netLoc,
  403. path: null,
  404. params: relativeParts.params,
  405. query: relativeParts.query,
  406. fragment: relativeParts.fragment
  407. };
  408. if (!relativeParts.netLoc) {
  409. // 3) If the embedded URL's <net_loc> is non-empty, we skip to
  410. // Step 7. Otherwise, the embedded URL inherits the <net_loc>
  411. // (if any) of the base URL.
  412. builtParts.netLoc = baseParts.netLoc;
  413. // 4) If the embedded URL path is preceded by a slash "/", the
  414. // path is not relative and we skip to Step 7.
  415. if (relativeParts.path[0] !== '/') {
  416. if (!relativeParts.path) {
  417. // 5) If the embedded URL path is empty (and not preceded by a
  418. // slash), then the embedded URL inherits the base URL path
  419. builtParts.path = baseParts.path;
  420. // 5a) if the embedded URL's <params> is non-empty, we skip to
  421. // step 7; otherwise, it inherits the <params> of the base
  422. // URL (if any) and
  423. if (!relativeParts.params) {
  424. builtParts.params = baseParts.params;
  425. // 5b) if the embedded URL's <query> is non-empty, we skip to
  426. // step 7; otherwise, it inherits the <query> of the base
  427. // URL (if any) and we skip to step 7.
  428. if (!relativeParts.query) {
  429. builtParts.query = baseParts.query;
  430. }
  431. }
  432. } else {
  433. // 6) The last segment of the base URL's path (anything
  434. // following the rightmost slash "/", or the entire path if no
  435. // slash is present) is removed and the embedded URL's path is
  436. // appended in its place.
  437. var baseURLPath = baseParts.path;
  438. var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) + relativeParts.path;
  439. builtParts.path = URLToolkit.normalizePath(newPath);
  440. }
  441. }
  442. }
  443. if (builtParts.path === null) {
  444. builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;
  445. }
  446. return URLToolkit.buildURLFromParts(builtParts);
  447. },
  448. parseURL: function(url) {
  449. var parts = URL_REGEX.exec(url);
  450. if (!parts) {
  451. return null;
  452. }
  453. return {
  454. scheme: parts[1] || '',
  455. netLoc: parts[2] || '',
  456. path: parts[3] || '',
  457. params: parts[4] || '',
  458. query: parts[5] || '',
  459. fragment: parts[6] || ''
  460. };
  461. },
  462. normalizePath: function(path) {
  463. // The following operations are
  464. // then applied, in order, to the new path:
  465. // 6a) All occurrences of "./", where "." is a complete path
  466. // segment, are removed.
  467. // 6b) If the path ends with "." as a complete path segment,
  468. // that "." is removed.
  469. path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');
  470. // 6c) All occurrences of "<segment>/../", where <segment> is a
  471. // complete path segment not equal to "..", are removed.
  472. // Removal of these path segments is performed iteratively,
  473. // removing the leftmost matching pattern on each iteration,
  474. // until no matching pattern remains.
  475. // 6d) If the path ends with "<segment>/..", where <segment> is a
  476. // complete path segment not equal to "..", that
  477. // "<segment>/.." is removed.
  478. while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length) {} // jshint ignore:line
  479. return path.split('').reverse().join('');
  480. },
  481. buildURLFromParts: function(parts) {
  482. return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;
  483. }
  484. };
  485. /* jshint ignore:start */
  486. if(true)
  487. module.exports = URLToolkit;
  488. else if(typeof define === 'function' && define.amd)
  489. define([], function() { return URLToolkit; });
  490. else if(typeof exports === 'object')
  491. exports["URLToolkit"] = URLToolkit;
  492. else
  493. root["URLToolkit"] = URLToolkit;
  494. })(this);
  495. /* jshint ignore:end */
  496. /***/ }),
  497. /* 4 */
  498. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  499. "use strict";
  500. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return utf8ArrayToStr; });
  501. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  502. /**
  503. * ID3 parser
  504. */
  505. var ID3 = function () {
  506. function ID3() {
  507. _classCallCheck(this, ID3);
  508. }
  509. /**
  510. * Returns true if an ID3 header can be found at offset in data
  511. * @param {Uint8Array} data - The data to search in
  512. * @param {number} offset - The offset at which to start searching
  513. * @return {boolean} - True if an ID3 header is found
  514. */
  515. ID3.isHeader = function isHeader(data, offset) {
  516. /*
  517. * http://id3.org/id3v2.3.0
  518. * [0] = 'I'
  519. * [1] = 'D'
  520. * [2] = '3'
  521. * [3,4] = {Version}
  522. * [5] = {Flags}
  523. * [6-9] = {ID3 Size}
  524. *
  525. * An ID3v2 tag can be detected with the following pattern:
  526. * $49 44 33 yy yy xx zz zz zz zz
  527. * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80
  528. */
  529. if (offset + 10 <= data.length) {
  530. //look for 'ID3' identifier
  531. if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) {
  532. //check version is within range
  533. if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) {
  534. //check size is within range
  535. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  536. return true;
  537. }
  538. }
  539. }
  540. }
  541. return false;
  542. };
  543. /**
  544. * Returns true if an ID3 footer can be found at offset in data
  545. * @param {Uint8Array} data - The data to search in
  546. * @param {number} offset - The offset at which to start searching
  547. * @return {boolean} - True if an ID3 footer is found
  548. */
  549. ID3.isFooter = function isFooter(data, offset) {
  550. /*
  551. * The footer is a copy of the header, but with a different identifier
  552. */
  553. if (offset + 10 <= data.length) {
  554. //look for '3DI' identifier
  555. if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) {
  556. //check version is within range
  557. if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) {
  558. //check size is within range
  559. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  560. return true;
  561. }
  562. }
  563. }
  564. }
  565. return false;
  566. };
  567. /**
  568. * Returns any adjacent ID3 tags found in data starting at offset, as one block of data
  569. * @param {Uint8Array} data - The data to search in
  570. * @param {number} offset - The offset at which to start searching
  571. * @return {Uint8Array} - The block of data containing any ID3 tags found
  572. */
  573. ID3.getID3Data = function getID3Data(data, offset) {
  574. var front = offset;
  575. var length = 0;
  576. while (ID3.isHeader(data, offset)) {
  577. //ID3 header is 10 bytes
  578. length += 10;
  579. var size = ID3._readSize(data, offset + 6);
  580. length += size;
  581. if (ID3.isFooter(data, offset + 10)) {
  582. //ID3 footer is 10 bytes
  583. length += 10;
  584. }
  585. offset += length;
  586. }
  587. if (length > 0) {
  588. return data.subarray(front, front + length);
  589. }
  590. return undefined;
  591. };
  592. ID3._readSize = function _readSize(data, offset) {
  593. var size = 0;
  594. size = (data[offset] & 0x7f) << 21;
  595. size |= (data[offset + 1] & 0x7f) << 14;
  596. size |= (data[offset + 2] & 0x7f) << 7;
  597. size |= data[offset + 3] & 0x7f;
  598. return size;
  599. };
  600. /**
  601. * Searches for the Elementary Stream timestamp found in the ID3 data chunk
  602. * @param {Uint8Array} data - Block of data containing one or more ID3 tags
  603. * @return {number} - The timestamp
  604. */
  605. ID3.getTimeStamp = function getTimeStamp(data) {
  606. var frames = ID3.getID3Frames(data);
  607. for (var i = 0; i < frames.length; i++) {
  608. var frame = frames[i];
  609. if (ID3.isTimeStampFrame(frame)) {
  610. return ID3._readTimeStamp(frame);
  611. }
  612. }
  613. return undefined;
  614. };
  615. /**
  616. * Returns true if the ID3 frame is an Elementary Stream timestamp frame
  617. * @param {ID3 frame} frame
  618. */
  619. ID3.isTimeStampFrame = function isTimeStampFrame(frame) {
  620. return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp';
  621. };
  622. ID3._getFrameData = function _getFrameData(data) {
  623. /*
  624. Frame ID $xx xx xx xx (four characters)
  625. Size $xx xx xx xx
  626. Flags $xx xx
  627. */
  628. var type = String.fromCharCode(data[0], data[1], data[2], data[3]);
  629. var size = ID3._readSize(data, 4);
  630. //skip frame id, size, and flags
  631. var offset = 10;
  632. return { type: type, size: size, data: data.subarray(offset, offset + size) };
  633. };
  634. /**
  635. * Returns an array of ID3 frames found in all the ID3 tags in the id3Data
  636. * @param {Uint8Array} id3Data - The ID3 data containing one or more ID3 tags
  637. * @return {ID3 frame[]} - Array of ID3 frame objects
  638. */
  639. ID3.getID3Frames = function getID3Frames(id3Data) {
  640. var offset = 0;
  641. var frames = [];
  642. while (ID3.isHeader(id3Data, offset)) {
  643. var size = ID3._readSize(id3Data, offset + 6);
  644. //skip past ID3 header
  645. offset += 10;
  646. var end = offset + size;
  647. //loop through frames in the ID3 tag
  648. while (offset + 8 < end) {
  649. var frameData = ID3._getFrameData(id3Data.subarray(offset));
  650. var frame = ID3._decodeFrame(frameData);
  651. if (frame) {
  652. frames.push(frame);
  653. }
  654. //skip frame header and frame data
  655. offset += frameData.size + 10;
  656. }
  657. if (ID3.isFooter(id3Data, offset)) {
  658. offset += 10;
  659. }
  660. }
  661. return frames;
  662. };
  663. ID3._decodeFrame = function _decodeFrame(frame) {
  664. if (frame.type === 'PRIV') {
  665. return ID3._decodePrivFrame(frame);
  666. } else if (frame.type[0] === 'T') {
  667. return ID3._decodeTextFrame(frame);
  668. } else if (frame.type[0] === 'W') {
  669. return ID3._decodeURLFrame(frame);
  670. }
  671. return undefined;
  672. };
  673. ID3._readTimeStamp = function _readTimeStamp(timeStampFrame) {
  674. if (timeStampFrame.data.byteLength === 8) {
  675. var data = new Uint8Array(timeStampFrame.data);
  676. // timestamp is 33 bit expressed as a big-endian eight-octet number,
  677. // with the upper 31 bits set to zero.
  678. var pts33Bit = data[3] & 0x1;
  679. var timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];
  680. timestamp /= 45;
  681. if (pts33Bit) {
  682. timestamp += 47721858.84; // 2^32 / 90
  683. }
  684. return Math.round(timestamp);
  685. }
  686. return undefined;
  687. };
  688. ID3._decodePrivFrame = function _decodePrivFrame(frame) {
  689. /*
  690. Format: <text string>\0<binary data>
  691. */
  692. if (frame.size < 2) {
  693. return undefined;
  694. }
  695. var owner = ID3._utf8ArrayToStr(frame.data, true);
  696. var privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
  697. return { key: frame.type, info: owner, data: privateData.buffer };
  698. };
  699. ID3._decodeTextFrame = function _decodeTextFrame(frame) {
  700. if (frame.size < 2) {
  701. return undefined;
  702. }
  703. if (frame.type === 'TXXX') {
  704. /*
  705. Format:
  706. [0] = {Text Encoding}
  707. [1-?] = {Description}\0{Value}
  708. */
  709. var index = 1;
  710. var description = ID3._utf8ArrayToStr(frame.data.subarray(index));
  711. index += description.length + 1;
  712. var value = ID3._utf8ArrayToStr(frame.data.subarray(index));
  713. return { key: frame.type, info: description, data: value };
  714. } else {
  715. /*
  716. Format:
  717. [0] = {Text Encoding}
  718. [1-?] = {Value}
  719. */
  720. var text = ID3._utf8ArrayToStr(frame.data.subarray(1));
  721. return { key: frame.type, data: text };
  722. }
  723. };
  724. ID3._decodeURLFrame = function _decodeURLFrame(frame) {
  725. if (frame.type === 'WXXX') {
  726. /*
  727. Format:
  728. [0] = {Text Encoding}
  729. [1-?] = {Description}\0{URL}
  730. */
  731. if (frame.size < 2) {
  732. return undefined;
  733. }
  734. var index = 1;
  735. var description = ID3._utf8ArrayToStr(frame.data.subarray(index));
  736. index += description.length + 1;
  737. var value = ID3._utf8ArrayToStr(frame.data.subarray(index));
  738. return { key: frame.type, info: description, data: value };
  739. } else {
  740. /*
  741. Format:
  742. [0-?] = {URL}
  743. */
  744. var url = ID3._utf8ArrayToStr(frame.data);
  745. return { key: frame.type, data: url };
  746. }
  747. };
  748. // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197
  749. // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
  750. /* utf.js - UTF-8 <=> UTF-16 convertion
  751. *
  752. * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
  753. * Version: 1.0
  754. * LastModified: Dec 25 1999
  755. * This library is free. You can redistribute it and/or modify it.
  756. */
  757. ID3._utf8ArrayToStr = function _utf8ArrayToStr(array) {
  758. var exitOnNull = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  759. var len = array.length;
  760. var c = void 0;
  761. var char2 = void 0;
  762. var char3 = void 0;
  763. var out = '';
  764. var i = 0;
  765. while (i < len) {
  766. c = array[i++];
  767. if (c === 0x00 && exitOnNull) {
  768. return out;
  769. } else if (c === 0x00 || c === 0x03) {
  770. // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it
  771. continue;
  772. }
  773. switch (c >> 4) {
  774. case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:
  775. // 0xxxxxxx
  776. out += String.fromCharCode(c);
  777. break;
  778. case 12:case 13:
  779. // 110x xxxx 10xx xxxx
  780. char2 = array[i++];
  781. out += String.fromCharCode((c & 0x1F) << 6 | char2 & 0x3F);
  782. break;
  783. case 14:
  784. // 1110 xxxx 10xx xxxx 10xx xxxx
  785. char2 = array[i++];
  786. char3 = array[i++];
  787. out += String.fromCharCode((c & 0x0F) << 12 | (char2 & 0x3F) << 6 | (char3 & 0x3F) << 0);
  788. break;
  789. default:
  790. }
  791. }
  792. return out;
  793. };
  794. return ID3;
  795. }();
  796. var utf8ArrayToStr = ID3._utf8ArrayToStr;
  797. /* harmony default export */ __webpack_exports__["a"] = (ID3);
  798. /***/ }),
  799. /* 5 */
  800. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  801. "use strict";
  802. // CONCATENATED MODULE: ./src/crypt/aes-crypto.js
  803. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  804. var AESCrypto = function () {
  805. function AESCrypto(subtle, iv) {
  806. _classCallCheck(this, AESCrypto);
  807. this.subtle = subtle;
  808. this.aesIV = iv;
  809. }
  810. AESCrypto.prototype.decrypt = function decrypt(data, key) {
  811. return this.subtle.decrypt({ name: 'AES-CBC', iv: this.aesIV }, key, data);
  812. };
  813. return AESCrypto;
  814. }();
  815. /* harmony default export */ var aes_crypto = (AESCrypto);
  816. // CONCATENATED MODULE: ./src/crypt/fast-aes-key.js
  817. function fast_aes_key__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  818. var FastAESKey = function () {
  819. function FastAESKey(subtle, key) {
  820. fast_aes_key__classCallCheck(this, FastAESKey);
  821. this.subtle = subtle;
  822. this.key = key;
  823. }
  824. FastAESKey.prototype.expandKey = function expandKey() {
  825. return this.subtle.importKey('raw', this.key, { name: 'AES-CBC' }, false, ['encrypt', 'decrypt']);
  826. };
  827. return FastAESKey;
  828. }();
  829. /* harmony default export */ var fast_aes_key = (FastAESKey);
  830. // CONCATENATED MODULE: ./src/crypt/aes-decryptor.js
  831. function aes_decryptor__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  832. var AESDecryptor = function () {
  833. function AESDecryptor() {
  834. aes_decryptor__classCallCheck(this, AESDecryptor);
  835. // Static after running initTable
  836. this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
  837. this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  838. this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  839. this.sBox = new Uint32Array(256);
  840. this.invSBox = new Uint32Array(256);
  841. // Changes during runtime
  842. this.key = new Uint32Array(0);
  843. this.initTable();
  844. }
  845. // Using view.getUint32() also swaps the byte order.
  846. AESDecryptor.prototype.uint8ArrayToUint32Array_ = function uint8ArrayToUint32Array_(arrayBuffer) {
  847. var view = new DataView(arrayBuffer);
  848. var newArray = new Uint32Array(4);
  849. for (var i = 0; i < 4; i++) {
  850. newArray[i] = view.getUint32(i * 4);
  851. }
  852. return newArray;
  853. };
  854. AESDecryptor.prototype.initTable = function initTable() {
  855. var sBox = this.sBox;
  856. var invSBox = this.invSBox;
  857. var subMix = this.subMix;
  858. var subMix0 = subMix[0];
  859. var subMix1 = subMix[1];
  860. var subMix2 = subMix[2];
  861. var subMix3 = subMix[3];
  862. var invSubMix = this.invSubMix;
  863. var invSubMix0 = invSubMix[0];
  864. var invSubMix1 = invSubMix[1];
  865. var invSubMix2 = invSubMix[2];
  866. var invSubMix3 = invSubMix[3];
  867. var d = new Uint32Array(256);
  868. var x = 0;
  869. var xi = 0;
  870. var i = 0;
  871. for (i = 0; i < 256; i++) {
  872. if (i < 128) {
  873. d[i] = i << 1;
  874. } else {
  875. d[i] = i << 1 ^ 0x11b;
  876. }
  877. }
  878. for (i = 0; i < 256; i++) {
  879. var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
  880. sx = sx >>> 8 ^ sx & 0xff ^ 0x63;
  881. sBox[x] = sx;
  882. invSBox[sx] = x;
  883. // Compute multiplication
  884. var x2 = d[x];
  885. var x4 = d[x2];
  886. var x8 = d[x4];
  887. // Compute sub/invSub bytes, mix columns tables
  888. var t = d[sx] * 0x101 ^ sx * 0x1010100;
  889. subMix0[x] = t << 24 | t >>> 8;
  890. subMix1[x] = t << 16 | t >>> 16;
  891. subMix2[x] = t << 8 | t >>> 24;
  892. subMix3[x] = t;
  893. // Compute inv sub bytes, inv mix columns tables
  894. t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  895. invSubMix0[sx] = t << 24 | t >>> 8;
  896. invSubMix1[sx] = t << 16 | t >>> 16;
  897. invSubMix2[sx] = t << 8 | t >>> 24;
  898. invSubMix3[sx] = t;
  899. // Compute next counter
  900. if (!x) {
  901. x = xi = 1;
  902. } else {
  903. x = x2 ^ d[d[d[x8 ^ x2]]];
  904. xi ^= d[d[xi]];
  905. }
  906. }
  907. };
  908. AESDecryptor.prototype.expandKey = function expandKey(keyBuffer) {
  909. // convert keyBuffer to Uint32Array
  910. var key = this.uint8ArrayToUint32Array_(keyBuffer);
  911. var sameKey = true;
  912. var offset = 0;
  913. while (offset < key.length && sameKey) {
  914. sameKey = key[offset] === this.key[offset];
  915. offset++;
  916. }
  917. if (sameKey) {
  918. return;
  919. }
  920. this.key = key;
  921. var keySize = this.keySize = key.length;
  922. if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
  923. throw new Error('Invalid aes key size=' + keySize);
  924. }
  925. var ksRows = this.ksRows = (keySize + 6 + 1) * 4;
  926. var ksRow = void 0;
  927. var invKsRow = void 0;
  928. var keySchedule = this.keySchedule = new Uint32Array(ksRows);
  929. var invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
  930. var sbox = this.sBox;
  931. var rcon = this.rcon;
  932. var invSubMix = this.invSubMix;
  933. var invSubMix0 = invSubMix[0];
  934. var invSubMix1 = invSubMix[1];
  935. var invSubMix2 = invSubMix[2];
  936. var invSubMix3 = invSubMix[3];
  937. var prev = void 0;
  938. var t = void 0;
  939. for (ksRow = 0; ksRow < ksRows; ksRow++) {
  940. if (ksRow < keySize) {
  941. prev = keySchedule[ksRow] = key[ksRow];
  942. continue;
  943. }
  944. t = prev;
  945. if (ksRow % keySize === 0) {
  946. // Rot word
  947. t = t << 8 | t >>> 24;
  948. // Sub word
  949. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  950. // Mix Rcon
  951. t ^= rcon[ksRow / keySize | 0] << 24;
  952. } else if (keySize > 6 && ksRow % keySize === 4) {
  953. // Sub word
  954. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  955. }
  956. keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
  957. }
  958. for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
  959. ksRow = ksRows - invKsRow;
  960. if (invKsRow & 3) {
  961. t = keySchedule[ksRow];
  962. } else {
  963. t = keySchedule[ksRow - 4];
  964. }
  965. if (invKsRow < 4 || ksRow <= 4) {
  966. invKeySchedule[invKsRow] = t;
  967. } else {
  968. invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]];
  969. }
  970. invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
  971. }
  972. };
  973. // Adding this as a method greatly improves performance.
  974. AESDecryptor.prototype.networkToHostOrderSwap = function networkToHostOrderSwap(word) {
  975. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  976. };
  977. AESDecryptor.prototype.decrypt = function decrypt(inputArrayBuffer, offset, aesIV) {
  978. var nRounds = this.keySize + 6;
  979. var invKeySchedule = this.invKeySchedule;
  980. var invSBOX = this.invSBox;
  981. var invSubMix = this.invSubMix;
  982. var invSubMix0 = invSubMix[0];
  983. var invSubMix1 = invSubMix[1];
  984. var invSubMix2 = invSubMix[2];
  985. var invSubMix3 = invSubMix[3];
  986. var initVector = this.uint8ArrayToUint32Array_(aesIV);
  987. var initVector0 = initVector[0];
  988. var initVector1 = initVector[1];
  989. var initVector2 = initVector[2];
  990. var initVector3 = initVector[3];
  991. var inputInt32 = new Int32Array(inputArrayBuffer);
  992. var outputInt32 = new Int32Array(inputInt32.length);
  993. var t0 = void 0,
  994. t1 = void 0,
  995. t2 = void 0,
  996. t3 = void 0;
  997. var s0 = void 0,
  998. s1 = void 0,
  999. s2 = void 0,
  1000. s3 = void 0;
  1001. var inputWords0 = void 0,
  1002. inputWords1 = void 0,
  1003. inputWords2 = void 0,
  1004. inputWords3 = void 0;
  1005. var ksRow, i;
  1006. var swapWord = this.networkToHostOrderSwap;
  1007. while (offset < inputInt32.length) {
  1008. inputWords0 = swapWord(inputInt32[offset]);
  1009. inputWords1 = swapWord(inputInt32[offset + 1]);
  1010. inputWords2 = swapWord(inputInt32[offset + 2]);
  1011. inputWords3 = swapWord(inputInt32[offset + 3]);
  1012. s0 = inputWords0 ^ invKeySchedule[0];
  1013. s1 = inputWords3 ^ invKeySchedule[1];
  1014. s2 = inputWords2 ^ invKeySchedule[2];
  1015. s3 = inputWords1 ^ invKeySchedule[3];
  1016. ksRow = 4;
  1017. // Iterate through the rounds of decryption
  1018. for (i = 1; i < nRounds; i++) {
  1019. t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];
  1020. t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  1021. t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  1022. t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  1023. // Update state
  1024. s0 = t0;
  1025. s1 = t1;
  1026. s2 = t2;
  1027. s3 = t3;
  1028. ksRow = ksRow + 4;
  1029. }
  1030. // Shift rows, sub bytes, add round key
  1031. t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow];
  1032. t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  1033. t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  1034. t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  1035. ksRow = ksRow + 3;
  1036. // Write
  1037. outputInt32[offset] = swapWord(t0 ^ initVector0);
  1038. outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
  1039. outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
  1040. outputInt32[offset + 3] = swapWord(t1 ^ initVector3);
  1041. // reset initVector to last 4 unsigned int
  1042. initVector0 = inputWords0;
  1043. initVector1 = inputWords1;
  1044. initVector2 = inputWords2;
  1045. initVector3 = inputWords3;
  1046. offset = offset + 4;
  1047. }
  1048. return outputInt32.buffer;
  1049. };
  1050. AESDecryptor.prototype.destroy = function destroy() {
  1051. this.key = undefined;
  1052. this.keySize = undefined;
  1053. this.ksRows = undefined;
  1054. this.sBox = undefined;
  1055. this.invSBox = undefined;
  1056. this.subMix = undefined;
  1057. this.invSubMix = undefined;
  1058. this.keySchedule = undefined;
  1059. this.invKeySchedule = undefined;
  1060. this.rcon = undefined;
  1061. };
  1062. return AESDecryptor;
  1063. }();
  1064. /* harmony default export */ var aes_decryptor = (AESDecryptor);
  1065. // EXTERNAL MODULE: ./src/errors.js
  1066. var errors = __webpack_require__(2);
  1067. // EXTERNAL MODULE: ./src/utils/logger.js
  1068. var logger = __webpack_require__(0);
  1069. // CONCATENATED MODULE: ./src/crypt/decrypter.js
  1070. function decrypter__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1071. /*globals self: false */
  1072. var decrypter_Decrypter = function () {
  1073. function Decrypter(observer, config) {
  1074. decrypter__classCallCheck(this, Decrypter);
  1075. this.observer = observer;
  1076. this.config = config;
  1077. this.logEnabled = true;
  1078. try {
  1079. var browserCrypto = crypto ? crypto : self.crypto;
  1080. this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
  1081. } catch (e) {}
  1082. this.disableWebCrypto = !this.subtle;
  1083. }
  1084. Decrypter.prototype.isSync = function isSync() {
  1085. return this.disableWebCrypto && this.config.enableSoftwareAES;
  1086. };
  1087. Decrypter.prototype.decrypt = function decrypt(data, key, iv, callback) {
  1088. var _this = this;
  1089. if (this.disableWebCrypto && this.config.enableSoftwareAES) {
  1090. if (this.logEnabled) {
  1091. logger["b" /* logger */].log('JS AES decrypt');
  1092. this.logEnabled = false;
  1093. }
  1094. var decryptor = this.decryptor;
  1095. if (!decryptor) {
  1096. this.decryptor = decryptor = new aes_decryptor();
  1097. }
  1098. decryptor.expandKey(key);
  1099. callback(decryptor.decrypt(data, 0, iv));
  1100. } else {
  1101. if (this.logEnabled) {
  1102. logger["b" /* logger */].log('WebCrypto AES decrypt');
  1103. this.logEnabled = false;
  1104. }
  1105. var subtle = this.subtle;
  1106. if (this.key !== key) {
  1107. this.key = key;
  1108. this.fastAesKey = new fast_aes_key(subtle, key);
  1109. }
  1110. this.fastAesKey.expandKey().then(function (aesKey) {
  1111. // decrypt using web crypto
  1112. var crypto = new aes_crypto(subtle, iv);
  1113. crypto.decrypt(data, aesKey).catch(function (err) {
  1114. _this.onWebCryptoError(err, data, key, iv, callback);
  1115. }).then(function (result) {
  1116. callback(result);
  1117. });
  1118. }).catch(function (err) {
  1119. _this.onWebCryptoError(err, data, key, iv, callback);
  1120. });
  1121. }
  1122. };
  1123. Decrypter.prototype.onWebCryptoError = function onWebCryptoError(err, data, key, iv, callback) {
  1124. if (this.config.enableSoftwareAES) {
  1125. logger["b" /* logger */].log('WebCrypto Error, disable WebCrypto API');
  1126. this.disableWebCrypto = true;
  1127. this.logEnabled = true;
  1128. this.decrypt(data, key, iv, callback);
  1129. } else {
  1130. logger["b" /* logger */].error('decrypting error : ' + err.message);
  1131. this.observer.trigger(Event.ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_DECRYPT_ERROR, fatal: true, reason: err.message });
  1132. }
  1133. };
  1134. Decrypter.prototype.destroy = function destroy() {
  1135. var decryptor = this.decryptor;
  1136. if (decryptor) {
  1137. decryptor.destroy();
  1138. this.decryptor = undefined;
  1139. }
  1140. };
  1141. return Decrypter;
  1142. }();
  1143. /* harmony default export */ var decrypter = __webpack_exports__["a"] = (decrypter_Decrypter);
  1144. /***/ }),
  1145. /* 6 */
  1146. /***/ (function(module, exports) {
  1147. // Copyright Joyent, Inc. and other Node contributors.
  1148. //
  1149. // Permission is hereby granted, free of charge, to any person obtaining a
  1150. // copy of this software and associated documentation files (the
  1151. // "Software"), to deal in the Software without restriction, including
  1152. // without limitation the rights to use, copy, modify, merge, publish,
  1153. // distribute, sublicense, and/or sell copies of the Software, and to permit
  1154. // persons to whom the Software is furnished to do so, subject to the
  1155. // following conditions:
  1156. //
  1157. // The above copyright notice and this permission notice shall be included
  1158. // in all copies or substantial portions of the Software.
  1159. //
  1160. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  1161. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  1162. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  1163. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  1164. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  1165. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  1166. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  1167. function EventEmitter() {
  1168. this._events = this._events || {};
  1169. this._maxListeners = this._maxListeners || undefined;
  1170. }
  1171. module.exports = EventEmitter;
  1172. // Backwards-compat with node 0.10.x
  1173. EventEmitter.EventEmitter = EventEmitter;
  1174. EventEmitter.prototype._events = undefined;
  1175. EventEmitter.prototype._maxListeners = undefined;
  1176. // By default EventEmitters will print a warning if more than 10 listeners are
  1177. // added to it. This is a useful default which helps finding memory leaks.
  1178. EventEmitter.defaultMaxListeners = 10;
  1179. // Obviously not all Emitters should be limited to 10. This function allows
  1180. // that to be increased. Set to zero for unlimited.
  1181. EventEmitter.prototype.setMaxListeners = function(n) {
  1182. if (!isNumber(n) || n < 0 || isNaN(n))
  1183. throw TypeError('n must be a positive number');
  1184. this._maxListeners = n;
  1185. return this;
  1186. };
  1187. EventEmitter.prototype.emit = function(type) {
  1188. var er, handler, len, args, i, listeners;
  1189. if (!this._events)
  1190. this._events = {};
  1191. // If there is no 'error' event listener then throw.
  1192. if (type === 'error') {
  1193. if (!this._events.error ||
  1194. (isObject(this._events.error) && !this._events.error.length)) {
  1195. er = arguments[1];
  1196. if (er instanceof Error) {
  1197. throw er; // Unhandled 'error' event
  1198. } else {
  1199. // At least give some kind of context to the user
  1200. var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
  1201. err.context = er;
  1202. throw err;
  1203. }
  1204. }
  1205. }
  1206. handler = this._events[type];
  1207. if (isUndefined(handler))
  1208. return false;
  1209. if (isFunction(handler)) {
  1210. switch (arguments.length) {
  1211. // fast cases
  1212. case 1:
  1213. handler.call(this);
  1214. break;
  1215. case 2:
  1216. handler.call(this, arguments[1]);
  1217. break;
  1218. case 3:
  1219. handler.call(this, arguments[1], arguments[2]);
  1220. break;
  1221. // slower
  1222. default:
  1223. args = Array.prototype.slice.call(arguments, 1);
  1224. handler.apply(this, args);
  1225. }
  1226. } else if (isObject(handler)) {
  1227. args = Array.prototype.slice.call(arguments, 1);
  1228. listeners = handler.slice();
  1229. len = listeners.length;
  1230. for (i = 0; i < len; i++)
  1231. listeners[i].apply(this, args);
  1232. }
  1233. return true;
  1234. };
  1235. EventEmitter.prototype.addListener = function(type, listener) {
  1236. var m;
  1237. if (!isFunction(listener))
  1238. throw TypeError('listener must be a function');
  1239. if (!this._events)
  1240. this._events = {};
  1241. // To avoid recursion in the case that type === "newListener"! Before
  1242. // adding it to the listeners, first emit "newListener".
  1243. if (this._events.newListener)
  1244. this.emit('newListener', type,
  1245. isFunction(listener.listener) ?
  1246. listener.listener : listener);
  1247. if (!this._events[type])
  1248. // Optimize the case of one listener. Don't need the extra array object.
  1249. this._events[type] = listener;
  1250. else if (isObject(this._events[type]))
  1251. // If we've already got an array, just append.
  1252. this._events[type].push(listener);
  1253. else
  1254. // Adding the second element, need to change to array.
  1255. this._events[type] = [this._events[type], listener];
  1256. // Check for listener leak
  1257. if (isObject(this._events[type]) && !this._events[type].warned) {
  1258. if (!isUndefined(this._maxListeners)) {
  1259. m = this._maxListeners;
  1260. } else {
  1261. m = EventEmitter.defaultMaxListeners;
  1262. }
  1263. if (m && m > 0 && this._events[type].length > m) {
  1264. this._events[type].warned = true;
  1265. console.error('(node) warning: possible EventEmitter memory ' +
  1266. 'leak detected. %d listeners added. ' +
  1267. 'Use emitter.setMaxListeners() to increase limit.',
  1268. this._events[type].length);
  1269. if (typeof console.trace === 'function') {
  1270. // not supported in IE 10
  1271. console.trace();
  1272. }
  1273. }
  1274. }
  1275. return this;
  1276. };
  1277. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  1278. EventEmitter.prototype.once = function(type, listener) {
  1279. if (!isFunction(listener))
  1280. throw TypeError('listener must be a function');
  1281. var fired = false;
  1282. function g() {
  1283. this.removeListener(type, g);
  1284. if (!fired) {
  1285. fired = true;
  1286. listener.apply(this, arguments);
  1287. }
  1288. }
  1289. g.listener = listener;
  1290. this.on(type, g);
  1291. return this;
  1292. };
  1293. // emits a 'removeListener' event iff the listener was removed
  1294. EventEmitter.prototype.removeListener = function(type, listener) {
  1295. var list, position, length, i;
  1296. if (!isFunction(listener))
  1297. throw TypeError('listener must be a function');
  1298. if (!this._events || !this._events[type])
  1299. return this;
  1300. list = this._events[type];
  1301. length = list.length;
  1302. position = -1;
  1303. if (list === listener ||
  1304. (isFunction(list.listener) && list.listener === listener)) {
  1305. delete this._events[type];
  1306. if (this._events.removeListener)
  1307. this.emit('removeListener', type, listener);
  1308. } else if (isObject(list)) {
  1309. for (i = length; i-- > 0;) {
  1310. if (list[i] === listener ||
  1311. (list[i].listener && list[i].listener === listener)) {
  1312. position = i;
  1313. break;
  1314. }
  1315. }
  1316. if (position < 0)
  1317. return this;
  1318. if (list.length === 1) {
  1319. list.length = 0;
  1320. delete this._events[type];
  1321. } else {
  1322. list.splice(position, 1);
  1323. }
  1324. if (this._events.removeListener)
  1325. this.emit('removeListener', type, listener);
  1326. }
  1327. return this;
  1328. };
  1329. EventEmitter.prototype.removeAllListeners = function(type) {
  1330. var key, listeners;
  1331. if (!this._events)
  1332. return this;
  1333. // not listening for removeListener, no need to emit
  1334. if (!this._events.removeListener) {
  1335. if (arguments.length === 0)
  1336. this._events = {};
  1337. else if (this._events[type])
  1338. delete this._events[type];
  1339. return this;
  1340. }
  1341. // emit removeListener for all listeners on all events
  1342. if (arguments.length === 0) {
  1343. for (key in this._events) {
  1344. if (key === 'removeListener') continue;
  1345. this.removeAllListeners(key);
  1346. }
  1347. this.removeAllListeners('removeListener');
  1348. this._events = {};
  1349. return this;
  1350. }
  1351. listeners = this._events[type];
  1352. if (isFunction(listeners)) {
  1353. this.removeListener(type, listeners);
  1354. } else if (listeners) {
  1355. // LIFO order
  1356. while (listeners.length)
  1357. this.removeListener(type, listeners[listeners.length - 1]);
  1358. }
  1359. delete this._events[type];
  1360. return this;
  1361. };
  1362. EventEmitter.prototype.listeners = function(type) {
  1363. var ret;
  1364. if (!this._events || !this._events[type])
  1365. ret = [];
  1366. else if (isFunction(this._events[type]))
  1367. ret = [this._events[type]];
  1368. else
  1369. ret = this._events[type].slice();
  1370. return ret;
  1371. };
  1372. EventEmitter.prototype.listenerCount = function(type) {
  1373. if (this._events) {
  1374. var evlistener = this._events[type];
  1375. if (isFunction(evlistener))
  1376. return 1;
  1377. else if (evlistener)
  1378. return evlistener.length;
  1379. }
  1380. return 0;
  1381. };
  1382. EventEmitter.listenerCount = function(emitter, type) {
  1383. return emitter.listenerCount(type);
  1384. };
  1385. function isFunction(arg) {
  1386. return typeof arg === 'function';
  1387. }
  1388. function isNumber(arg) {
  1389. return typeof arg === 'number';
  1390. }
  1391. function isObject(arg) {
  1392. return typeof arg === 'object' && arg !== null;
  1393. }
  1394. function isUndefined(arg) {
  1395. return arg === void 0;
  1396. }
  1397. /***/ }),
  1398. /* 7 */
  1399. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  1400. "use strict";
  1401. /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_logger__ = __webpack_require__(0);
  1402. /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__events__ = __webpack_require__(1);
  1403. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1404. /**
  1405. * MP4 demuxer
  1406. */
  1407. var UINT32_MAX = Math.pow(2, 32) - 1;
  1408. var MP4Demuxer = function () {
  1409. function MP4Demuxer(observer, remuxer) {
  1410. _classCallCheck(this, MP4Demuxer);
  1411. this.observer = observer;
  1412. this.remuxer = remuxer;
  1413. }
  1414. MP4Demuxer.prototype.resetTimeStamp = function resetTimeStamp(initPTS) {
  1415. this.initPTS = initPTS;
  1416. };
  1417. MP4Demuxer.prototype.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
  1418. //jshint unused:false
  1419. if (initSegment && initSegment.byteLength) {
  1420. var initData = this.initData = MP4Demuxer.parseInitSegment(initSegment);
  1421. // default audio codec if nothing specified
  1422. // TODO : extract that from initsegment
  1423. if (audioCodec == null) {
  1424. audioCodec = 'mp4a.40.5';
  1425. }
  1426. if (videoCodec == null) {
  1427. videoCodec = 'avc1.42e01e';
  1428. }
  1429. var tracks = {};
  1430. if (initData.audio && initData.video) {
  1431. tracks.audiovideo = { container: 'video/mp4', codec: audioCodec + ',' + videoCodec, initSegment: duration ? initSegment : null };
  1432. } else {
  1433. if (initData.audio) {
  1434. tracks.audio = { container: 'audio/mp4', codec: audioCodec, initSegment: duration ? initSegment : null };
  1435. }
  1436. if (initData.video) {
  1437. tracks.video = { container: 'video/mp4', codec: videoCodec, initSegment: duration ? initSegment : null };
  1438. }
  1439. }
  1440. this.observer.trigger(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].FRAG_PARSING_INIT_SEGMENT, { tracks: tracks });
  1441. } else {
  1442. if (audioCodec) {
  1443. this.audioCodec = audioCodec;
  1444. }
  1445. if (videoCodec) {
  1446. this.videoCodec = videoCodec;
  1447. }
  1448. }
  1449. };
  1450. MP4Demuxer.probe = function probe(data) {
  1451. // ensure we find a moof box in the first 16 kB
  1452. return MP4Demuxer.findBox({ data: data, start: 0, end: Math.min(data.length, 16384) }, ['moof']).length > 0;
  1453. };
  1454. MP4Demuxer.bin2str = function bin2str(buffer) {
  1455. return String.fromCharCode.apply(null, buffer);
  1456. };
  1457. MP4Demuxer.readUint16 = function readUint16(buffer, offset) {
  1458. if (buffer.data) {
  1459. offset += buffer.start;
  1460. buffer = buffer.data;
  1461. }
  1462. var val = buffer[offset] << 8 | buffer[offset + 1];
  1463. return val < 0 ? 65536 + val : val;
  1464. };
  1465. MP4Demuxer.readUint32 = function readUint32(buffer, offset) {
  1466. if (buffer.data) {
  1467. offset += buffer.start;
  1468. buffer = buffer.data;
  1469. }
  1470. var val = buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];
  1471. return val < 0 ? 4294967296 + val : val;
  1472. };
  1473. MP4Demuxer.writeUint32 = function writeUint32(buffer, offset, value) {
  1474. if (buffer.data) {
  1475. offset += buffer.start;
  1476. buffer = buffer.data;
  1477. }
  1478. buffer[offset] = value >> 24;
  1479. buffer[offset + 1] = value >> 16 & 0xff;
  1480. buffer[offset + 2] = value >> 8 & 0xff;
  1481. buffer[offset + 3] = value & 0xff;
  1482. };
  1483. // Find the data for a box specified by its path
  1484. MP4Demuxer.findBox = function findBox(data, path) {
  1485. var results = [],
  1486. i,
  1487. size,
  1488. type,
  1489. end,
  1490. subresults,
  1491. start,
  1492. endbox;
  1493. if (data.data) {
  1494. start = data.start;
  1495. end = data.end;
  1496. data = data.data;
  1497. } else {
  1498. start = 0;
  1499. end = data.byteLength;
  1500. }
  1501. if (!path.length) {
  1502. // short-circuit the search for empty paths
  1503. return null;
  1504. }
  1505. for (i = start; i < end;) {
  1506. size = MP4Demuxer.readUint32(data, i);
  1507. type = MP4Demuxer.bin2str(data.subarray(i + 4, i + 8));
  1508. endbox = size > 1 ? i + size : end;
  1509. if (type === path[0]) {
  1510. if (path.length === 1) {
  1511. // this is the end of the path and we've found the box we were
  1512. // looking for
  1513. results.push({ data: data, start: i + 8, end: endbox });
  1514. } else {
  1515. // recursively search for the next box along the path
  1516. subresults = MP4Demuxer.findBox({ data: data, start: i + 8, end: endbox }, path.slice(1));
  1517. if (subresults.length) {
  1518. results = results.concat(subresults);
  1519. }
  1520. }
  1521. }
  1522. i = endbox;
  1523. }
  1524. // we've finished searching all of data
  1525. return results;
  1526. };
  1527. MP4Demuxer.parseSegmentIndex = function parseSegmentIndex(initSegment) {
  1528. var moov = MP4Demuxer.findBox(initSegment, ['moov'])[0];
  1529. var moovEndOffset = moov ? moov.end : null; // we need this in case we need to chop of garbage of the end of current data
  1530. var index = 0;
  1531. var sidx = MP4Demuxer.findBox(initSegment, ['sidx']);
  1532. var references = void 0;
  1533. if (!sidx || !sidx[0]) {
  1534. return null;
  1535. }
  1536. references = [];
  1537. sidx = sidx[0];
  1538. var version = sidx.data[0];
  1539. // set initial offset, we skip the reference ID (not needed)
  1540. index = version === 0 ? 8 : 16;
  1541. var timescale = MP4Demuxer.readUint32(sidx, index);
  1542. index += 4;
  1543. // TODO: parse earliestPresentationTime and firstOffset
  1544. // usually zero in our case
  1545. var earliestPresentationTime = 0;
  1546. var firstOffset = 0;
  1547. if (version === 0) {
  1548. index += 8;
  1549. } else {
  1550. index += 16;
  1551. }
  1552. // skip reserved
  1553. index += 2;
  1554. var startByte = sidx.end + firstOffset;
  1555. var referencesCount = MP4Demuxer.readUint16(sidx, index);
  1556. index += 2;
  1557. for (var i = 0; i < referencesCount; i++) {
  1558. var referenceIndex = index;
  1559. var referenceInfo = MP4Demuxer.readUint32(sidx, referenceIndex);
  1560. referenceIndex += 4;
  1561. var referenceSize = referenceInfo & 0x7FFFFFFF;
  1562. var referenceType = (referenceInfo & 0x80000000) >>> 31;
  1563. if (referenceType === 1) {
  1564. console.warn('SIDX has hierarchical references (not supported)');
  1565. return;
  1566. }
  1567. var subsegmentDuration = MP4Demuxer.readUint32(sidx, referenceIndex);
  1568. referenceIndex += 4;
  1569. references.push({
  1570. referenceSize: referenceSize,
  1571. subsegmentDuration: subsegmentDuration, // unscaled
  1572. info: {
  1573. duration: subsegmentDuration / timescale,
  1574. start: startByte,
  1575. end: startByte + referenceSize - 1
  1576. }
  1577. });
  1578. startByte += referenceSize;
  1579. // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits
  1580. // for |sapDelta|.
  1581. referenceIndex += 4;
  1582. // skip to next ref
  1583. index = referenceIndex;
  1584. }
  1585. return {
  1586. earliestPresentationTime: earliestPresentationTime,
  1587. timescale: timescale,
  1588. version: version,
  1589. referencesCount: referencesCount,
  1590. references: references,
  1591. moovEndOffset: moovEndOffset
  1592. };
  1593. };
  1594. /**
  1595. * Parses an MP4 initialization segment and extracts stream type and
  1596. * timescale values for any declared tracks. Timescale values indicate the
  1597. * number of clock ticks per second to assume for time-based values
  1598. * elsewhere in the MP4.
  1599. *
  1600. * To determine the start time of an MP4, you need two pieces of
  1601. * information: the timescale unit and the earliest base media decode
  1602. * time. Multiple timescales can be specified within an MP4 but the
  1603. * base media decode time is always expressed in the timescale from
  1604. * the media header box for the track:
  1605. * ```
  1606. * moov > trak > mdia > mdhd.timescale
  1607. * moov > trak > mdia > hdlr
  1608. * ```
  1609. * @param init {Uint8Array} the bytes of the init segment
  1610. * @return {object} a hash of track type to timescale values or null if
  1611. * the init segment is malformed.
  1612. */
  1613. MP4Demuxer.parseInitSegment = function parseInitSegment(initSegment) {
  1614. var result = [];
  1615. var traks = MP4Demuxer.findBox(initSegment, ['moov', 'trak']);
  1616. traks.forEach(function (trak) {
  1617. var tkhd = MP4Demuxer.findBox(trak, ['tkhd'])[0];
  1618. if (tkhd) {
  1619. var version = tkhd.data[tkhd.start];
  1620. var index = version === 0 ? 12 : 20;
  1621. var trackId = MP4Demuxer.readUint32(tkhd, index);
  1622. var mdhd = MP4Demuxer.findBox(trak, ['mdia', 'mdhd'])[0];
  1623. if (mdhd) {
  1624. version = mdhd.data[mdhd.start];
  1625. index = version === 0 ? 12 : 20;
  1626. var timescale = MP4Demuxer.readUint32(mdhd, index);
  1627. var hdlr = MP4Demuxer.findBox(trak, ['mdia', 'hdlr'])[0];
  1628. if (hdlr) {
  1629. var hdlrType = MP4Demuxer.bin2str(hdlr.data.subarray(hdlr.start + 8, hdlr.start + 12));
  1630. var type = { 'soun': 'audio', 'vide': 'video' }[hdlrType];
  1631. if (type) {
  1632. // extract codec info. TODO : parse codec details to be able to build MIME type
  1633. var codecBox = MP4Demuxer.findBox(trak, ['mdia', 'minf', 'stbl', 'stsd']);
  1634. if (codecBox.length) {
  1635. codecBox = codecBox[0];
  1636. var codecType = MP4Demuxer.bin2str(codecBox.data.subarray(codecBox.start + 12, codecBox.start + 16));
  1637. __WEBPACK_IMPORTED_MODULE_0__utils_logger__["b" /* logger */].log('MP4Demuxer:' + type + ':' + codecType + ' found');
  1638. }
  1639. result[trackId] = { timescale: timescale, type: type };
  1640. result[type] = { timescale: timescale, id: trackId };
  1641. }
  1642. }
  1643. }
  1644. }
  1645. });
  1646. return result;
  1647. };
  1648. /**
  1649. * Determine the base media decode start time, in seconds, for an MP4
  1650. * fragment. If multiple fragments are specified, the earliest time is
  1651. * returned.
  1652. *
  1653. * The base media decode time can be parsed from track fragment
  1654. * metadata:
  1655. * ```
  1656. * moof > traf > tfdt.baseMediaDecodeTime
  1657. * ```
  1658. * It requires the timescale value from the mdhd to interpret.
  1659. *
  1660. * @param timescale {object} a hash of track ids to timescale values.
  1661. * @return {number} the earliest base media decode start time for the
  1662. * fragment, in seconds
  1663. */
  1664. MP4Demuxer.getStartDTS = function getStartDTS(initData, fragment) {
  1665. var trafs, baseTimes, result;
  1666. // we need info from two childrend of each track fragment box
  1667. trafs = MP4Demuxer.findBox(fragment, ['moof', 'traf']);
  1668. // determine the start times for each track
  1669. baseTimes = [].concat.apply([], trafs.map(function (traf) {
  1670. return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) {
  1671. var id, scale, baseTime;
  1672. // get the track id from the tfhd
  1673. id = MP4Demuxer.readUint32(tfhd, 4);
  1674. // assume a 90kHz clock if no timescale was specified
  1675. scale = initData[id].timescale || 90e3;
  1676. // get the base media decode time from the tfdt
  1677. baseTime = MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) {
  1678. var version, result;
  1679. version = tfdt.data[tfdt.start];
  1680. result = MP4Demuxer.readUint32(tfdt, 4);
  1681. if (version === 1) {
  1682. result *= Math.pow(2, 32);
  1683. result += MP4Demuxer.readUint32(tfdt, 8);
  1684. }
  1685. return result;
  1686. })[0];
  1687. // convert base time to seconds
  1688. return baseTime / scale;
  1689. });
  1690. }));
  1691. // return the minimum
  1692. result = Math.min.apply(null, baseTimes);
  1693. return isFinite(result) ? result : 0;
  1694. };
  1695. MP4Demuxer.offsetStartDTS = function offsetStartDTS(initData, fragment, timeOffset) {
  1696. MP4Demuxer.findBox(fragment, ['moof', 'traf']).map(function (traf) {
  1697. return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) {
  1698. // get the track id from the tfhd
  1699. var id = MP4Demuxer.readUint32(tfhd, 4);
  1700. // assume a 90kHz clock if no timescale was specified
  1701. var timescale = initData[id].timescale || 90e3;
  1702. // get the base media decode time from the tfdt
  1703. MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) {
  1704. var version = tfdt.data[tfdt.start];
  1705. var baseMediaDecodeTime = MP4Demuxer.readUint32(tfdt, 4);
  1706. if (version === 0) {
  1707. MP4Demuxer.writeUint32(tfdt, 4, baseMediaDecodeTime - timeOffset * timescale);
  1708. } else {
  1709. baseMediaDecodeTime *= Math.pow(2, 32);
  1710. baseMediaDecodeTime += MP4Demuxer.readUint32(tfdt, 8);
  1711. baseMediaDecodeTime -= timeOffset * timescale;
  1712. baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);
  1713. var upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
  1714. var lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
  1715. MP4Demuxer.writeUint32(tfdt, 4, upper);
  1716. MP4Demuxer.writeUint32(tfdt, 8, lower);
  1717. }
  1718. });
  1719. });
  1720. });
  1721. };
  1722. // feed incoming data to the front of the parsing pipeline
  1723. MP4Demuxer.prototype.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {
  1724. var initData = this.initData;
  1725. if (!initData) {
  1726. this.resetInitSegment(data, this.audioCodec, this.videoCodec, false);
  1727. initData = this.initData;
  1728. }
  1729. var startDTS = void 0,
  1730. initPTS = this.initPTS;
  1731. if (initPTS === undefined) {
  1732. var _startDTS = MP4Demuxer.getStartDTS(initData, data);
  1733. this.initPTS = initPTS = _startDTS - timeOffset;
  1734. this.observer.trigger(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].INIT_PTS_FOUND, { initPTS: initPTS });
  1735. }
  1736. MP4Demuxer.offsetStartDTS(initData, data, initPTS);
  1737. startDTS = MP4Demuxer.getStartDTS(initData, data);
  1738. this.remuxer.remux(initData.audio, initData.video, null, null, startDTS, contiguous, accurateTimeOffset, data);
  1739. };
  1740. MP4Demuxer.prototype.destroy = function destroy() {};
  1741. return MP4Demuxer;
  1742. }();
  1743. /* harmony default export */ __webpack_exports__["a"] = (MP4Demuxer);
  1744. /***/ }),
  1745. /* 8 */
  1746. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  1747. "use strict";
  1748. // EXTERNAL MODULE: ./src/events.js
  1749. var events = __webpack_require__(1);
  1750. // EXTERNAL MODULE: ./src/errors.js
  1751. var errors = __webpack_require__(2);
  1752. // EXTERNAL MODULE: ./src/crypt/decrypter.js + 3 modules
  1753. var crypt_decrypter = __webpack_require__(5);
  1754. // EXTERNAL MODULE: ./src/utils/logger.js
  1755. var logger = __webpack_require__(0);
  1756. // CONCATENATED MODULE: ./src/demux/adts.js
  1757. /**
  1758. * ADTS parser helper
  1759. */
  1760. function getAudioConfig(observer, data, offset, audioCodec) {
  1761. var adtsObjectType,
  1762. // :int
  1763. adtsSampleingIndex,
  1764. // :int
  1765. adtsExtensionSampleingIndex,
  1766. // :int
  1767. adtsChanelConfig,
  1768. // :int
  1769. config,
  1770. userAgent = navigator.userAgent.toLowerCase(),
  1771. manifestCodec = audioCodec,
  1772. adtsSampleingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  1773. // byte 2
  1774. adtsObjectType = ((data[offset + 2] & 0xC0) >>> 6) + 1;
  1775. adtsSampleingIndex = (data[offset + 2] & 0x3C) >>> 2;
  1776. if (adtsSampleingIndex > adtsSampleingRates.length - 1) {
  1777. observer.trigger(Event.ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_PARSING_ERROR, fatal: true, reason: 'invalid ADTS sampling index:' + adtsSampleingIndex });
  1778. return;
  1779. }
  1780. adtsChanelConfig = (data[offset + 2] & 0x01) << 2;
  1781. // byte 3
  1782. adtsChanelConfig |= (data[offset + 3] & 0xC0) >>> 6;
  1783. logger["b" /* logger */].log('manifest codec:' + audioCodec + ',ADTS data:type:' + adtsObjectType + ',sampleingIndex:' + adtsSampleingIndex + '[' + adtsSampleingRates[adtsSampleingIndex] + 'Hz],channelConfig:' + adtsChanelConfig);
  1784. // firefox: freq less than 24kHz = AAC SBR (HE-AAC)
  1785. if (/firefox/i.test(userAgent)) {
  1786. if (adtsSampleingIndex >= 6) {
  1787. adtsObjectType = 5;
  1788. config = new Array(4);
  1789. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  1790. // there is a factor 2 between frame sample rate and output sample rate
  1791. // multiply frequency by 2 (see table below, equivalent to substract 3)
  1792. adtsExtensionSampleingIndex = adtsSampleingIndex - 3;
  1793. } else {
  1794. adtsObjectType = 2;
  1795. config = new Array(2);
  1796. adtsExtensionSampleingIndex = adtsSampleingIndex;
  1797. }
  1798. // Android : always use AAC
  1799. } else if (userAgent.indexOf('android') !== -1) {
  1800. adtsObjectType = 2;
  1801. config = new Array(2);
  1802. adtsExtensionSampleingIndex = adtsSampleingIndex;
  1803. } else {
  1804. /* for other browsers (Chrome/Vivaldi/Opera ...)
  1805. always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)
  1806. */
  1807. adtsObjectType = 5;
  1808. config = new Array(4);
  1809. // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)
  1810. if (audioCodec && (audioCodec.indexOf('mp4a.40.29') !== -1 || audioCodec.indexOf('mp4a.40.5') !== -1) || !audioCodec && adtsSampleingIndex >= 6) {
  1811. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  1812. // there is a factor 2 between frame sample rate and output sample rate
  1813. // multiply frequency by 2 (see table below, equivalent to substract 3)
  1814. adtsExtensionSampleingIndex = adtsSampleingIndex - 3;
  1815. } else {
  1816. // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)
  1817. // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.
  1818. if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && (adtsSampleingIndex >= 6 && adtsChanelConfig === 1 || /vivaldi/i.test(userAgent)) || !audioCodec && adtsChanelConfig === 1) {
  1819. adtsObjectType = 2;
  1820. config = new Array(2);
  1821. }
  1822. adtsExtensionSampleingIndex = adtsSampleingIndex;
  1823. }
  1824. }
  1825. /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config
  1826. ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()
  1827. Audio Profile / Audio Object Type
  1828. 0: Null
  1829. 1: AAC Main
  1830. 2: AAC LC (Low Complexity)
  1831. 3: AAC SSR (Scalable Sample Rate)
  1832. 4: AAC LTP (Long Term Prediction)
  1833. 5: SBR (Spectral Band Replication)
  1834. 6: AAC Scalable
  1835. sampling freq
  1836. 0: 96000 Hz
  1837. 1: 88200 Hz
  1838. 2: 64000 Hz
  1839. 3: 48000 Hz
  1840. 4: 44100 Hz
  1841. 5: 32000 Hz
  1842. 6: 24000 Hz
  1843. 7: 22050 Hz
  1844. 8: 16000 Hz
  1845. 9: 12000 Hz
  1846. 10: 11025 Hz
  1847. 11: 8000 Hz
  1848. 12: 7350 Hz
  1849. 13: Reserved
  1850. 14: Reserved
  1851. 15: frequency is written explictly
  1852. Channel Configurations
  1853. These are the channel configurations:
  1854. 0: Defined in AOT Specifc Config
  1855. 1: 1 channel: front-center
  1856. 2: 2 channels: front-left, front-right
  1857. */
  1858. // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1
  1859. config[0] = adtsObjectType << 3;
  1860. // samplingFrequencyIndex
  1861. config[0] |= (adtsSampleingIndex & 0x0E) >> 1;
  1862. config[1] |= (adtsSampleingIndex & 0x01) << 7;
  1863. // channelConfiguration
  1864. config[1] |= adtsChanelConfig << 3;
  1865. if (adtsObjectType === 5) {
  1866. // adtsExtensionSampleingIndex
  1867. config[1] |= (adtsExtensionSampleingIndex & 0x0E) >> 1;
  1868. config[2] = (adtsExtensionSampleingIndex & 0x01) << 7;
  1869. // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???
  1870. // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc
  1871. config[2] |= 2 << 2;
  1872. config[3] = 0;
  1873. }
  1874. return { config: config, samplerate: adtsSampleingRates[adtsSampleingIndex], channelCount: adtsChanelConfig, codec: 'mp4a.40.' + adtsObjectType, manifestCodec: manifestCodec };
  1875. }
  1876. function isHeaderPattern(data, offset) {
  1877. return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;
  1878. }
  1879. function getHeaderLength(data, offset) {
  1880. return !!(data[offset + 1] & 0x01) ? 7 : 9;
  1881. }
  1882. function getFullFrameLength(data, offset) {
  1883. return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xE0) >>> 5;
  1884. }
  1885. function isHeader(data, offset) {
  1886. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  1887. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  1888. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  1889. if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
  1890. return true;
  1891. }
  1892. return false;
  1893. }
  1894. function adts_probe(data, offset) {
  1895. // same as isHeader but we also check that ADTS frame follows last ADTS frame
  1896. // or end of data is reached
  1897. if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
  1898. // ADTS header Length
  1899. var headerLength = getHeaderLength(data, offset);
  1900. // ADTS frame Length
  1901. var frameLength = headerLength;
  1902. if (offset + 5 < data.length) {
  1903. frameLength = getFullFrameLength(data, offset);
  1904. }
  1905. var newOffset = offset + frameLength;
  1906. if (newOffset === data.length || newOffset + 1 < data.length && isHeaderPattern(data, newOffset)) {
  1907. return true;
  1908. }
  1909. }
  1910. return false;
  1911. }
  1912. function initTrackConfig(track, observer, data, offset, audioCodec) {
  1913. if (!track.samplerate) {
  1914. var config = getAudioConfig(observer, data, offset, audioCodec);
  1915. track.config = config.config;
  1916. track.samplerate = config.samplerate;
  1917. track.channelCount = config.channelCount;
  1918. track.codec = config.codec;
  1919. track.manifestCodec = config.manifestCodec;
  1920. logger["b" /* logger */].log('parsed codec:' + track.codec + ',rate:' + config.samplerate + ',nb channel:' + config.channelCount);
  1921. }
  1922. }
  1923. function getFrameDuration(samplerate) {
  1924. return 1024 * 90000 / samplerate;
  1925. }
  1926. function parseFrameHeader(data, offset, pts, frameIndex, frameDuration) {
  1927. var headerLength, frameLength, stamp;
  1928. var length = data.length;
  1929. // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
  1930. headerLength = getHeaderLength(data, offset);
  1931. // retrieve frame size
  1932. frameLength = getFullFrameLength(data, offset);
  1933. frameLength -= headerLength;
  1934. if (frameLength > 0 && offset + headerLength + frameLength <= length) {
  1935. stamp = pts + frameIndex * frameDuration;
  1936. //logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
  1937. return { headerLength: headerLength, frameLength: frameLength, stamp: stamp };
  1938. }
  1939. return undefined;
  1940. }
  1941. function appendFrame(track, data, offset, pts, frameIndex) {
  1942. var frameDuration = getFrameDuration(track.samplerate);
  1943. var header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration);
  1944. if (header) {
  1945. var stamp = header.stamp;
  1946. var headerLength = header.headerLength;
  1947. var frameLength = header.frameLength;
  1948. //logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
  1949. var aacSample = {
  1950. unit: data.subarray(offset + headerLength, offset + headerLength + frameLength),
  1951. pts: stamp,
  1952. dts: stamp
  1953. };
  1954. track.samples.push(aacSample);
  1955. track.len += frameLength;
  1956. return { sample: aacSample, length: frameLength + headerLength };
  1957. }
  1958. return undefined;
  1959. }
  1960. // EXTERNAL MODULE: ./src/demux/id3.js
  1961. var id3 = __webpack_require__(4);
  1962. // CONCATENATED MODULE: ./src/demux/aacdemuxer.js
  1963. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1964. /**
  1965. * AAC demuxer
  1966. */
  1967. var aacdemuxer_AACDemuxer = function () {
  1968. function AACDemuxer(observer, remuxer, config) {
  1969. _classCallCheck(this, AACDemuxer);
  1970. this.observer = observer;
  1971. this.config = config;
  1972. this.remuxer = remuxer;
  1973. }
  1974. AACDemuxer.prototype.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
  1975. this._audioTrack = { container: 'audio/adts', type: 'audio', id: 0, sequenceNumber: 0, isAAC: true, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 };
  1976. };
  1977. AACDemuxer.prototype.resetTimeStamp = function resetTimeStamp() {};
  1978. AACDemuxer.probe = function probe(data) {
  1979. if (!data) {
  1980. return false;
  1981. }
  1982. // Check for the ADTS sync word
  1983. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  1984. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  1985. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  1986. var id3Data = id3["a" /* default */].getID3Data(data, 0) || [];
  1987. var offset = id3Data.length;
  1988. for (var length = data.length; offset < length; offset++) {
  1989. if (adts_probe(data, offset)) {
  1990. logger["b" /* logger */].log('ADTS sync word found !');
  1991. return true;
  1992. }
  1993. }
  1994. return false;
  1995. };
  1996. // feed incoming data to the front of the parsing pipeline
  1997. AACDemuxer.prototype.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {
  1998. var track = this._audioTrack;
  1999. var id3Data = id3["a" /* default */].getID3Data(data, 0) || [];
  2000. var timestamp = id3["a" /* default */].getTimeStamp(id3Data);
  2001. var pts = timestamp ? 90 * timestamp : timeOffset * 90000;
  2002. var frameIndex = 0;
  2003. var stamp = pts;
  2004. var length = data.length;
  2005. var offset = id3Data.length;
  2006. var id3Samples = [{ pts: stamp, dts: stamp, data: id3Data }];
  2007. while (offset < length - 1) {
  2008. if (isHeader(data, offset) && offset + 5 < length) {
  2009. initTrackConfig(track, this.observer, data, offset, track.manifestCodec);
  2010. var frame = appendFrame(track, data, offset, pts, frameIndex);
  2011. if (frame) {
  2012. offset += frame.length;
  2013. stamp = frame.sample.pts;
  2014. frameIndex++;
  2015. } else {
  2016. logger["b" /* logger */].log('Unable to parse AAC frame');
  2017. break;
  2018. }
  2019. } else if (id3["a" /* default */].isHeader(data, offset)) {
  2020. id3Data = id3["a" /* default */].getID3Data(data, offset);
  2021. id3Samples.push({ pts: stamp, dts: stamp, data: id3Data });
  2022. offset += id3Data.length;
  2023. } else {
  2024. //nothing found, keep looking
  2025. offset++;
  2026. }
  2027. }
  2028. this.remuxer.remux(track, { samples: [] }, { samples: id3Samples, inputTimeScale: 90000 }, { samples: [] }, timeOffset, contiguous, accurateTimeOffset);
  2029. };
  2030. AACDemuxer.prototype.destroy = function destroy() {};
  2031. return AACDemuxer;
  2032. }();
  2033. /* harmony default export */ var aacdemuxer = (aacdemuxer_AACDemuxer);
  2034. // EXTERNAL MODULE: ./src/demux/mp4demuxer.js
  2035. var mp4demuxer = __webpack_require__(7);
  2036. // CONCATENATED MODULE: ./src/demux/mpegaudio.js
  2037. /**
  2038. * MPEG parser helper
  2039. */
  2040. var MpegAudio = {
  2041. 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],
  2042. SamplingRateMap: [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000],
  2043. SamplesCoefficients: [
  2044. // MPEG 2.5
  2045. [0, // Reserved
  2046. 72, // Layer3
  2047. 144, // Layer2
  2048. 12 // Layer1
  2049. ],
  2050. // Reserved
  2051. [0, // Reserved
  2052. 0, // Layer3
  2053. 0, // Layer2
  2054. 0 // Layer1
  2055. ],
  2056. // MPEG 2
  2057. [0, // Reserved
  2058. 72, // Layer3
  2059. 144, // Layer2
  2060. 12 // Layer1
  2061. ],
  2062. // MPEG 1
  2063. [0, // Reserved
  2064. 144, // Layer3
  2065. 144, // Layer2
  2066. 12 // Layer1
  2067. ]],
  2068. BytesInSlot: [0, // Reserved
  2069. 1, // Layer3
  2070. 1, // Layer2
  2071. 4 // Layer1
  2072. ],
  2073. appendFrame: function appendFrame(track, data, offset, pts, frameIndex) {
  2074. // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference
  2075. if (offset + 24 > data.length) {
  2076. return undefined;
  2077. }
  2078. var header = this.parseHeader(data, offset);
  2079. if (header && offset + header.frameLength <= data.length) {
  2080. var frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;
  2081. var stamp = pts + frameIndex * frameDuration;
  2082. var sample = { unit: data.subarray(offset, offset + header.frameLength), pts: stamp, dts: stamp };
  2083. track.config = [];
  2084. track.channelCount = header.channelCount;
  2085. track.samplerate = header.sampleRate;
  2086. track.samples.push(sample);
  2087. track.len += header.frameLength;
  2088. return { sample: sample, length: header.frameLength };
  2089. }
  2090. return undefined;
  2091. },
  2092. parseHeader: function parseHeader(data, offset) {
  2093. var headerB = data[offset + 1] >> 3 & 3;
  2094. var headerC = data[offset + 1] >> 1 & 3;
  2095. var headerE = data[offset + 2] >> 4 & 15;
  2096. var headerF = data[offset + 2] >> 2 & 3;
  2097. var headerG = data[offset + 2] >> 1 & 1;
  2098. if (headerB !== 1 && headerE !== 0 && headerE !== 15 && headerF !== 3) {
  2099. var columnInBitrates = headerB === 3 ? 3 - headerC : headerC === 3 ? 3 : 4;
  2100. var bitRate = MpegAudio.BitratesMap[columnInBitrates * 14 + headerE - 1] * 1000;
  2101. var columnInSampleRates = headerB === 3 ? 0 : headerB === 2 ? 1 : 2;
  2102. var sampleRate = MpegAudio.SamplingRateMap[columnInSampleRates * 3 + headerF];
  2103. var channelCount = data[offset + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)
  2104. var sampleCoefficient = MpegAudio.SamplesCoefficients[headerB][headerC];
  2105. var bytesInSlot = MpegAudio.BytesInSlot[headerC];
  2106. var samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
  2107. var frameLength = parseInt(sampleCoefficient * bitRate / sampleRate + headerG, 10) * bytesInSlot;
  2108. return { sampleRate: sampleRate, channelCount: channelCount, frameLength: frameLength, samplesPerFrame: samplesPerFrame };
  2109. }
  2110. return undefined;
  2111. },
  2112. isHeaderPattern: function isHeaderPattern(data, offset) {
  2113. return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;
  2114. },
  2115. isHeader: function isHeader(data, offset) {
  2116. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  2117. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  2118. // More info http://www.mp3-tech.org/programmer/frame_header.html
  2119. if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {
  2120. return true;
  2121. }
  2122. return false;
  2123. },
  2124. probe: function probe(data, offset) {
  2125. // same as isHeader but we also check that MPEG frame follows last MPEG frame
  2126. // or end of data is reached
  2127. if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {
  2128. // MPEG header Length
  2129. var headerLength = 4;
  2130. // MPEG frame Length
  2131. var header = this.parseHeader(data, offset);
  2132. var frameLength = headerLength;
  2133. if (header && header.frameLength) {
  2134. frameLength = header.frameLength;
  2135. }
  2136. var newOffset = offset + frameLength;
  2137. if (newOffset === data.length || newOffset + 1 < data.length && this.isHeaderPattern(data, newOffset)) {
  2138. return true;
  2139. }
  2140. }
  2141. return false;
  2142. }
  2143. };
  2144. /* harmony default export */ var mpegaudio = (MpegAudio);
  2145. // CONCATENATED MODULE: ./src/demux/exp-golomb.js
  2146. function exp_golomb__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  2147. /**
  2148. * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
  2149. */
  2150. var exp_golomb_ExpGolomb = function () {
  2151. function ExpGolomb(data) {
  2152. exp_golomb__classCallCheck(this, ExpGolomb);
  2153. this.data = data;
  2154. // the number of bytes left to examine in this.data
  2155. this.bytesAvailable = data.byteLength;
  2156. // the current word being examined
  2157. this.word = 0; // :uint
  2158. // the number of bits left to examine in the current word
  2159. this.bitsAvailable = 0; // :uint
  2160. }
  2161. // ():void
  2162. ExpGolomb.prototype.loadWord = function loadWord() {
  2163. var data = this.data,
  2164. bytesAvailable = this.bytesAvailable,
  2165. position = data.byteLength - bytesAvailable,
  2166. workingBytes = new Uint8Array(4),
  2167. availableBytes = Math.min(4, bytesAvailable);
  2168. if (availableBytes === 0) {
  2169. throw new Error('no bytes available');
  2170. }
  2171. workingBytes.set(data.subarray(position, position + availableBytes));
  2172. this.word = new DataView(workingBytes.buffer).getUint32(0);
  2173. // track the amount of this.data that has been processed
  2174. this.bitsAvailable = availableBytes * 8;
  2175. this.bytesAvailable -= availableBytes;
  2176. };
  2177. // (count:int):void
  2178. ExpGolomb.prototype.skipBits = function skipBits(count) {
  2179. var skipBytes; // :int
  2180. if (this.bitsAvailable > count) {
  2181. this.word <<= count;
  2182. this.bitsAvailable -= count;
  2183. } else {
  2184. count -= this.bitsAvailable;
  2185. skipBytes = count >> 3;
  2186. count -= skipBytes >> 3;
  2187. this.bytesAvailable -= skipBytes;
  2188. this.loadWord();
  2189. this.word <<= count;
  2190. this.bitsAvailable -= count;
  2191. }
  2192. };
  2193. // (size:int):uint
  2194. ExpGolomb.prototype.readBits = function readBits(size) {
  2195. var bits = Math.min(this.bitsAvailable, size),
  2196. // :uint
  2197. valu = this.word >>> 32 - bits; // :uint
  2198. if (size > 32) {
  2199. logger["b" /* logger */].error('Cannot read more than 32 bits at a time');
  2200. }
  2201. this.bitsAvailable -= bits;
  2202. if (this.bitsAvailable > 0) {
  2203. this.word <<= bits;
  2204. } else if (this.bytesAvailable > 0) {
  2205. this.loadWord();
  2206. }
  2207. bits = size - bits;
  2208. if (bits > 0 && this.bitsAvailable) {
  2209. return valu << bits | this.readBits(bits);
  2210. } else {
  2211. return valu;
  2212. }
  2213. };
  2214. // ():uint
  2215. ExpGolomb.prototype.skipLZ = function skipLZ() {
  2216. var leadingZeroCount; // :uint
  2217. for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
  2218. if (0 !== (this.word & 0x80000000 >>> leadingZeroCount)) {
  2219. // the first bit of working word is 1
  2220. this.word <<= leadingZeroCount;
  2221. this.bitsAvailable -= leadingZeroCount;
  2222. return leadingZeroCount;
  2223. }
  2224. }
  2225. // we exhausted word and still have not found a 1
  2226. this.loadWord();
  2227. return leadingZeroCount + this.skipLZ();
  2228. };
  2229. // ():void
  2230. ExpGolomb.prototype.skipUEG = function skipUEG() {
  2231. this.skipBits(1 + this.skipLZ());
  2232. };
  2233. // ():void
  2234. ExpGolomb.prototype.skipEG = function skipEG() {
  2235. this.skipBits(1 + this.skipLZ());
  2236. };
  2237. // ():uint
  2238. ExpGolomb.prototype.readUEG = function readUEG() {
  2239. var clz = this.skipLZ(); // :uint
  2240. return this.readBits(clz + 1) - 1;
  2241. };
  2242. // ():int
  2243. ExpGolomb.prototype.readEG = function readEG() {
  2244. var valu = this.readUEG(); // :int
  2245. if (0x01 & valu) {
  2246. // the number is odd if the low order bit is set
  2247. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  2248. } else {
  2249. return -1 * (valu >>> 1); // divide by two then make it negative
  2250. }
  2251. };
  2252. // Some convenience functions
  2253. // :Boolean
  2254. ExpGolomb.prototype.readBoolean = function readBoolean() {
  2255. return 1 === this.readBits(1);
  2256. };
  2257. // ():int
  2258. ExpGolomb.prototype.readUByte = function readUByte() {
  2259. return this.readBits(8);
  2260. };
  2261. // ():int
  2262. ExpGolomb.prototype.readUShort = function readUShort() {
  2263. return this.readBits(16);
  2264. };
  2265. // ():int
  2266. ExpGolomb.prototype.readUInt = function readUInt() {
  2267. return this.readBits(32);
  2268. };
  2269. /**
  2270. * Advance the ExpGolomb decoder past a scaling list. The scaling
  2271. * list is optionally transmitted as part of a sequence parameter
  2272. * set and is not relevant to transmuxing.
  2273. * @param count {number} the number of entries in this scaling list
  2274. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  2275. */
  2276. ExpGolomb.prototype.skipScalingList = function skipScalingList(count) {
  2277. var lastScale = 8,
  2278. nextScale = 8,
  2279. j,
  2280. deltaScale;
  2281. for (j = 0; j < count; j++) {
  2282. if (nextScale !== 0) {
  2283. deltaScale = this.readEG();
  2284. nextScale = (lastScale + deltaScale + 256) % 256;
  2285. }
  2286. lastScale = nextScale === 0 ? lastScale : nextScale;
  2287. }
  2288. };
  2289. /**
  2290. * Read a sequence parameter set and return some interesting video
  2291. * properties. A sequence parameter set is the H264 metadata that
  2292. * describes the properties of upcoming video frames.
  2293. * @param data {Uint8Array} the bytes of a sequence parameter set
  2294. * @return {object} an object with configuration parsed from the
  2295. * sequence parameter set, including the dimensions of the
  2296. * associated video frames.
  2297. */
  2298. ExpGolomb.prototype.readSPS = function readSPS() {
  2299. var frameCropLeftOffset = 0,
  2300. frameCropRightOffset = 0,
  2301. frameCropTopOffset = 0,
  2302. frameCropBottomOffset = 0,
  2303. profileIdc,
  2304. profileCompat,
  2305. levelIdc,
  2306. numRefFramesInPicOrderCntCycle,
  2307. picWidthInMbsMinus1,
  2308. picHeightInMapUnitsMinus1,
  2309. frameMbsOnlyFlag,
  2310. scalingListCount,
  2311. i,
  2312. readUByte = this.readUByte.bind(this),
  2313. readBits = this.readBits.bind(this),
  2314. readUEG = this.readUEG.bind(this),
  2315. readBoolean = this.readBoolean.bind(this),
  2316. skipBits = this.skipBits.bind(this),
  2317. skipEG = this.skipEG.bind(this),
  2318. skipUEG = this.skipUEG.bind(this),
  2319. skipScalingList = this.skipScalingList.bind(this);
  2320. readUByte();
  2321. profileIdc = readUByte(); // profile_idc
  2322. profileCompat = readBits(5); // constraint_set[0-4]_flag, u(5)
  2323. skipBits(3); // reserved_zero_3bits u(3),
  2324. levelIdc = readUByte(); //level_idc u(8)
  2325. skipUEG(); // seq_parameter_set_id
  2326. // some profiles have more optional data we don't need
  2327. if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
  2328. var chromaFormatIdc = readUEG();
  2329. if (chromaFormatIdc === 3) {
  2330. skipBits(1); // separate_colour_plane_flag
  2331. }
  2332. skipUEG(); // bit_depth_luma_minus8
  2333. skipUEG(); // bit_depth_chroma_minus8
  2334. skipBits(1); // qpprime_y_zero_transform_bypass_flag
  2335. if (readBoolean()) {
  2336. // seq_scaling_matrix_present_flag
  2337. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  2338. for (i = 0; i < scalingListCount; i++) {
  2339. if (readBoolean()) {
  2340. // seq_scaling_list_present_flag[ i ]
  2341. if (i < 6) {
  2342. skipScalingList(16);
  2343. } else {
  2344. skipScalingList(64);
  2345. }
  2346. }
  2347. }
  2348. }
  2349. }
  2350. skipUEG(); // log2_max_frame_num_minus4
  2351. var picOrderCntType = readUEG();
  2352. if (picOrderCntType === 0) {
  2353. readUEG(); //log2_max_pic_order_cnt_lsb_minus4
  2354. } else if (picOrderCntType === 1) {
  2355. skipBits(1); // delta_pic_order_always_zero_flag
  2356. skipEG(); // offset_for_non_ref_pic
  2357. skipEG(); // offset_for_top_to_bottom_field
  2358. numRefFramesInPicOrderCntCycle = readUEG();
  2359. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  2360. skipEG(); // offset_for_ref_frame[ i ]
  2361. }
  2362. }
  2363. skipUEG(); // max_num_ref_frames
  2364. skipBits(1); // gaps_in_frame_num_value_allowed_flag
  2365. picWidthInMbsMinus1 = readUEG();
  2366. picHeightInMapUnitsMinus1 = readUEG();
  2367. frameMbsOnlyFlag = readBits(1);
  2368. if (frameMbsOnlyFlag === 0) {
  2369. skipBits(1); // mb_adaptive_frame_field_flag
  2370. }
  2371. skipBits(1); // direct_8x8_inference_flag
  2372. if (readBoolean()) {
  2373. // frame_cropping_flag
  2374. frameCropLeftOffset = readUEG();
  2375. frameCropRightOffset = readUEG();
  2376. frameCropTopOffset = readUEG();
  2377. frameCropBottomOffset = readUEG();
  2378. }
  2379. var pixelRatio = [1, 1];
  2380. if (readBoolean()) {
  2381. // vui_parameters_present_flag
  2382. if (readBoolean()) {
  2383. // aspect_ratio_info_present_flag
  2384. var aspectRatioIdc = readUByte();
  2385. switch (aspectRatioIdc) {
  2386. case 1:
  2387. pixelRatio = [1, 1];break;
  2388. case 2:
  2389. pixelRatio = [12, 11];break;
  2390. case 3:
  2391. pixelRatio = [10, 11];break;
  2392. case 4:
  2393. pixelRatio = [16, 11];break;
  2394. case 5:
  2395. pixelRatio = [40, 33];break;
  2396. case 6:
  2397. pixelRatio = [24, 11];break;
  2398. case 7:
  2399. pixelRatio = [20, 11];break;
  2400. case 8:
  2401. pixelRatio = [32, 11];break;
  2402. case 9:
  2403. pixelRatio = [80, 33];break;
  2404. case 10:
  2405. pixelRatio = [18, 11];break;
  2406. case 11:
  2407. pixelRatio = [15, 11];break;
  2408. case 12:
  2409. pixelRatio = [64, 33];break;
  2410. case 13:
  2411. pixelRatio = [160, 99];break;
  2412. case 14:
  2413. pixelRatio = [4, 3];break;
  2414. case 15:
  2415. pixelRatio = [3, 2];break;
  2416. case 16:
  2417. pixelRatio = [2, 1];break;
  2418. case 255:
  2419. {
  2420. pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
  2421. break;
  2422. }
  2423. }
  2424. }
  2425. }
  2426. return {
  2427. width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
  2428. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
  2429. pixelRatio: pixelRatio
  2430. };
  2431. };
  2432. ExpGolomb.prototype.readSliceType = function readSliceType() {
  2433. // skip NALu type
  2434. this.readUByte();
  2435. // discard first_mb_in_slice
  2436. this.readUEG();
  2437. // return slice_type
  2438. return this.readUEG();
  2439. };
  2440. return ExpGolomb;
  2441. }();
  2442. /* harmony default export */ var exp_golomb = (exp_golomb_ExpGolomb);
  2443. // CONCATENATED MODULE: ./src/demux/sample-aes.js
  2444. function sample_aes__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  2445. /**
  2446. * SAMPLE-AES decrypter
  2447. */
  2448. var sample_aes_SampleAesDecrypter = function () {
  2449. function SampleAesDecrypter(observer, config, decryptdata, discardEPB) {
  2450. sample_aes__classCallCheck(this, SampleAesDecrypter);
  2451. this.decryptdata = decryptdata;
  2452. this.discardEPB = discardEPB;
  2453. this.decrypter = new crypt_decrypter["a" /* default */](observer, config);
  2454. }
  2455. SampleAesDecrypter.prototype.decryptBuffer = function decryptBuffer(encryptedData, callback) {
  2456. this.decrypter.decrypt(encryptedData, this.decryptdata.key.buffer, this.decryptdata.iv.buffer, callback);
  2457. };
  2458. // AAC - encrypt all full 16 bytes blocks starting from offset 16
  2459. SampleAesDecrypter.prototype.decryptAacSample = function decryptAacSample(samples, sampleIndex, callback, sync) {
  2460. var curUnit = samples[sampleIndex].unit;
  2461. var encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
  2462. var encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
  2463. var localthis = this;
  2464. this.decryptBuffer(encryptedBuffer, function (decryptedData) {
  2465. decryptedData = new Uint8Array(decryptedData);
  2466. curUnit.set(decryptedData, 16);
  2467. if (!sync) {
  2468. localthis.decryptAacSamples(samples, sampleIndex + 1, callback);
  2469. }
  2470. });
  2471. };
  2472. SampleAesDecrypter.prototype.decryptAacSamples = function decryptAacSamples(samples, sampleIndex, callback) {
  2473. for (;; sampleIndex++) {
  2474. if (sampleIndex >= samples.length) {
  2475. callback();
  2476. return;
  2477. }
  2478. if (samples[sampleIndex].unit.length < 32) {
  2479. continue;
  2480. }
  2481. var sync = this.decrypter.isSync();
  2482. this.decryptAacSample(samples, sampleIndex, callback, sync);
  2483. if (!sync) {
  2484. return;
  2485. }
  2486. }
  2487. };
  2488. // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
  2489. SampleAesDecrypter.prototype.getAvcEncryptedData = function getAvcEncryptedData(decodedData) {
  2490. var encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
  2491. var encryptedData = new Int8Array(encryptedDataLen);
  2492. var outputPos = 0;
  2493. for (var inputPos = 32; inputPos <= decodedData.length - 16; inputPos += 160, outputPos += 16) {
  2494. encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
  2495. }
  2496. return encryptedData;
  2497. };
  2498. SampleAesDecrypter.prototype.getAvcDecryptedUnit = function getAvcDecryptedUnit(decodedData, decryptedData) {
  2499. decryptedData = new Uint8Array(decryptedData);
  2500. var inputPos = 0;
  2501. for (var outputPos = 32; outputPos <= decodedData.length - 16; outputPos += 160, inputPos += 16) {
  2502. decodedData.set(decryptedData.subarray(inputPos, inputPos + 16), outputPos);
  2503. }
  2504. return decodedData;
  2505. };
  2506. SampleAesDecrypter.prototype.decryptAvcSample = function decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync) {
  2507. var decodedData = this.discardEPB(curUnit.data);
  2508. var encryptedData = this.getAvcEncryptedData(decodedData);
  2509. var localthis = this;
  2510. this.decryptBuffer(encryptedData.buffer, function (decryptedData) {
  2511. curUnit.data = localthis.getAvcDecryptedUnit(decodedData, decryptedData);
  2512. if (!sync) {
  2513. localthis.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
  2514. }
  2515. });
  2516. };
  2517. SampleAesDecrypter.prototype.decryptAvcSamples = function decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
  2518. for (;; sampleIndex++, unitIndex = 0) {
  2519. if (sampleIndex >= samples.length) {
  2520. callback();
  2521. return;
  2522. }
  2523. var curUnits = samples[sampleIndex].units;
  2524. for (;; unitIndex++) {
  2525. if (unitIndex >= curUnits.length) {
  2526. break;
  2527. }
  2528. var curUnit = curUnits[unitIndex];
  2529. if (curUnit.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
  2530. continue;
  2531. }
  2532. var sync = this.decrypter.isSync();
  2533. this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync);
  2534. if (!sync) {
  2535. return;
  2536. }
  2537. }
  2538. }
  2539. };
  2540. return SampleAesDecrypter;
  2541. }();
  2542. /* harmony default export */ var sample_aes = (sample_aes_SampleAesDecrypter);
  2543. // CONCATENATED MODULE: ./src/demux/tsdemuxer.js
  2544. function tsdemuxer__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  2545. /**
  2546. * highly optimized TS demuxer:
  2547. * parse PAT, PMT
  2548. * extract PES packet from audio and video PIDs
  2549. * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet
  2550. * trigger the remuxer upon parsing completion
  2551. * 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.
  2552. * it also controls the remuxing process :
  2553. * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.
  2554. */
  2555. // import Hex from '../utils/hex';
  2556. // We are using fixed track IDs for driving the MP4 remuxer
  2557. // instead of following the TS PIDs.
  2558. // There is no reason not to do this and some browsers/SourceBuffer-demuxers
  2559. // may not like if there are TrackID "switches"
  2560. // See https://github.com/video-dev/hls.js/issues/1331
  2561. // Here we are mapping our internal track types to constant MP4 track IDs
  2562. // With MSE currently one can only have one track of each, and we are muxing
  2563. // whatever video/audio rendition in them.
  2564. var RemuxerTrackIdConfig = {
  2565. video: 0,
  2566. audio: 1,
  2567. id3: 2,
  2568. text: 3
  2569. };
  2570. var tsdemuxer_TSDemuxer = function () {
  2571. function TSDemuxer(observer, remuxer, config, typeSupported) {
  2572. tsdemuxer__classCallCheck(this, TSDemuxer);
  2573. this.observer = observer;
  2574. this.config = config;
  2575. this.typeSupported = typeSupported;
  2576. this.remuxer = remuxer;
  2577. this.sampleAes = null;
  2578. }
  2579. TSDemuxer.prototype.setDecryptData = function setDecryptData(decryptdata) {
  2580. if (decryptdata != null && decryptdata.key != null && decryptdata.method === 'SAMPLE-AES') {
  2581. this.sampleAes = new sample_aes(this.observer, this.config, decryptdata, this.discardEPB);
  2582. } else {
  2583. this.sampleAes = null;
  2584. }
  2585. };
  2586. TSDemuxer.probe = function probe(data) {
  2587. var syncOffset = TSDemuxer._syncOffset(data);
  2588. if (syncOffset < 0) {
  2589. return false;
  2590. } else {
  2591. if (syncOffset) {
  2592. logger["b" /* logger */].warn('MPEG2-TS detected but first sync word found @ offset ' + syncOffset + ', junk ahead ?');
  2593. }
  2594. return true;
  2595. }
  2596. };
  2597. TSDemuxer._syncOffset = function _syncOffset(data) {
  2598. // scan 1000 first bytes
  2599. var scanwindow = Math.min(1000, data.length - 3 * 188);
  2600. var i = 0;
  2601. while (i < scanwindow) {
  2602. // a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47
  2603. if (data[i] === 0x47 && data[i + 188] === 0x47 && data[i + 2 * 188] === 0x47) {
  2604. return i;
  2605. } else {
  2606. i++;
  2607. }
  2608. }
  2609. return -1;
  2610. };
  2611. /**
  2612. * Creates a track model internal to demuxer used to drive remuxing input
  2613. *
  2614. * @param {string} type 'audio' | 'video' | 'id3' | 'text'
  2615. * @param {number} duration
  2616. * @return {object} TSDemuxer's internal track model
  2617. */
  2618. TSDemuxer.createTrack = function createTrack(type, duration) {
  2619. return {
  2620. container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,
  2621. type: type,
  2622. id: RemuxerTrackIdConfig[type],
  2623. pid: -1,
  2624. inputTimeScale: 90000,
  2625. sequenceNumber: 0,
  2626. samples: [],
  2627. len: 0,
  2628. dropped: type === 'video' ? 0 : undefined,
  2629. isAAC: type === 'audio' ? true : undefined,
  2630. duration: type === 'audio' ? duration : undefined
  2631. };
  2632. };
  2633. /**
  2634. * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
  2635. * Resets all internal track instances of the demuxer.
  2636. *
  2637. * @override Implements generic demuxing/remuxing interface (see DemuxerInline)
  2638. * @param {object} initSegment
  2639. * @param {string} audioCodec
  2640. * @param {string} videoCodec
  2641. * @param {number} duration (in TS timescale = 90kHz)
  2642. */
  2643. TSDemuxer.prototype.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
  2644. this.pmtParsed = false;
  2645. this._pmtId = -1;
  2646. this._avcTrack = TSDemuxer.createTrack('video', duration);
  2647. this._audioTrack = TSDemuxer.createTrack('audio', duration);
  2648. this._id3Track = TSDemuxer.createTrack('id3', duration);
  2649. this._txtTrack = TSDemuxer.createTrack('text', duration);
  2650. // flush any partial content
  2651. this.aacOverFlow = null;
  2652. this.aacLastPTS = null;
  2653. this.avcSample = null;
  2654. this.audioCodec = audioCodec;
  2655. this.videoCodec = videoCodec;
  2656. this._duration = duration;
  2657. };
  2658. /**
  2659. *
  2660. * @override
  2661. */
  2662. TSDemuxer.prototype.resetTimeStamp = function resetTimeStamp() {};
  2663. // feed incoming data to the front of the parsing pipeline
  2664. TSDemuxer.prototype.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {
  2665. var start,
  2666. len = data.length,
  2667. stt,
  2668. pid,
  2669. atf,
  2670. offset,
  2671. pes,
  2672. unknownPIDs = false;
  2673. this.contiguous = contiguous;
  2674. var pmtParsed = this.pmtParsed,
  2675. avcTrack = this._avcTrack,
  2676. audioTrack = this._audioTrack,
  2677. id3Track = this._id3Track,
  2678. avcId = avcTrack.pid,
  2679. audioId = audioTrack.pid,
  2680. id3Id = id3Track.pid,
  2681. pmtId = this._pmtId,
  2682. avcData = avcTrack.pesData,
  2683. audioData = audioTrack.pesData,
  2684. id3Data = id3Track.pesData,
  2685. parsePAT = this._parsePAT,
  2686. parsePMT = this._parsePMT,
  2687. parsePES = this._parsePES,
  2688. parseAVCPES = this._parseAVCPES.bind(this),
  2689. parseAACPES = this._parseAACPES.bind(this),
  2690. parseMPEGPES = this._parseMPEGPES.bind(this),
  2691. parseID3PES = this._parseID3PES.bind(this);
  2692. var syncOffset = TSDemuxer._syncOffset(data);
  2693. // don't parse last TS packet if incomplete
  2694. len -= (len + syncOffset) % 188;
  2695. // loop through TS packets
  2696. for (start = syncOffset; start < len; start += 188) {
  2697. if (data[start] === 0x47) {
  2698. stt = !!(data[start + 1] & 0x40);
  2699. // pid is a 13-bit field starting at the last bit of TS[1]
  2700. pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];
  2701. atf = (data[start + 3] & 0x30) >> 4;
  2702. // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.
  2703. if (atf > 1) {
  2704. offset = start + 5 + data[start + 4];
  2705. // continue if there is only adaptation field
  2706. if (offset === start + 188) {
  2707. continue;
  2708. }
  2709. } else {
  2710. offset = start + 4;
  2711. }
  2712. switch (pid) {
  2713. case avcId:
  2714. if (stt) {
  2715. if (avcData && (pes = parsePES(avcData))) {
  2716. parseAVCPES(pes, false);
  2717. }
  2718. avcData = { data: [], size: 0 };
  2719. }
  2720. if (avcData) {
  2721. avcData.data.push(data.subarray(offset, start + 188));
  2722. avcData.size += start + 188 - offset;
  2723. }
  2724. break;
  2725. case audioId:
  2726. if (stt) {
  2727. if (audioData && (pes = parsePES(audioData))) {
  2728. if (audioTrack.isAAC) {
  2729. parseAACPES(pes);
  2730. } else {
  2731. parseMPEGPES(pes);
  2732. }
  2733. }
  2734. audioData = { data: [], size: 0 };
  2735. }
  2736. if (audioData) {
  2737. audioData.data.push(data.subarray(offset, start + 188));
  2738. audioData.size += start + 188 - offset;
  2739. }
  2740. break;
  2741. case id3Id:
  2742. if (stt) {
  2743. if (id3Data && (pes = parsePES(id3Data))) {
  2744. parseID3PES(pes);
  2745. }
  2746. id3Data = { data: [], size: 0 };
  2747. }
  2748. if (id3Data) {
  2749. id3Data.data.push(data.subarray(offset, start + 188));
  2750. id3Data.size += start + 188 - offset;
  2751. }
  2752. break;
  2753. case 0:
  2754. if (stt) {
  2755. offset += data[offset] + 1;
  2756. }
  2757. pmtId = this._pmtId = parsePAT(data, offset);
  2758. break;
  2759. case pmtId:
  2760. if (stt) {
  2761. offset += data[offset] + 1;
  2762. }
  2763. var parsedPIDs = parsePMT(data, offset, this.typeSupported.mpeg === true || this.typeSupported.mp3 === true, this.sampleAes != null);
  2764. // only update track id if track PID found while parsing PMT
  2765. // this is to avoid resetting the PID to -1 in case
  2766. // track PID transiently disappears from the stream
  2767. // this could happen in case of transient missing audio samples for example
  2768. // NOTE this is only the PID of the track as found in TS,
  2769. // but we are not using this for MP4 track IDs.
  2770. avcId = parsedPIDs.avc;
  2771. if (avcId > 0) {
  2772. avcTrack.pid = avcId;
  2773. }
  2774. audioId = parsedPIDs.audio;
  2775. if (audioId > 0) {
  2776. audioTrack.pid = audioId;
  2777. audioTrack.isAAC = parsedPIDs.isAAC;
  2778. }
  2779. id3Id = parsedPIDs.id3;
  2780. if (id3Id > 0) {
  2781. id3Track.pid = id3Id;
  2782. }
  2783. if (unknownPIDs && !pmtParsed) {
  2784. logger["b" /* logger */].log('reparse from beginning');
  2785. unknownPIDs = false;
  2786. // we set it to -188, the += 188 in the for loop will reset start to 0
  2787. start = syncOffset - 188;
  2788. }
  2789. pmtParsed = this.pmtParsed = true;
  2790. break;
  2791. case 17:
  2792. case 0x1fff:
  2793. break;
  2794. default:
  2795. unknownPIDs = true;
  2796. break;
  2797. }
  2798. } else {
  2799. this.observer.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_PARSING_ERROR, fatal: false, reason: 'TS packet did not start with 0x47' });
  2800. }
  2801. }
  2802. // try to parse last PES packets
  2803. if (avcData && (pes = parsePES(avcData))) {
  2804. parseAVCPES(pes, true);
  2805. avcTrack.pesData = null;
  2806. } else {
  2807. // either avcData null or PES truncated, keep it for next frag parsing
  2808. avcTrack.pesData = avcData;
  2809. }
  2810. if (audioData && (pes = parsePES(audioData))) {
  2811. if (audioTrack.isAAC) {
  2812. parseAACPES(pes);
  2813. } else {
  2814. parseMPEGPES(pes);
  2815. }
  2816. audioTrack.pesData = null;
  2817. } else {
  2818. if (audioData && audioData.size) {
  2819. logger["b" /* logger */].log('last AAC PES packet truncated,might overlap between fragments');
  2820. }
  2821. // either audioData null or PES truncated, keep it for next frag parsing
  2822. audioTrack.pesData = audioData;
  2823. }
  2824. if (id3Data && (pes = parsePES(id3Data))) {
  2825. parseID3PES(pes);
  2826. id3Track.pesData = null;
  2827. } else {
  2828. // either id3Data null or PES truncated, keep it for next frag parsing
  2829. id3Track.pesData = id3Data;
  2830. }
  2831. if (this.sampleAes == null) {
  2832. this.remuxer.remux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);
  2833. } else {
  2834. this.decryptAndRemux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);
  2835. }
  2836. };
  2837. TSDemuxer.prototype.decryptAndRemux = function decryptAndRemux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
  2838. if (audioTrack.samples && audioTrack.isAAC) {
  2839. var localthis = this;
  2840. this.sampleAes.decryptAacSamples(audioTrack.samples, 0, function () {
  2841. localthis.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
  2842. });
  2843. } else {
  2844. this.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
  2845. }
  2846. };
  2847. TSDemuxer.prototype.decryptAndRemuxAvc = function decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
  2848. if (videoTrack.samples) {
  2849. var localthis = this;
  2850. this.sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, function () {
  2851. localthis.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
  2852. });
  2853. } else {
  2854. this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
  2855. }
  2856. };
  2857. TSDemuxer.prototype.destroy = function destroy() {
  2858. this._initPTS = this._initDTS = undefined;
  2859. this._duration = 0;
  2860. };
  2861. TSDemuxer.prototype._parsePAT = function _parsePAT(data, offset) {
  2862. // skip the PSI header and parse the first PMT entry
  2863. return (data[offset + 10] & 0x1F) << 8 | data[offset + 11];
  2864. //logger.log('PMT PID:' + this._pmtId);
  2865. };
  2866. TSDemuxer.prototype._parsePMT = function _parsePMT(data, offset, mpegSupported, isSampleAes) {
  2867. var sectionLength,
  2868. tableEnd,
  2869. programInfoLength,
  2870. pid,
  2871. result = { audio: -1, avc: -1, id3: -1, isAAC: true };
  2872. sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
  2873. tableEnd = offset + 3 + sectionLength - 4;
  2874. // to determine where the table is, we have to figure out how
  2875. // long the program info descriptors are
  2876. programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11];
  2877. // advance the offset to the first entry in the mapping table
  2878. offset += 12 + programInfoLength;
  2879. while (offset < tableEnd) {
  2880. pid = (data[offset + 1] & 0x1F) << 8 | data[offset + 2];
  2881. switch (data[offset]) {
  2882. case 0xcf:
  2883. // SAMPLE-AES AAC
  2884. if (!isSampleAes) {
  2885. logger["b" /* logger */].log('unkown stream type:' + data[offset]);
  2886. break;
  2887. }
  2888. /* falls through */
  2889. // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
  2890. case 0x0f:
  2891. //logger.log('AAC PID:' + pid);
  2892. if (result.audio === -1) {
  2893. result.audio = pid;
  2894. }
  2895. break;
  2896. // Packetized metadata (ID3)
  2897. case 0x15:
  2898. //logger.log('ID3 PID:' + pid);
  2899. if (result.id3 === -1) {
  2900. result.id3 = pid;
  2901. }
  2902. break;
  2903. case 0xdb:
  2904. // SAMPLE-AES AVC
  2905. if (!isSampleAes) {
  2906. logger["b" /* logger */].log('unkown stream type:' + data[offset]);
  2907. break;
  2908. }
  2909. /* falls through */
  2910. // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
  2911. case 0x1b:
  2912. //logger.log('AVC PID:' + pid);
  2913. if (result.avc === -1) {
  2914. result.avc = pid;
  2915. }
  2916. break;
  2917. // ISO/IEC 11172-3 (MPEG-1 audio)
  2918. // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)
  2919. case 0x03:
  2920. case 0x04:
  2921. //logger.log('MPEG PID:' + pid);
  2922. if (!mpegSupported) {
  2923. logger["b" /* logger */].log('MPEG audio found, not supported in this browser for now');
  2924. } else if (result.audio === -1) {
  2925. result.audio = pid;
  2926. result.isAAC = false;
  2927. }
  2928. break;
  2929. case 0x24:
  2930. logger["b" /* logger */].warn('HEVC stream type found, not supported for now');
  2931. break;
  2932. default:
  2933. logger["b" /* logger */].log('unkown stream type:' + data[offset]);
  2934. break;
  2935. }
  2936. // move to the next table entry
  2937. // skip past the elementary stream descriptors, if present
  2938. offset += ((data[offset + 3] & 0x0F) << 8 | data[offset + 4]) + 5;
  2939. }
  2940. return result;
  2941. };
  2942. TSDemuxer.prototype._parsePES = function _parsePES(stream) {
  2943. var i = 0,
  2944. frag,
  2945. pesFlags,
  2946. pesPrefix,
  2947. pesLen,
  2948. pesHdrLen,
  2949. pesData,
  2950. pesPts,
  2951. pesDts,
  2952. payloadStartOffset,
  2953. data = stream.data;
  2954. // safety check
  2955. if (!stream || stream.size === 0) {
  2956. return null;
  2957. }
  2958. // we might need up to 19 bytes to read PES header
  2959. // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes
  2960. // usually only one merge is needed (and this is rare ...)
  2961. while (data[0].length < 19 && data.length > 1) {
  2962. var newData = new Uint8Array(data[0].length + data[1].length);
  2963. newData.set(data[0]);
  2964. newData.set(data[1], data[0].length);
  2965. data[0] = newData;
  2966. data.splice(1, 1);
  2967. }
  2968. //retrieve PTS/DTS from first fragment
  2969. frag = data[0];
  2970. pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
  2971. if (pesPrefix === 1) {
  2972. pesLen = (frag[4] << 8) + frag[5];
  2973. // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated
  2974. // minus 6 : PES header size
  2975. if (pesLen && pesLen > stream.size - 6) {
  2976. return null;
  2977. }
  2978. pesFlags = frag[7];
  2979. if (pesFlags & 0xC0) {
  2980. /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  2981. as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
  2982. as Bitwise operators treat their operands as a sequence of 32 bits */
  2983. pesPts = (frag[9] & 0x0E) * 536870912 + // 1 << 29
  2984. (frag[10] & 0xFF) * 4194304 + // 1 << 22
  2985. (frag[11] & 0xFE) * 16384 + // 1 << 14
  2986. (frag[12] & 0xFF) * 128 + // 1 << 7
  2987. (frag[13] & 0xFE) / 2;
  2988. // check if greater than 2^32 -1
  2989. if (pesPts > 4294967295) {
  2990. // decrement 2^33
  2991. pesPts -= 8589934592;
  2992. }
  2993. if (pesFlags & 0x40) {
  2994. pesDts = (frag[14] & 0x0E) * 536870912 + // 1 << 29
  2995. (frag[15] & 0xFF) * 4194304 + // 1 << 22
  2996. (frag[16] & 0xFE) * 16384 + // 1 << 14
  2997. (frag[17] & 0xFF) * 128 + // 1 << 7
  2998. (frag[18] & 0xFE) / 2;
  2999. // check if greater than 2^32 -1
  3000. if (pesDts > 4294967295) {
  3001. // decrement 2^33
  3002. pesDts -= 8589934592;
  3003. }
  3004. if (pesPts - pesDts > 60 * 90000) {
  3005. logger["b" /* logger */].warn(Math.round((pesPts - pesDts) / 90000) + 's delta between PTS and DTS, align them');
  3006. pesPts = pesDts;
  3007. }
  3008. } else {
  3009. pesDts = pesPts;
  3010. }
  3011. }
  3012. pesHdrLen = frag[8];
  3013. // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension
  3014. payloadStartOffset = pesHdrLen + 9;
  3015. stream.size -= payloadStartOffset;
  3016. //reassemble PES packet
  3017. pesData = new Uint8Array(stream.size);
  3018. for (var j = 0, dataLen = data.length; j < dataLen; j++) {
  3019. frag = data[j];
  3020. var len = frag.byteLength;
  3021. if (payloadStartOffset) {
  3022. if (payloadStartOffset > len) {
  3023. // trim full frag if PES header bigger than frag
  3024. payloadStartOffset -= len;
  3025. continue;
  3026. } else {
  3027. // trim partial frag if PES header smaller than frag
  3028. frag = frag.subarray(payloadStartOffset);
  3029. len -= payloadStartOffset;
  3030. payloadStartOffset = 0;
  3031. }
  3032. }
  3033. pesData.set(frag, i);
  3034. i += len;
  3035. }
  3036. if (pesLen) {
  3037. // payload size : remove PES header + PES extension
  3038. pesLen -= pesHdrLen + 3;
  3039. }
  3040. return { data: pesData, pts: pesPts, dts: pesDts, len: pesLen };
  3041. } else {
  3042. return null;
  3043. }
  3044. };
  3045. TSDemuxer.prototype.pushAccesUnit = function pushAccesUnit(avcSample, avcTrack) {
  3046. if (avcSample.units.length && avcSample.frame) {
  3047. var samples = avcTrack.samples;
  3048. var nbSamples = samples.length;
  3049. // only push AVC sample if starting with a keyframe is not mandatory OR
  3050. // if keyframe already found in this fragment OR
  3051. // keyframe found in last fragment (track.sps) AND
  3052. // samples already appended (we already found a keyframe in this fragment) OR fragment is contiguous
  3053. if (!this.config.forceKeyFrameOnDiscontinuity || avcSample.key === true || avcTrack.sps && (nbSamples || this.contiguous)) {
  3054. avcSample.id = nbSamples;
  3055. samples.push(avcSample);
  3056. } else {
  3057. // dropped samples, track it
  3058. avcTrack.dropped++;
  3059. }
  3060. }
  3061. if (avcSample.debug.length) {
  3062. logger["b" /* logger */].log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug);
  3063. }
  3064. };
  3065. TSDemuxer.prototype._parseAVCPES = function _parseAVCPES(pes, last) {
  3066. var _this = this;
  3067. //logger.log('parse new PES');
  3068. var track = this._avcTrack,
  3069. units = this._parseAVCNALu(pes.data),
  3070. debug = false,
  3071. expGolombDecoder,
  3072. avcSample = this.avcSample,
  3073. push,
  3074. spsfound = false,
  3075. i,
  3076. pushAccesUnit = this.pushAccesUnit.bind(this),
  3077. createAVCSample = function createAVCSample(key, pts, dts, debug) {
  3078. return { key: key, pts: pts, dts: dts, units: [], debug: debug };
  3079. };
  3080. //free pes.data to save up some memory
  3081. pes.data = null;
  3082. // if new NAL units found and last sample still there, let's push ...
  3083. // this helps parsing streams with missing AUD (only do this if AUD never found)
  3084. if (avcSample && units.length && !track.audFound) {
  3085. pushAccesUnit(avcSample, track);
  3086. avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, '');
  3087. }
  3088. units.forEach(function (unit) {
  3089. switch (unit.type) {
  3090. //NDR
  3091. case 1:
  3092. push = true;
  3093. if (!avcSample) {
  3094. avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
  3095. }
  3096. if (debug) {
  3097. avcSample.debug += 'NDR ';
  3098. }
  3099. avcSample.frame = true;
  3100. var data = unit.data;
  3101. // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)
  3102. if (spsfound && data.length > 4) {
  3103. // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR
  3104. var sliceType = new exp_golomb(data).readSliceType();
  3105. // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice
  3106. // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.
  3107. // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.
  3108. // I slice: A slice that is not an SI slice that is decoded using intra prediction only.
  3109. //if (sliceType === 2 || sliceType === 7) {
  3110. if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
  3111. avcSample.key = true;
  3112. }
  3113. }
  3114. break;
  3115. //IDR
  3116. case 5:
  3117. push = true;
  3118. // handle PES not starting with AUD
  3119. if (!avcSample) {
  3120. avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
  3121. }
  3122. if (debug) {
  3123. avcSample.debug += 'IDR ';
  3124. }
  3125. avcSample.key = true;
  3126. avcSample.frame = true;
  3127. break;
  3128. //SEI
  3129. case 6:
  3130. push = true;
  3131. if (debug && avcSample) {
  3132. avcSample.debug += 'SEI ';
  3133. }
  3134. expGolombDecoder = new exp_golomb(_this.discardEPB(unit.data));
  3135. // skip frameType
  3136. expGolombDecoder.readUByte();
  3137. var payloadType = 0;
  3138. var payloadSize = 0;
  3139. var endOfCaptions = false;
  3140. var b = 0;
  3141. while (!endOfCaptions && expGolombDecoder.bytesAvailable > 1) {
  3142. payloadType = 0;
  3143. do {
  3144. b = expGolombDecoder.readUByte();
  3145. payloadType += b;
  3146. } while (b === 0xFF);
  3147. // Parse payload size.
  3148. payloadSize = 0;
  3149. do {
  3150. b = expGolombDecoder.readUByte();
  3151. payloadSize += b;
  3152. } while (b === 0xFF);
  3153. // TODO: there can be more than one payload in an SEI packet...
  3154. // TODO: need to read type and size in a while loop to get them all
  3155. if (payloadType === 4 && expGolombDecoder.bytesAvailable !== 0) {
  3156. endOfCaptions = true;
  3157. var countryCode = expGolombDecoder.readUByte();
  3158. if (countryCode === 181) {
  3159. var providerCode = expGolombDecoder.readUShort();
  3160. if (providerCode === 49) {
  3161. var userStructure = expGolombDecoder.readUInt();
  3162. if (userStructure === 0x47413934) {
  3163. var userDataType = expGolombDecoder.readUByte();
  3164. // Raw CEA-608 bytes wrapped in CEA-708 packet
  3165. if (userDataType === 3) {
  3166. var firstByte = expGolombDecoder.readUByte();
  3167. var secondByte = expGolombDecoder.readUByte();
  3168. var totalCCs = 31 & firstByte;
  3169. var byteArray = [firstByte, secondByte];
  3170. for (i = 0; i < totalCCs; i++) {
  3171. // 3 bytes per CC
  3172. byteArray.push(expGolombDecoder.readUByte());
  3173. byteArray.push(expGolombDecoder.readUByte());
  3174. byteArray.push(expGolombDecoder.readUByte());
  3175. }
  3176. _this._insertSampleInOrder(_this._txtTrack.samples, { type: 3, pts: pes.pts, bytes: byteArray });
  3177. }
  3178. }
  3179. }
  3180. }
  3181. } else if (payloadSize < expGolombDecoder.bytesAvailable) {
  3182. for (i = 0; i < payloadSize; i++) {
  3183. expGolombDecoder.readUByte();
  3184. }
  3185. }
  3186. }
  3187. break;
  3188. //SPS
  3189. case 7:
  3190. push = true;
  3191. spsfound = true;
  3192. if (debug && avcSample) {
  3193. avcSample.debug += 'SPS ';
  3194. }
  3195. if (!track.sps) {
  3196. expGolombDecoder = new exp_golomb(unit.data);
  3197. var config = expGolombDecoder.readSPS();
  3198. track.width = config.width;
  3199. track.height = config.height;
  3200. track.pixelRatio = config.pixelRatio;
  3201. track.sps = [unit.data];
  3202. track.duration = _this._duration;
  3203. var codecarray = unit.data.subarray(1, 4);
  3204. var codecstring = 'avc1.';
  3205. for (i = 0; i < 3; i++) {
  3206. var h = codecarray[i].toString(16);
  3207. if (h.length < 2) {
  3208. h = '0' + h;
  3209. }
  3210. codecstring += h;
  3211. }
  3212. track.codec = codecstring;
  3213. }
  3214. break;
  3215. //PPS
  3216. case 8:
  3217. push = true;
  3218. if (debug && avcSample) {
  3219. avcSample.debug += 'PPS ';
  3220. }
  3221. if (!track.pps) {
  3222. track.pps = [unit.data];
  3223. }
  3224. break;
  3225. // AUD
  3226. case 9:
  3227. push = false;
  3228. track.audFound = true;
  3229. if (avcSample) {
  3230. pushAccesUnit(avcSample, track);
  3231. }
  3232. avcSample = _this.avcSample = createAVCSample(false, pes.pts, pes.dts, debug ? 'AUD ' : '');
  3233. break;
  3234. // Filler Data
  3235. case 12:
  3236. push = false;
  3237. break;
  3238. default:
  3239. push = false;
  3240. if (avcSample) {
  3241. avcSample.debug += 'unknown NAL ' + unit.type + ' ';
  3242. }
  3243. break;
  3244. }
  3245. if (avcSample && push) {
  3246. var _units = avcSample.units;
  3247. _units.push(unit);
  3248. }
  3249. });
  3250. // if last PES packet, push samples
  3251. if (last && avcSample) {
  3252. pushAccesUnit(avcSample, track);
  3253. this.avcSample = null;
  3254. }
  3255. };
  3256. TSDemuxer.prototype._insertSampleInOrder = function _insertSampleInOrder(arr, data) {
  3257. var len = arr.length;
  3258. if (len > 0) {
  3259. if (data.pts >= arr[len - 1].pts) {
  3260. arr.push(data);
  3261. } else {
  3262. for (var pos = len - 1; pos >= 0; pos--) {
  3263. if (data.pts < arr[pos].pts) {
  3264. arr.splice(pos, 0, data);
  3265. break;
  3266. }
  3267. }
  3268. }
  3269. } else {
  3270. arr.push(data);
  3271. }
  3272. };
  3273. TSDemuxer.prototype._getLastNalUnit = function _getLastNalUnit() {
  3274. var avcSample = this.avcSample,
  3275. lastUnit = void 0;
  3276. // try to fallback to previous sample if current one is empty
  3277. if (!avcSample || avcSample.units.length === 0) {
  3278. var track = this._avcTrack,
  3279. samples = track.samples;
  3280. avcSample = samples[samples.length - 1];
  3281. }
  3282. if (avcSample) {
  3283. var units = avcSample.units;
  3284. lastUnit = units[units.length - 1];
  3285. }
  3286. return lastUnit;
  3287. };
  3288. TSDemuxer.prototype._parseAVCNALu = function _parseAVCNALu(array) {
  3289. var i = 0,
  3290. len = array.byteLength,
  3291. value,
  3292. overflow,
  3293. track = this._avcTrack,
  3294. state = track.naluState || 0,
  3295. lastState = state;
  3296. var units = [],
  3297. unit,
  3298. unitType,
  3299. lastUnitStart = -1,
  3300. lastUnitType;
  3301. //logger.log('PES:' + Hex.hexDump(array));
  3302. if (state === -1) {
  3303. // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet
  3304. lastUnitStart = 0;
  3305. // NALu type is value read from offset 0
  3306. lastUnitType = array[0] & 0x1f;
  3307. state = 0;
  3308. i = 1;
  3309. }
  3310. while (i < len) {
  3311. value = array[i++];
  3312. // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case
  3313. if (!state) {
  3314. state = value ? 0 : 1;
  3315. continue;
  3316. }
  3317. if (state === 1) {
  3318. state = value ? 0 : 2;
  3319. continue;
  3320. }
  3321. // here we have state either equal to 2 or 3
  3322. if (!value) {
  3323. state = 3;
  3324. } else if (value === 1) {
  3325. if (lastUnitStart >= 0) {
  3326. unit = { data: array.subarray(lastUnitStart, i - state - 1), type: lastUnitType };
  3327. //logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
  3328. units.push(unit);
  3329. } else {
  3330. // lastUnitStart is undefined => this is the first start code found in this PES packet
  3331. // first check if start code delimiter is overlapping between 2 PES packets,
  3332. // ie it started in last packet (lastState not zero)
  3333. // and ended at the beginning of this PES packet (i <= 4 - lastState)
  3334. var lastUnit = this._getLastNalUnit();
  3335. if (lastUnit) {
  3336. if (lastState && i <= 4 - lastState) {
  3337. // start delimiter overlapping between PES packets
  3338. // strip start delimiter bytes from the end of last NAL unit
  3339. // check if lastUnit had a state different from zero
  3340. if (lastUnit.state) {
  3341. // strip last bytes
  3342. lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
  3343. }
  3344. }
  3345. // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.
  3346. overflow = i - state - 1;
  3347. if (overflow > 0) {
  3348. //logger.log('first NALU found with overflow:' + overflow);
  3349. var tmp = new Uint8Array(lastUnit.data.byteLength + overflow);
  3350. tmp.set(lastUnit.data, 0);
  3351. tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);
  3352. lastUnit.data = tmp;
  3353. }
  3354. }
  3355. }
  3356. // check if we can read unit type
  3357. if (i < len) {
  3358. unitType = array[i] & 0x1f;
  3359. //logger.log('find NALU @ offset:' + i + ',type:' + unitType);
  3360. lastUnitStart = i;
  3361. lastUnitType = unitType;
  3362. state = 0;
  3363. } else {
  3364. // not enough byte to read unit type. let's read it on next PES parsing
  3365. state = -1;
  3366. }
  3367. } else {
  3368. state = 0;
  3369. }
  3370. }
  3371. if (lastUnitStart >= 0 && state >= 0) {
  3372. unit = { data: array.subarray(lastUnitStart, len), type: lastUnitType, state: state };
  3373. units.push(unit);
  3374. //logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);
  3375. }
  3376. // no NALu found
  3377. if (units.length === 0) {
  3378. // append pes.data to previous NAL unit
  3379. var _lastUnit = this._getLastNalUnit();
  3380. if (_lastUnit) {
  3381. var _tmp = new Uint8Array(_lastUnit.data.byteLength + array.byteLength);
  3382. _tmp.set(_lastUnit.data, 0);
  3383. _tmp.set(array, _lastUnit.data.byteLength);
  3384. _lastUnit.data = _tmp;
  3385. }
  3386. }
  3387. track.naluState = state;
  3388. return units;
  3389. };
  3390. /**
  3391. * remove Emulation Prevention bytes from a RBSP
  3392. */
  3393. TSDemuxer.prototype.discardEPB = function discardEPB(data) {
  3394. var length = data.byteLength,
  3395. EPBPositions = [],
  3396. i = 1,
  3397. newLength,
  3398. newData;
  3399. // Find all `Emulation Prevention Bytes`
  3400. while (i < length - 2) {
  3401. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  3402. EPBPositions.push(i + 2);
  3403. i += 2;
  3404. } else {
  3405. i++;
  3406. }
  3407. }
  3408. // If no Emulation Prevention Bytes were found just return the original
  3409. // array
  3410. if (EPBPositions.length === 0) {
  3411. return data;
  3412. }
  3413. // Create a new array to hold the NAL unit data
  3414. newLength = length - EPBPositions.length;
  3415. newData = new Uint8Array(newLength);
  3416. var sourceIndex = 0;
  3417. for (i = 0; i < newLength; sourceIndex++, i++) {
  3418. if (sourceIndex === EPBPositions[0]) {
  3419. // Skip this byte
  3420. sourceIndex++;
  3421. // Remove this position index
  3422. EPBPositions.shift();
  3423. }
  3424. newData[i] = data[sourceIndex];
  3425. }
  3426. return newData;
  3427. };
  3428. TSDemuxer.prototype._parseAACPES = function _parseAACPES(pes) {
  3429. var track = this._audioTrack,
  3430. data = pes.data,
  3431. pts = pes.pts,
  3432. startOffset = 0,
  3433. aacOverFlow = this.aacOverFlow,
  3434. aacLastPTS = this.aacLastPTS,
  3435. frameDuration,
  3436. frameIndex,
  3437. offset,
  3438. stamp,
  3439. len;
  3440. if (aacOverFlow) {
  3441. var tmp = new Uint8Array(aacOverFlow.byteLength + data.byteLength);
  3442. tmp.set(aacOverFlow, 0);
  3443. tmp.set(data, aacOverFlow.byteLength);
  3444. //logger.log(`AAC: append overflowing ${aacOverFlow.byteLength} bytes to beginning of new PES`);
  3445. data = tmp;
  3446. }
  3447. // look for ADTS header (0xFFFx)
  3448. for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
  3449. if (isHeader(data, offset)) {
  3450. break;
  3451. }
  3452. }
  3453. // if ADTS header does not start straight from the beginning of the PES payload, raise an error
  3454. if (offset) {
  3455. var reason, fatal;
  3456. if (offset < len - 1) {
  3457. reason = 'AAC PES did not start with ADTS header,offset:' + offset;
  3458. fatal = false;
  3459. } else {
  3460. reason = 'no ADTS header found in AAC PES';
  3461. fatal = true;
  3462. }
  3463. logger["b" /* logger */].warn('parsing error:' + reason);
  3464. this.observer.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_PARSING_ERROR, fatal: fatal, reason: reason });
  3465. if (fatal) {
  3466. return;
  3467. }
  3468. }
  3469. initTrackConfig(track, this.observer, data, offset, this.audioCodec);
  3470. frameIndex = 0;
  3471. frameDuration = getFrameDuration(track.samplerate);
  3472. // if last AAC frame is overflowing, we should ensure timestamps are contiguous:
  3473. // first sample PTS should be equal to last sample PTS + frameDuration
  3474. if (aacOverFlow && aacLastPTS) {
  3475. var newPTS = aacLastPTS + frameDuration;
  3476. if (Math.abs(newPTS - pts) > 1) {
  3477. logger["b" /* logger */].log('AAC: align PTS for overlapping frames by ' + Math.round((newPTS - pts) / 90));
  3478. pts = newPTS;
  3479. }
  3480. }
  3481. //scan for aac samples
  3482. while (offset < len) {
  3483. if (isHeader(data, offset) && offset + 5 < len) {
  3484. var frame = appendFrame(track, data, offset, pts, frameIndex);
  3485. if (frame) {
  3486. //logger.log(`${Math.round(frame.sample.pts)} : AAC`);
  3487. offset += frame.length;
  3488. stamp = frame.sample.pts;
  3489. frameIndex++;
  3490. } else {
  3491. //logger.log('Unable to parse AAC frame');
  3492. break;
  3493. }
  3494. } else {
  3495. //nothing found, keep looking
  3496. offset++;
  3497. }
  3498. }
  3499. if (offset < len) {
  3500. aacOverFlow = data.subarray(offset, len);
  3501. //logger.log(`AAC: overflow detected:${len-offset}`);
  3502. } else {
  3503. aacOverFlow = null;
  3504. }
  3505. this.aacOverFlow = aacOverFlow;
  3506. this.aacLastPTS = stamp;
  3507. };
  3508. TSDemuxer.prototype._parseMPEGPES = function _parseMPEGPES(pes) {
  3509. var data = pes.data;
  3510. var length = data.length;
  3511. var frameIndex = 0;
  3512. var offset = 0;
  3513. var pts = pes.pts;
  3514. while (offset < length) {
  3515. if (mpegaudio.isHeader(data, offset)) {
  3516. var frame = mpegaudio.appendFrame(this._audioTrack, data, offset, pts, frameIndex);
  3517. if (frame) {
  3518. offset += frame.length;
  3519. frameIndex++;
  3520. } else {
  3521. //logger.log('Unable to parse Mpeg audio frame');
  3522. break;
  3523. }
  3524. } else {
  3525. //nothing found, keep looking
  3526. offset++;
  3527. }
  3528. }
  3529. };
  3530. TSDemuxer.prototype._parseID3PES = function _parseID3PES(pes) {
  3531. this._id3Track.samples.push(pes);
  3532. };
  3533. return TSDemuxer;
  3534. }();
  3535. /* harmony default export */ var tsdemuxer = (tsdemuxer_TSDemuxer);
  3536. // CONCATENATED MODULE: ./src/demux/mp3demuxer.js
  3537. function mp3demuxer__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  3538. /**
  3539. * MP3 demuxer
  3540. */
  3541. var mp3demuxer_MP3Demuxer = function () {
  3542. function MP3Demuxer(observer, remuxer, config) {
  3543. mp3demuxer__classCallCheck(this, MP3Demuxer);
  3544. this.observer = observer;
  3545. this.config = config;
  3546. this.remuxer = remuxer;
  3547. }
  3548. MP3Demuxer.prototype.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
  3549. this._audioTrack = { container: 'audio/mpeg', type: 'audio', id: -1, sequenceNumber: 0, isAAC: false, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 };
  3550. };
  3551. MP3Demuxer.prototype.resetTimeStamp = function resetTimeStamp() {};
  3552. MP3Demuxer.probe = function probe(data) {
  3553. // check if data contains ID3 timestamp and MPEG sync word
  3554. var offset, length;
  3555. var id3Data = id3["a" /* default */].getID3Data(data, 0);
  3556. if (id3Data && id3["a" /* default */].getTimeStamp(id3Data) !== undefined) {
  3557. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  3558. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  3559. // More info http://www.mp3-tech.org/programmer/frame_header.html
  3560. for (offset = id3Data.length, length = Math.min(data.length - 1, offset + 100); offset < length; offset++) {
  3561. if (mpegaudio.probe(data, offset)) {
  3562. logger["b" /* logger */].log('MPEG Audio sync word found !');
  3563. return true;
  3564. }
  3565. }
  3566. }
  3567. return false;
  3568. };
  3569. // feed incoming data to the front of the parsing pipeline
  3570. MP3Demuxer.prototype.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {
  3571. var id3Data = id3["a" /* default */].getID3Data(data, 0);
  3572. var timestamp = id3["a" /* default */].getTimeStamp(id3Data);
  3573. var pts = timestamp ? 90 * timestamp : timeOffset * 90000;
  3574. var offset = id3Data.length;
  3575. var length = data.length;
  3576. var frameIndex = 0,
  3577. stamp = 0;
  3578. var track = this._audioTrack;
  3579. var id3Samples = [{ pts: pts, dts: pts, data: id3Data }];
  3580. while (offset < length) {
  3581. if (mpegaudio.isHeader(data, offset)) {
  3582. var frame = mpegaudio.appendFrame(track, data, offset, pts, frameIndex);
  3583. if (frame) {
  3584. offset += frame.length;
  3585. stamp = frame.sample.pts;
  3586. frameIndex++;
  3587. } else {
  3588. //logger.log('Unable to parse Mpeg audio frame');
  3589. break;
  3590. }
  3591. } else if (id3["a" /* default */].isHeader(data, offset)) {
  3592. id3Data = id3["a" /* default */].getID3Data(data, offset);
  3593. id3Samples.push({ pts: stamp, dts: stamp, data: id3Data });
  3594. offset += id3Data.length;
  3595. } else {
  3596. //nothing found, keep looking
  3597. offset++;
  3598. }
  3599. }
  3600. this.remuxer.remux(track, { samples: [] }, { samples: id3Samples, inputTimeScale: 90000 }, { samples: [] }, timeOffset, contiguous, accurateTimeOffset);
  3601. };
  3602. MP3Demuxer.prototype.destroy = function destroy() {};
  3603. return MP3Demuxer;
  3604. }();
  3605. /* harmony default export */ var mp3demuxer = (mp3demuxer_MP3Demuxer);
  3606. // CONCATENATED MODULE: ./src/helper/aac.js
  3607. function aac__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  3608. /**
  3609. * AAC helper
  3610. */
  3611. var AAC = function () {
  3612. function AAC() {
  3613. aac__classCallCheck(this, AAC);
  3614. }
  3615. AAC.getSilentFrame = function getSilentFrame(codec, channelCount) {
  3616. switch (codec) {
  3617. case 'mp4a.40.2':
  3618. if (channelCount === 1) {
  3619. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
  3620. } else if (channelCount === 2) {
  3621. return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
  3622. } else if (channelCount === 3) {
  3623. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
  3624. } else if (channelCount === 4) {
  3625. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
  3626. } else if (channelCount === 5) {
  3627. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
  3628. } else if (channelCount === 6) {
  3629. 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]);
  3630. }
  3631. break;
  3632. // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)
  3633. default:
  3634. if (channelCount === 1) {
  3635. // 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
  3636. 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]);
  3637. } else if (channelCount === 2) {
  3638. // 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
  3639. 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]);
  3640. } else if (channelCount === 3) {
  3641. // 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
  3642. 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]);
  3643. }
  3644. break;
  3645. }
  3646. return null;
  3647. };
  3648. return AAC;
  3649. }();
  3650. /* harmony default export */ var aac = (AAC);
  3651. // CONCATENATED MODULE: ./src/remux/mp4-generator.js
  3652. function mp4_generator__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  3653. /**
  3654. * Generate MP4 Box
  3655. */
  3656. //import Hex from '../utils/hex';
  3657. var UINT32_MAX = Math.pow(2, 32) - 1;
  3658. var MP4 = function () {
  3659. function MP4() {
  3660. mp4_generator__classCallCheck(this, MP4);
  3661. }
  3662. MP4.init = function init() {
  3663. MP4.types = {
  3664. avc1: [], // codingname
  3665. avcC: [],
  3666. btrt: [],
  3667. dinf: [],
  3668. dref: [],
  3669. esds: [],
  3670. ftyp: [],
  3671. hdlr: [],
  3672. mdat: [],
  3673. mdhd: [],
  3674. mdia: [],
  3675. mfhd: [],
  3676. minf: [],
  3677. moof: [],
  3678. moov: [],
  3679. mp4a: [],
  3680. '.mp3': [],
  3681. mvex: [],
  3682. mvhd: [],
  3683. pasp: [],
  3684. sdtp: [],
  3685. stbl: [],
  3686. stco: [],
  3687. stsc: [],
  3688. stsd: [],
  3689. stsz: [],
  3690. stts: [],
  3691. tfdt: [],
  3692. tfhd: [],
  3693. traf: [],
  3694. trak: [],
  3695. trun: [],
  3696. trex: [],
  3697. tkhd: [],
  3698. vmhd: [],
  3699. smhd: []
  3700. };
  3701. var i;
  3702. for (i in MP4.types) {
  3703. if (MP4.types.hasOwnProperty(i)) {
  3704. MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  3705. }
  3706. }
  3707. var videoHdlr = new Uint8Array([0x00, // version 0
  3708. 0x00, 0x00, 0x00, // flags
  3709. 0x00, 0x00, 0x00, 0x00, // pre_defined
  3710. 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
  3711. 0x00, 0x00, 0x00, 0x00, // reserved
  3712. 0x00, 0x00, 0x00, 0x00, // reserved
  3713. 0x00, 0x00, 0x00, 0x00, // reserved
  3714. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  3715. ]);
  3716. var audioHdlr = new Uint8Array([0x00, // version 0
  3717. 0x00, 0x00, 0x00, // flags
  3718. 0x00, 0x00, 0x00, 0x00, // pre_defined
  3719. 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
  3720. 0x00, 0x00, 0x00, 0x00, // reserved
  3721. 0x00, 0x00, 0x00, 0x00, // reserved
  3722. 0x00, 0x00, 0x00, 0x00, // reserved
  3723. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  3724. ]);
  3725. MP4.HDLR_TYPES = {
  3726. 'video': videoHdlr,
  3727. 'audio': audioHdlr
  3728. };
  3729. var dref = new Uint8Array([0x00, // version 0
  3730. 0x00, 0x00, 0x00, // flags
  3731. 0x00, 0x00, 0x00, 0x01, // entry_count
  3732. 0x00, 0x00, 0x00, 0x0c, // entry_size
  3733. 0x75, 0x72, 0x6c, 0x20, // 'url' type
  3734. 0x00, // version 0
  3735. 0x00, 0x00, 0x01 // entry_flags
  3736. ]);
  3737. var stco = new Uint8Array([0x00, // version
  3738. 0x00, 0x00, 0x00, // flags
  3739. 0x00, 0x00, 0x00, 0x00 // entry_count
  3740. ]);
  3741. MP4.STTS = MP4.STSC = MP4.STCO = stco;
  3742. MP4.STSZ = new Uint8Array([0x00, // version
  3743. 0x00, 0x00, 0x00, // flags
  3744. 0x00, 0x00, 0x00, 0x00, // sample_size
  3745. 0x00, 0x00, 0x00, 0x00]);
  3746. MP4.VMHD = new Uint8Array([0x00, // version
  3747. 0x00, 0x00, 0x01, // flags
  3748. 0x00, 0x00, // graphicsmode
  3749. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  3750. ]);
  3751. MP4.SMHD = new Uint8Array([0x00, // version
  3752. 0x00, 0x00, 0x00, // flags
  3753. 0x00, 0x00, // balance
  3754. 0x00, 0x00 // reserved
  3755. ]);
  3756. MP4.STSD = new Uint8Array([0x00, // version 0
  3757. 0x00, 0x00, 0x00, // flags
  3758. 0x00, 0x00, 0x00, 0x01]); // entry_count
  3759. var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom
  3760. var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1
  3761. var minorVersion = new Uint8Array([0, 0, 0, 1]);
  3762. MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
  3763. MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
  3764. };
  3765. MP4.box = function box(type) {
  3766. var payload = Array.prototype.slice.call(arguments, 1),
  3767. size = 8,
  3768. i = payload.length,
  3769. len = i,
  3770. result;
  3771. // calculate the total size we need to allocate
  3772. while (i--) {
  3773. size += payload[i].byteLength;
  3774. }
  3775. result = new Uint8Array(size);
  3776. result[0] = size >> 24 & 0xff;
  3777. result[1] = size >> 16 & 0xff;
  3778. result[2] = size >> 8 & 0xff;
  3779. result[3] = size & 0xff;
  3780. result.set(type, 4);
  3781. // copy the payload into the result
  3782. for (i = 0, size = 8; i < len; i++) {
  3783. // copy payload[i] array @ offset size
  3784. result.set(payload[i], size);
  3785. size += payload[i].byteLength;
  3786. }
  3787. return result;
  3788. };
  3789. MP4.hdlr = function hdlr(type) {
  3790. return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
  3791. };
  3792. MP4.mdat = function mdat(data) {
  3793. return MP4.box(MP4.types.mdat, data);
  3794. };
  3795. MP4.mdhd = function mdhd(timescale, duration) {
  3796. duration *= timescale;
  3797. var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  3798. var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  3799. return MP4.box(MP4.types.mdhd, new Uint8Array([0x01, // version 1
  3800. 0x00, 0x00, 0x00, // flags
  3801. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
  3802. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
  3803. timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale
  3804. 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)
  3805. 0x00, 0x00]));
  3806. };
  3807. MP4.mdia = function mdia(track) {
  3808. return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));
  3809. };
  3810. MP4.mfhd = function mfhd(sequenceNumber) {
  3811. return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
  3812. sequenceNumber >> 24, sequenceNumber >> 16 & 0xFF, sequenceNumber >> 8 & 0xFF, sequenceNumber & 0xFF]) // sequence_number
  3813. );
  3814. };
  3815. MP4.minf = function minf(track) {
  3816. if (track.type === 'audio') {
  3817. return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
  3818. } else {
  3819. return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
  3820. }
  3821. };
  3822. MP4.moof = function moof(sn, baseMediaDecodeTime, track) {
  3823. return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
  3824. };
  3825. /**
  3826. * @param tracks... (optional) {array} the tracks associated with this movie
  3827. */
  3828. MP4.moov = function moov(tracks) {
  3829. var i = tracks.length,
  3830. boxes = [];
  3831. while (i--) {
  3832. boxes[i] = MP4.trak(tracks[i]);
  3833. }
  3834. return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));
  3835. };
  3836. MP4.mvex = function mvex(tracks) {
  3837. var i = tracks.length,
  3838. boxes = [];
  3839. while (i--) {
  3840. boxes[i] = MP4.trex(tracks[i]);
  3841. }
  3842. return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));
  3843. };
  3844. MP4.mvhd = function mvhd(timescale, duration) {
  3845. duration *= timescale;
  3846. var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  3847. var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  3848. var bytes = new Uint8Array([0x01, // version 1
  3849. 0x00, 0x00, 0x00, // flags
  3850. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
  3851. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
  3852. timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale
  3853. 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
  3854. 0x01, 0x00, // 1.0 volume
  3855. 0x00, 0x00, // reserved
  3856. 0x00, 0x00, 0x00, 0x00, // reserved
  3857. 0x00, 0x00, 0x00, 0x00, // reserved
  3858. 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
  3859. 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
  3860. 0xff, 0xff, 0xff, 0xff // next_track_ID
  3861. ]);
  3862. return MP4.box(MP4.types.mvhd, bytes);
  3863. };
  3864. MP4.sdtp = function sdtp(track) {
  3865. var samples = track.samples || [],
  3866. bytes = new Uint8Array(4 + samples.length),
  3867. flags,
  3868. i;
  3869. // leave the full box header (4 bytes) all zero
  3870. // write the sample table
  3871. for (i = 0; i < samples.length; i++) {
  3872. flags = samples[i].flags;
  3873. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  3874. }
  3875. return MP4.box(MP4.types.sdtp, bytes);
  3876. };
  3877. MP4.stbl = function stbl(track) {
  3878. 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));
  3879. };
  3880. MP4.avc1 = function avc1(track) {
  3881. var sps = [],
  3882. pps = [],
  3883. i,
  3884. data,
  3885. len;
  3886. // assemble the SPSs
  3887. for (i = 0; i < track.sps.length; i++) {
  3888. data = track.sps[i];
  3889. len = data.byteLength;
  3890. sps.push(len >>> 8 & 0xFF);
  3891. sps.push(len & 0xFF);
  3892. sps = sps.concat(Array.prototype.slice.call(data)); // SPS
  3893. }
  3894. // assemble the PPSs
  3895. for (i = 0; i < track.pps.length; i++) {
  3896. data = track.pps[i];
  3897. len = data.byteLength;
  3898. pps.push(len >>> 8 & 0xFF);
  3899. pps.push(len & 0xFF);
  3900. pps = pps.concat(Array.prototype.slice.call(data));
  3901. }
  3902. var avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01, // version
  3903. sps[3], // profile
  3904. sps[4], // profile compat
  3905. sps[5], // level
  3906. 0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes
  3907. 0xE0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets
  3908. ].concat(sps).concat([track.pps.length // numOfPictureParameterSets
  3909. ]).concat(pps))),
  3910. // "PPS"
  3911. width = track.width,
  3912. height = track.height,
  3913. hSpacing = track.pixelRatio[0],
  3914. vSpacing = track.pixelRatio[1];
  3915. return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00, // reserved
  3916. 0x00, 0x00, 0x00, // reserved
  3917. 0x00, 0x01, // data_reference_index
  3918. 0x00, 0x00, // pre_defined
  3919. 0x00, 0x00, // reserved
  3920. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
  3921. width >> 8 & 0xFF, width & 0xff, // width
  3922. height >> 8 & 0xFF, height & 0xff, // height
  3923. 0x00, 0x48, 0x00, 0x00, // horizresolution
  3924. 0x00, 0x48, 0x00, 0x00, // vertresolution
  3925. 0x00, 0x00, 0x00, 0x00, // reserved
  3926. 0x00, 0x01, // frame_count
  3927. 0x12, 0x64, 0x61, 0x69, 0x6C, //dailymotion/hls.js
  3928. 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
  3929. 0x00, 0x18, // depth = 24
  3930. 0x11, 0x11]), // pre_defined = -1
  3931. avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
  3932. 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
  3933. 0x00, 0x2d, 0xc6, 0xc0])), // avgBitrate
  3934. MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24, // hSpacing
  3935. hSpacing >> 16 & 0xFF, hSpacing >> 8 & 0xFF, hSpacing & 0xFF, vSpacing >> 24, // vSpacing
  3936. vSpacing >> 16 & 0xFF, vSpacing >> 8 & 0xFF, vSpacing & 0xFF])));
  3937. };
  3938. MP4.esds = function esds(track) {
  3939. var configlen = track.config.length;
  3940. return new Uint8Array([0x00, // version 0
  3941. 0x00, 0x00, 0x00, // flags
  3942. 0x03, // descriptor_type
  3943. 0x17 + configlen, // length
  3944. 0x00, 0x01, //es_id
  3945. 0x00, // stream_priority
  3946. 0x04, // descriptor_type
  3947. 0x0f + configlen, // length
  3948. 0x40, //codec : mpeg4_audio
  3949. 0x15, // stream_type
  3950. 0x00, 0x00, 0x00, // buffer_size
  3951. 0x00, 0x00, 0x00, 0x00, // maxBitrate
  3952. 0x00, 0x00, 0x00, 0x00, // avgBitrate
  3953. 0x05 // descriptor_type
  3954. ].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor
  3955. };
  3956. MP4.mp4a = function mp4a(track) {
  3957. var samplerate = track.samplerate;
  3958. return MP4.box(MP4.types.mp4a, new Uint8Array([0x00, 0x00, 0x00, // reserved
  3959. 0x00, 0x00, 0x00, // reserved
  3960. 0x00, 0x01, // data_reference_index
  3961. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  3962. 0x00, track.channelCount, // channelcount
  3963. 0x00, 0x10, // sampleSize:16bits
  3964. 0x00, 0x00, 0x00, 0x00, // reserved2
  3965. samplerate >> 8 & 0xFF, samplerate & 0xff, //
  3966. 0x00, 0x00]), MP4.box(MP4.types.esds, MP4.esds(track)));
  3967. };
  3968. MP4.mp3 = function mp3(track) {
  3969. var samplerate = track.samplerate;
  3970. return MP4.box(MP4.types['.mp3'], new Uint8Array([0x00, 0x00, 0x00, // reserved
  3971. 0x00, 0x00, 0x00, // reserved
  3972. 0x00, 0x01, // data_reference_index
  3973. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  3974. 0x00, track.channelCount, // channelcount
  3975. 0x00, 0x10, // sampleSize:16bits
  3976. 0x00, 0x00, 0x00, 0x00, // reserved2
  3977. samplerate >> 8 & 0xFF, samplerate & 0xff, //
  3978. 0x00, 0x00]));
  3979. };
  3980. MP4.stsd = function stsd(track) {
  3981. if (track.type === 'audio') {
  3982. if (!track.isAAC && track.codec === 'mp3') {
  3983. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));
  3984. }
  3985. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
  3986. } else {
  3987. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
  3988. }
  3989. };
  3990. MP4.tkhd = function tkhd(track) {
  3991. var id = track.id,
  3992. duration = track.duration * track.timescale,
  3993. width = track.width,
  3994. height = track.height,
  3995. upperWordDuration = Math.floor(duration / (UINT32_MAX + 1)),
  3996. lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  3997. return MP4.box(MP4.types.tkhd, new Uint8Array([0x01, // version 1
  3998. 0x00, 0x00, 0x07, // flags
  3999. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
  4000. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
  4001. id >> 24 & 0xFF, id >> 16 & 0xFF, id >> 8 & 0xFF, id & 0xFF, // track_ID
  4002. 0x00, 0x00, 0x00, 0x00, // reserved
  4003. 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
  4004. 0x00, 0x00, // layer
  4005. 0x00, 0x00, // alternate_group
  4006. 0x00, 0x00, // non-audio track volume
  4007. 0x00, 0x00, // reserved
  4008. 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
  4009. width >> 8 & 0xFF, width & 0xFF, 0x00, 0x00, // width
  4010. height >> 8 & 0xFF, height & 0xFF, 0x00, 0x00 // height
  4011. ]));
  4012. };
  4013. MP4.traf = function traf(track, baseMediaDecodeTime) {
  4014. var sampleDependencyTable = MP4.sdtp(track),
  4015. id = track.id,
  4016. upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1)),
  4017. lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
  4018. return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00, // version 0
  4019. 0x00, 0x00, 0x00, // flags
  4020. id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF]) // track_ID
  4021. ), MP4.box(MP4.types.tfdt, new Uint8Array([0x01, // version 1
  4022. 0x00, 0x00, 0x00, // flags
  4023. 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
  4024. 20 + // tfdt
  4025. 8 + // traf header
  4026. 16 + // mfhd
  4027. 8 + // moof header
  4028. 8), // mdat header
  4029. sampleDependencyTable);
  4030. };
  4031. /**
  4032. * Generate a track box.
  4033. * @param track {object} a track definition
  4034. * @return {Uint8Array} the track box
  4035. */
  4036. MP4.trak = function trak(track) {
  4037. track.duration = track.duration || 0xffffffff;
  4038. return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
  4039. };
  4040. MP4.trex = function trex(track) {
  4041. var id = track.id;
  4042. return MP4.box(MP4.types.trex, new Uint8Array([0x00, // version 0
  4043. 0x00, 0x00, 0x00, // flags
  4044. id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF, // track_ID
  4045. 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
  4046. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  4047. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  4048. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  4049. ]));
  4050. };
  4051. MP4.trun = function trun(track, offset) {
  4052. var samples = track.samples || [],
  4053. len = samples.length,
  4054. arraylen = 12 + 16 * len,
  4055. array = new Uint8Array(arraylen),
  4056. i,
  4057. sample,
  4058. duration,
  4059. size,
  4060. flags,
  4061. cts;
  4062. offset += 8 + arraylen;
  4063. array.set([0x00, // version 0
  4064. 0x00, 0x0f, 0x01, // flags
  4065. len >>> 24 & 0xFF, len >>> 16 & 0xFF, len >>> 8 & 0xFF, len & 0xFF, // sample_count
  4066. offset >>> 24 & 0xFF, offset >>> 16 & 0xFF, offset >>> 8 & 0xFF, offset & 0xFF // data_offset
  4067. ], 0);
  4068. for (i = 0; i < len; i++) {
  4069. sample = samples[i];
  4070. duration = sample.duration;
  4071. size = sample.size;
  4072. flags = sample.flags;
  4073. cts = sample.cts;
  4074. array.set([duration >>> 24 & 0xFF, duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, // sample_duration
  4075. size >>> 24 & 0xFF, size >>> 16 & 0xFF, size >>> 8 & 0xFF, size & 0xFF, // sample_size
  4076. 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
  4077. cts >>> 24 & 0xFF, cts >>> 16 & 0xFF, cts >>> 8 & 0xFF, cts & 0xFF // sample_composition_time_offset
  4078. ], 12 + 16 * i);
  4079. }
  4080. return MP4.box(MP4.types.trun, array);
  4081. };
  4082. MP4.initSegment = function initSegment(tracks) {
  4083. if (!MP4.types) {
  4084. MP4.init();
  4085. }
  4086. var movie = MP4.moov(tracks),
  4087. result;
  4088. result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);
  4089. result.set(MP4.FTYP);
  4090. result.set(movie, MP4.FTYP.byteLength);
  4091. return result;
  4092. };
  4093. return MP4;
  4094. }();
  4095. /* harmony default export */ var mp4_generator = (MP4);
  4096. // CONCATENATED MODULE: ./src/remux/mp4-remuxer.js
  4097. function mp4_remuxer__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  4098. /**
  4099. * fMP4 remuxer
  4100. */
  4101. // 10 seconds
  4102. var MAX_SILENT_FRAME_DURATION = 10 * 1000;
  4103. var mp4_remuxer_MP4Remuxer = function () {
  4104. function MP4Remuxer(observer, config, typeSupported, vendor) {
  4105. mp4_remuxer__classCallCheck(this, MP4Remuxer);
  4106. this.observer = observer;
  4107. this.config = config;
  4108. this.typeSupported = typeSupported;
  4109. var userAgent = navigator.userAgent;
  4110. this.isSafari = vendor && vendor.indexOf('Apple') > -1 && userAgent && !userAgent.match('CriOS');
  4111. this.ISGenerated = false;
  4112. }
  4113. MP4Remuxer.prototype.destroy = function destroy() {};
  4114. MP4Remuxer.prototype.resetTimeStamp = function resetTimeStamp(defaultTimeStamp) {
  4115. this._initPTS = this._initDTS = defaultTimeStamp;
  4116. };
  4117. MP4Remuxer.prototype.resetInitSegment = function resetInitSegment() {
  4118. this.ISGenerated = false;
  4119. };
  4120. MP4Remuxer.prototype.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
  4121. // generate Init Segment if needed
  4122. if (!this.ISGenerated) {
  4123. this.generateIS(audioTrack, videoTrack, timeOffset);
  4124. }
  4125. if (this.ISGenerated) {
  4126. var nbAudioSamples = audioTrack.samples.length;
  4127. var nbVideoSamples = videoTrack.samples.length;
  4128. var audioTimeOffset = timeOffset;
  4129. var videoTimeOffset = timeOffset;
  4130. if (nbAudioSamples && nbVideoSamples) {
  4131. // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)
  4132. // if first audio DTS is not aligned with first video DTS then we need to take that into account
  4133. // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small
  4134. // drift between audio and video streams
  4135. var audiovideoDeltaDts = (audioTrack.samples[0].dts - videoTrack.samples[0].dts) / videoTrack.inputTimeScale;
  4136. audioTimeOffset += Math.max(0, audiovideoDeltaDts);
  4137. videoTimeOffset += Math.max(0, -audiovideoDeltaDts);
  4138. }
  4139. // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is
  4140. // calculated in remuxAudio.
  4141. //logger.log('nb AAC samples:' + audioTrack.samples.length);
  4142. if (nbAudioSamples) {
  4143. // if initSegment was generated without video samples, regenerate it again
  4144. if (!audioTrack.timescale) {
  4145. logger["b" /* logger */].warn('regenerate InitSegment as audio detected');
  4146. this.generateIS(audioTrack, videoTrack, timeOffset);
  4147. }
  4148. var audioData = this.remuxAudio(audioTrack, audioTimeOffset, contiguous, accurateTimeOffset);
  4149. //logger.log('nb AVC samples:' + videoTrack.samples.length);
  4150. if (nbVideoSamples) {
  4151. var audioTrackLength = void 0;
  4152. if (audioData) {
  4153. audioTrackLength = audioData.endPTS - audioData.startPTS;
  4154. }
  4155. // if initSegment was generated without video samples, regenerate it again
  4156. if (!videoTrack.timescale) {
  4157. logger["b" /* logger */].warn('regenerate InitSegment as video detected');
  4158. this.generateIS(audioTrack, videoTrack, timeOffset);
  4159. }
  4160. this.remuxVideo(videoTrack, videoTimeOffset, contiguous, audioTrackLength, accurateTimeOffset);
  4161. }
  4162. } else {
  4163. var videoData = void 0;
  4164. //logger.log('nb AVC samples:' + videoTrack.samples.length);
  4165. if (nbVideoSamples) {
  4166. videoData = this.remuxVideo(videoTrack, videoTimeOffset, contiguous, accurateTimeOffset);
  4167. }
  4168. if (videoData && audioTrack.codec) {
  4169. this.remuxEmptyAudio(audioTrack, audioTimeOffset, contiguous, videoData);
  4170. }
  4171. }
  4172. }
  4173. //logger.log('nb ID3 samples:' + audioTrack.samples.length);
  4174. if (id3Track.samples.length) {
  4175. this.remuxID3(id3Track, timeOffset);
  4176. }
  4177. //logger.log('nb ID3 samples:' + audioTrack.samples.length);
  4178. if (textTrack.samples.length) {
  4179. this.remuxText(textTrack, timeOffset);
  4180. }
  4181. //notify end of parsing
  4182. this.observer.trigger(events["a" /* default */].FRAG_PARSED);
  4183. };
  4184. MP4Remuxer.prototype.generateIS = function generateIS(audioTrack, videoTrack, timeOffset) {
  4185. var observer = this.observer,
  4186. audioSamples = audioTrack.samples,
  4187. videoSamples = videoTrack.samples,
  4188. typeSupported = this.typeSupported,
  4189. container = 'audio/mp4',
  4190. tracks = {},
  4191. data = { tracks: tracks },
  4192. computePTSDTS = this._initPTS === undefined,
  4193. initPTS,
  4194. initDTS;
  4195. if (computePTSDTS) {
  4196. initPTS = initDTS = Infinity;
  4197. }
  4198. if (audioTrack.config && audioSamples.length) {
  4199. // let's use audio sampling rate as MP4 time scale.
  4200. // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)
  4201. // using audio sampling rate here helps having an integer MP4 frame duration
  4202. // this avoids potential rounding issue and AV sync issue
  4203. audioTrack.timescale = audioTrack.samplerate;
  4204. logger["b" /* logger */].log('audio sampling rate : ' + audioTrack.samplerate);
  4205. if (!audioTrack.isAAC) {
  4206. if (typeSupported.mpeg) {
  4207. // Chrome and Safari
  4208. container = 'audio/mpeg';
  4209. audioTrack.codec = '';
  4210. } else if (typeSupported.mp3) {
  4211. // Firefox
  4212. audioTrack.codec = 'mp3';
  4213. }
  4214. }
  4215. tracks.audio = {
  4216. container: container,
  4217. codec: audioTrack.codec,
  4218. initSegment: !audioTrack.isAAC && typeSupported.mpeg ? new Uint8Array() : mp4_generator.initSegment([audioTrack]),
  4219. metadata: {
  4220. channelCount: audioTrack.channelCount
  4221. }
  4222. };
  4223. if (computePTSDTS) {
  4224. // remember first PTS of this demuxing context. for audio, PTS = DTS
  4225. initPTS = initDTS = audioSamples[0].pts - audioTrack.inputTimeScale * timeOffset;
  4226. }
  4227. }
  4228. if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
  4229. // let's use input time scale as MP4 video timescale
  4230. // we use input time scale straight away to avoid rounding issues on frame duration / cts computation
  4231. var inputTimeScale = videoTrack.inputTimeScale;
  4232. videoTrack.timescale = inputTimeScale;
  4233. tracks.video = {
  4234. container: 'video/mp4',
  4235. codec: videoTrack.codec,
  4236. initSegment: mp4_generator.initSegment([videoTrack]),
  4237. metadata: {
  4238. width: videoTrack.width,
  4239. height: videoTrack.height
  4240. }
  4241. };
  4242. if (computePTSDTS) {
  4243. initPTS = Math.min(initPTS, videoSamples[0].pts - inputTimeScale * timeOffset);
  4244. initDTS = Math.min(initDTS, videoSamples[0].dts - inputTimeScale * timeOffset);
  4245. this.observer.trigger(events["a" /* default */].INIT_PTS_FOUND, { initPTS: initPTS });
  4246. }
  4247. }
  4248. if (Object.keys(tracks).length) {
  4249. observer.trigger(events["a" /* default */].FRAG_PARSING_INIT_SEGMENT, data);
  4250. this.ISGenerated = true;
  4251. if (computePTSDTS) {
  4252. this._initPTS = initPTS;
  4253. this._initDTS = initDTS;
  4254. }
  4255. } else {
  4256. observer.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_PARSING_ERROR, fatal: false, reason: 'no audio/video samples found' });
  4257. }
  4258. };
  4259. MP4Remuxer.prototype.remuxVideo = function remuxVideo(track, timeOffset, contiguous, audioTrackLength, accurateTimeOffset) {
  4260. var offset = 8,
  4261. timeScale = track.timescale,
  4262. mp4SampleDuration,
  4263. mdat,
  4264. moof,
  4265. firstPTS,
  4266. firstDTS,
  4267. nextDTS,
  4268. lastPTS,
  4269. lastDTS,
  4270. inputSamples = track.samples,
  4271. outputSamples = [],
  4272. nbSamples = inputSamples.length,
  4273. ptsNormalize = this._PTSNormalize,
  4274. initDTS = this._initDTS;
  4275. // for (let i = 0; i < track.samples.length; i++) {
  4276. // let avcSample = track.samples[i];
  4277. // let units = avcSample.units;
  4278. // let unitsString = '';
  4279. // for (let j = 0; j < units.length ; j++) {
  4280. // unitsString += units[j].type + ',';
  4281. // if (units[j].data.length < 500) {
  4282. // unitsString += Hex.hexDump(units[j].data);
  4283. // }
  4284. // }
  4285. // logger.log(avcSample.pts + '/' + avcSample.dts + ',' + unitsString + avcSample.units.length);
  4286. // }
  4287. // if parsed fragment is contiguous with last one, let's use last DTS value as reference
  4288. var nextAvcDts = this.nextAvcDts;
  4289. var isSafari = this.isSafari;
  4290. // Safari does not like overlapping DTS on consecutive fragments. let's use nextAvcDts to overcome this if fragments are consecutive
  4291. if (isSafari) {
  4292. // also consider consecutive fragments as being contiguous (even if a level switch occurs),
  4293. // for sake of clarity:
  4294. // consecutive fragments are frags with
  4295. // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
  4296. // - less than 200 ms PTS gaps (timeScale/5)
  4297. contiguous |= inputSamples.length && nextAvcDts && (accurateTimeOffset && Math.abs(timeOffset - nextAvcDts / timeScale) < 0.1 || Math.abs(inputSamples[0].pts - nextAvcDts - initDTS) < timeScale / 5);
  4298. }
  4299. if (!contiguous) {
  4300. // if not contiguous, let's use target timeOffset
  4301. nextAvcDts = timeOffset * timeScale;
  4302. }
  4303. // PTS is coded on 33bits, and can loop from -2^32 to 2^32
  4304. // ptsNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value
  4305. inputSamples.forEach(function (sample) {
  4306. sample.pts = ptsNormalize(sample.pts - initDTS, nextAvcDts);
  4307. sample.dts = ptsNormalize(sample.dts - initDTS, nextAvcDts);
  4308. });
  4309. // sort video samples by DTS then PTS then demux id order
  4310. inputSamples.sort(function (a, b) {
  4311. var deltadts = a.dts - b.dts;
  4312. var deltapts = a.pts - b.pts;
  4313. return deltadts ? deltadts : deltapts ? deltapts : a.id - b.id;
  4314. });
  4315. // handle broken streams with PTS < DTS, tolerance up 200ms (18000 in 90kHz timescale)
  4316. var PTSDTSshift = inputSamples.reduce(function (prev, curr) {
  4317. return Math.max(Math.min(prev, curr.pts - curr.dts), -18000);
  4318. }, 0);
  4319. if (PTSDTSshift < 0) {
  4320. logger["b" /* logger */].warn('PTS < DTS detected in video samples, shifting DTS by ' + Math.round(PTSDTSshift / 90) + ' ms to overcome this issue');
  4321. for (var i = 0; i < inputSamples.length; i++) {
  4322. inputSamples[i].dts += PTSDTSshift;
  4323. }
  4324. }
  4325. // compute first DTS and last DTS, normalize them against reference value
  4326. var sample = inputSamples[0];
  4327. firstDTS = Math.max(sample.dts, 0);
  4328. firstPTS = Math.max(sample.pts, 0);
  4329. // check timestamp continuity accross consecutive fragments (this is to remove inter-fragment gap/hole)
  4330. var delta = Math.round((firstDTS - nextAvcDts) / 90);
  4331. // if fragment are contiguous, detect hole/overlapping between fragments
  4332. if (contiguous) {
  4333. if (delta) {
  4334. if (delta > 1) {
  4335. logger["b" /* logger */].log('AVC:' + delta + ' ms hole between fragments detected,filling it');
  4336. } else if (delta < -1) {
  4337. logger["b" /* logger */].log('AVC:' + -delta + ' ms overlapping between fragments detected');
  4338. }
  4339. // remove hole/gap : set DTS to next expected DTS
  4340. firstDTS = nextAvcDts;
  4341. inputSamples[0].dts = firstDTS;
  4342. // offset PTS as well, ensure that PTS is smaller or equal than new DTS
  4343. firstPTS = Math.max(firstPTS - delta, nextAvcDts);
  4344. inputSamples[0].pts = firstPTS;
  4345. logger["b" /* logger */].log('Video/PTS/DTS adjusted: ' + Math.round(firstPTS / 90) + '/' + Math.round(firstDTS / 90) + ',delta:' + delta + ' ms');
  4346. }
  4347. }
  4348. nextDTS = firstDTS;
  4349. // compute lastPTS/lastDTS
  4350. sample = inputSamples[inputSamples.length - 1];
  4351. lastDTS = Math.max(sample.dts, 0);
  4352. lastPTS = Math.max(sample.pts, 0, lastDTS);
  4353. // on Safari let's signal the same sample duration for all samples
  4354. // sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS
  4355. // set this constant duration as being the avg delta between consecutive DTS.
  4356. if (isSafari) {
  4357. mp4SampleDuration = Math.round((lastDTS - firstDTS) / (inputSamples.length - 1));
  4358. }
  4359. var nbNalu = 0,
  4360. naluLen = 0;
  4361. for (var _i = 0; _i < nbSamples; _i++) {
  4362. // compute total/avc sample length and nb of NAL units
  4363. var _sample = inputSamples[_i],
  4364. units = _sample.units,
  4365. nbUnits = units.length,
  4366. sampleLen = 0;
  4367. for (var j = 0; j < nbUnits; j++) {
  4368. sampleLen += units[j].data.length;
  4369. }
  4370. naluLen += sampleLen;
  4371. nbNalu += nbUnits;
  4372. _sample.length = sampleLen;
  4373. // normalize PTS/DTS
  4374. if (isSafari) {
  4375. // sample DTS is computed using a constant decoding offset (mp4SampleDuration) between samples
  4376. _sample.dts = firstDTS + _i * mp4SampleDuration;
  4377. } else {
  4378. // ensure sample monotonic DTS
  4379. _sample.dts = Math.max(_sample.dts, firstDTS);
  4380. }
  4381. // ensure that computed value is greater or equal than sample DTS
  4382. _sample.pts = Math.max(_sample.pts, _sample.dts);
  4383. }
  4384. /* concatenate the video data and construct the mdat in place
  4385. (need 8 more bytes to fill length and mpdat type) */
  4386. var mdatSize = naluLen + 4 * nbNalu + 8;
  4387. try {
  4388. mdat = new Uint8Array(mdatSize);
  4389. } catch (err) {
  4390. this.observer.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MUX_ERROR, details: errors["a" /* ErrorDetails */].REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: 'fail allocating video mdat ' + mdatSize });
  4391. return;
  4392. }
  4393. var view = new DataView(mdat.buffer);
  4394. view.setUint32(0, mdatSize);
  4395. mdat.set(mp4_generator.types.mdat, 4);
  4396. for (var _i2 = 0; _i2 < nbSamples; _i2++) {
  4397. var avcSample = inputSamples[_i2],
  4398. avcSampleUnits = avcSample.units,
  4399. mp4SampleLength = 0,
  4400. compositionTimeOffset = void 0;
  4401. // convert NALU bitstream to MP4 format (prepend NALU with size field)
  4402. for (var _j = 0, _nbUnits = avcSampleUnits.length; _j < _nbUnits; _j++) {
  4403. var unit = avcSampleUnits[_j],
  4404. unitData = unit.data,
  4405. unitDataLen = unit.data.byteLength;
  4406. view.setUint32(offset, unitDataLen);
  4407. offset += 4;
  4408. mdat.set(unitData, offset);
  4409. offset += unitDataLen;
  4410. mp4SampleLength += 4 + unitDataLen;
  4411. }
  4412. if (!isSafari) {
  4413. // expected sample duration is the Decoding Timestamp diff of consecutive samples
  4414. if (_i2 < nbSamples - 1) {
  4415. mp4SampleDuration = inputSamples[_i2 + 1].dts - avcSample.dts;
  4416. } else {
  4417. var config = this.config,
  4418. lastFrameDuration = avcSample.dts - inputSamples[_i2 > 0 ? _i2 - 1 : _i2].dts;
  4419. if (config.stretchShortVideoTrack) {
  4420. // In some cases, a segment's audio track duration may exceed the video track duration.
  4421. // Since we've already remuxed audio, and we know how long the audio track is, we look to
  4422. // see if the delta to the next segment is longer than the minimum of maxBufferHole and
  4423. // maxSeekHole. If so, playback would potentially get stuck, so we artificially inflate
  4424. // the duration of the last frame to minimize any potential gap between segments.
  4425. var maxBufferHole = config.maxBufferHole,
  4426. maxSeekHole = config.maxSeekHole,
  4427. gapTolerance = Math.floor(Math.min(maxBufferHole, maxSeekHole) * timeScale),
  4428. deltaToFrameEnd = (audioTrackLength ? firstPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts;
  4429. if (deltaToFrameEnd > gapTolerance) {
  4430. // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video
  4431. // frame overlap. maxBufferHole/maxSeekHole should be >> lastFrameDuration anyway.
  4432. mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
  4433. if (mp4SampleDuration < 0) {
  4434. mp4SampleDuration = lastFrameDuration;
  4435. }
  4436. logger["b" /* logger */].log('It is approximately ' + deltaToFrameEnd / 90 + ' ms to the next segment; using duration ' + mp4SampleDuration / 90 + ' ms for the last video frame.');
  4437. } else {
  4438. mp4SampleDuration = lastFrameDuration;
  4439. }
  4440. } else {
  4441. mp4SampleDuration = lastFrameDuration;
  4442. }
  4443. }
  4444. compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts);
  4445. } else {
  4446. compositionTimeOffset = Math.max(0, mp4SampleDuration * Math.round((avcSample.pts - avcSample.dts) / mp4SampleDuration));
  4447. }
  4448. //console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${avcSample.pts}/${avcSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(avcSample.pts/4294967296).toFixed(3)}');
  4449. outputSamples.push({
  4450. size: mp4SampleLength,
  4451. // constant duration
  4452. duration: mp4SampleDuration,
  4453. cts: compositionTimeOffset,
  4454. flags: {
  4455. isLeading: 0,
  4456. isDependedOn: 0,
  4457. hasRedundancy: 0,
  4458. degradPrio: 0,
  4459. dependsOn: avcSample.key ? 2 : 1,
  4460. isNonSync: avcSample.key ? 0 : 1
  4461. }
  4462. });
  4463. }
  4464. // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)
  4465. this.nextAvcDts = lastDTS + mp4SampleDuration;
  4466. var dropped = track.dropped;
  4467. track.len = 0;
  4468. track.nbNalu = 0;
  4469. track.dropped = 0;
  4470. if (outputSamples.length && navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
  4471. var flags = outputSamples[0].flags;
  4472. // chrome workaround, mark first sample as being a Random Access Point to avoid sourcebuffer append issue
  4473. // https://code.google.com/p/chromium/issues/detail?id=229412
  4474. flags.dependsOn = 2;
  4475. flags.isNonSync = 0;
  4476. }
  4477. track.samples = outputSamples;
  4478. moof = mp4_generator.moof(track.sequenceNumber++, firstDTS, track);
  4479. track.samples = [];
  4480. var data = {
  4481. data1: moof,
  4482. data2: mdat,
  4483. startPTS: firstPTS / timeScale,
  4484. endPTS: (lastPTS + mp4SampleDuration) / timeScale,
  4485. startDTS: firstDTS / timeScale,
  4486. endDTS: this.nextAvcDts / timeScale,
  4487. type: 'video',
  4488. nb: outputSamples.length,
  4489. dropped: dropped
  4490. };
  4491. this.observer.trigger(events["a" /* default */].FRAG_PARSING_DATA, data);
  4492. return data;
  4493. };
  4494. MP4Remuxer.prototype.remuxAudio = function remuxAudio(track, timeOffset, contiguous, accurateTimeOffset) {
  4495. var inputTimeScale = track.inputTimeScale,
  4496. mp4timeScale = track.timescale,
  4497. scaleFactor = inputTimeScale / mp4timeScale,
  4498. mp4SampleDuration = track.isAAC ? 1024 : 1152,
  4499. inputSampleDuration = mp4SampleDuration * scaleFactor,
  4500. ptsNormalize = this._PTSNormalize,
  4501. initDTS = this._initDTS,
  4502. rawMPEG = !track.isAAC && this.typeSupported.mpeg;
  4503. var offset,
  4504. mp4Sample,
  4505. fillFrame,
  4506. mdat,
  4507. moof,
  4508. firstPTS,
  4509. lastPTS,
  4510. inputSamples = track.samples,
  4511. outputSamples = [],
  4512. nextAudioPts = this.nextAudioPts;
  4513. // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),
  4514. // for sake of clarity:
  4515. // consecutive fragments are frags with
  4516. // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
  4517. // - less than 20 audio frames distance
  4518. // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
  4519. // this helps ensuring audio continuity
  4520. // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame
  4521. contiguous |= inputSamples.length && nextAudioPts && (accurateTimeOffset && Math.abs(timeOffset - nextAudioPts / inputTimeScale) < 0.1 || Math.abs(inputSamples[0].pts - nextAudioPts - initDTS) < 20 * inputSampleDuration);
  4522. // compute normalized PTS
  4523. inputSamples.forEach(function (sample) {
  4524. sample.pts = sample.dts = ptsNormalize(sample.pts - initDTS, timeOffset * inputTimeScale);
  4525. });
  4526. // filter out sample with negative PTS that are not playable anyway
  4527. // if we don't remove these negative samples, they will shift all audio samples forward.
  4528. // leading to audio overlap between current / next fragment
  4529. inputSamples = inputSamples.filter(function (sample) {
  4530. return sample.pts >= 0;
  4531. });
  4532. // in case all samples have negative PTS, and have been filtered out, return now
  4533. if (inputSamples.length === 0) {
  4534. return;
  4535. }
  4536. if (!contiguous) {
  4537. if (!accurateTimeOffset) {
  4538. // if frag are mot contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS
  4539. nextAudioPts = inputSamples[0].pts;
  4540. } else {
  4541. // if timeOffset is accurate, let's use it as predicted next audio PTS
  4542. nextAudioPts = timeOffset * inputTimeScale;
  4543. }
  4544. }
  4545. // If the audio track is missing samples, the frames seem to get "left-shifted" within the
  4546. // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.
  4547. // In an effort to prevent this from happening, we inject frames here where there are gaps.
  4548. // When possible, we inject a silent frame; when that's not possible, we duplicate the last
  4549. // frame.
  4550. if (track.isAAC) {
  4551. var maxAudioFramesDrift = this.config.maxAudioFramesDrift;
  4552. for (var i = 0, nextPts = nextAudioPts; i < inputSamples.length;) {
  4553. // First, let's see how far off this frame is from where we expect it to be
  4554. var sample = inputSamples[i],
  4555. delta;
  4556. var pts = sample.pts;
  4557. delta = pts - nextPts;
  4558. var duration = Math.abs(1000 * delta / inputTimeScale);
  4559. // If we're overlapping by more than a duration, drop this sample
  4560. if (delta <= -maxAudioFramesDrift * inputSampleDuration) {
  4561. logger["b" /* logger */].warn('Dropping 1 audio frame @ ' + (nextPts / inputTimeScale).toFixed(3) + 's due to ' + Math.round(duration) + ' ms overlap.');
  4562. inputSamples.splice(i, 1);
  4563. track.len -= sample.unit.length;
  4564. // Don't touch nextPtsNorm or i
  4565. }
  4566. // Insert missing frames if:
  4567. // 1: We're more than maxAudioFramesDrift frame away
  4568. // 2: Not more than MAX_SILENT_FRAME_DURATION away
  4569. // 3: currentTime (aka nextPtsNorm) is not 0
  4570. else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && nextPts) {
  4571. var missing = Math.round(delta / inputSampleDuration);
  4572. logger["b" /* logger */].warn('Injecting ' + missing + ' audio frame @ ' + (nextPts / inputTimeScale).toFixed(3) + 's due to ' + Math.round(1000 * delta / inputTimeScale) + ' ms gap.');
  4573. for (var j = 0; j < missing; j++) {
  4574. var newStamp = Math.max(nextPts, 0);
  4575. fillFrame = aac.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  4576. if (!fillFrame) {
  4577. logger["b" /* logger */].log('Unable to get silent frame for given audio codec; duplicating last frame instead.');
  4578. fillFrame = sample.unit.subarray();
  4579. }
  4580. inputSamples.splice(i, 0, { unit: fillFrame, pts: newStamp, dts: newStamp });
  4581. track.len += fillFrame.length;
  4582. nextPts += inputSampleDuration;
  4583. i++;
  4584. }
  4585. // Adjust sample to next expected pts
  4586. sample.pts = sample.dts = nextPts;
  4587. nextPts += inputSampleDuration;
  4588. i++;
  4589. } else {
  4590. // Otherwise, just adjust pts
  4591. if (Math.abs(delta) > 0.1 * inputSampleDuration) {
  4592. //logger.log(`Invalid frame delta ${Math.round(delta + inputSampleDuration)} at PTS ${Math.round(pts / 90)} (should be ${Math.round(inputSampleDuration)}).`);
  4593. }
  4594. sample.pts = sample.dts = nextPts;
  4595. nextPts += inputSampleDuration;
  4596. i++;
  4597. }
  4598. }
  4599. }
  4600. for (var _j2 = 0, _nbSamples = inputSamples.length; _j2 < _nbSamples; _j2++) {
  4601. var audioSample = inputSamples[_j2];
  4602. var unit = audioSample.unit;
  4603. var _pts = audioSample.pts;
  4604. //logger.log(`Audio/PTS:${Math.round(pts/90)}`);
  4605. // if not first sample
  4606. if (lastPTS !== undefined) {
  4607. mp4Sample.duration = Math.round((_pts - lastPTS) / scaleFactor);
  4608. } else {
  4609. var _delta = Math.round(1000 * (_pts - nextAudioPts) / inputTimeScale),
  4610. numMissingFrames = 0;
  4611. // if fragment are contiguous, detect hole/overlapping between fragments
  4612. // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
  4613. if (contiguous && track.isAAC) {
  4614. // log delta
  4615. if (_delta) {
  4616. if (_delta > 0 && _delta < MAX_SILENT_FRAME_DURATION) {
  4617. numMissingFrames = Math.round((_pts - nextAudioPts) / inputSampleDuration);
  4618. logger["b" /* logger */].log(_delta + ' ms hole between AAC samples detected,filling it');
  4619. if (numMissingFrames > 0) {
  4620. fillFrame = aac.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  4621. if (!fillFrame) {
  4622. fillFrame = unit.subarray();
  4623. }
  4624. track.len += numMissingFrames * fillFrame.length;
  4625. }
  4626. // if we have frame overlap, overlapping for more than half a frame duraion
  4627. } else if (_delta < -12) {
  4628. // drop overlapping audio frames... browser will deal with it
  4629. logger["b" /* logger */].log('drop overlapping AAC sample, expected/parsed/delta:' + (nextAudioPts / inputTimeScale).toFixed(3) + 's/' + (_pts / inputTimeScale).toFixed(3) + 's/' + -_delta + 'ms');
  4630. track.len -= unit.byteLength;
  4631. continue;
  4632. }
  4633. // set PTS/DTS to expected PTS/DTS
  4634. _pts = nextAudioPts;
  4635. }
  4636. }
  4637. // remember first PTS of our audioSamples
  4638. firstPTS = _pts;
  4639. if (track.len > 0) {
  4640. /* concatenate the audio data and construct the mdat in place
  4641. (need 8 more bytes to fill length and mdat type) */
  4642. var mdatSize = rawMPEG ? track.len : track.len + 8;
  4643. offset = rawMPEG ? 0 : 8;
  4644. try {
  4645. mdat = new Uint8Array(mdatSize);
  4646. } catch (err) {
  4647. this.observer.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MUX_ERROR, details: errors["a" /* ErrorDetails */].REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: 'fail allocating audio mdat ' + mdatSize });
  4648. return;
  4649. }
  4650. if (!rawMPEG) {
  4651. var view = new DataView(mdat.buffer);
  4652. view.setUint32(0, mdatSize);
  4653. mdat.set(mp4_generator.types.mdat, 4);
  4654. }
  4655. } else {
  4656. // no audio samples
  4657. return;
  4658. }
  4659. for (var _i3 = 0; _i3 < numMissingFrames; _i3++) {
  4660. fillFrame = aac.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  4661. if (!fillFrame) {
  4662. logger["b" /* logger */].log('Unable to get silent frame for given audio codec; duplicating this frame instead.');
  4663. fillFrame = unit.subarray();
  4664. }
  4665. mdat.set(fillFrame, offset);
  4666. offset += fillFrame.byteLength;
  4667. mp4Sample = {
  4668. size: fillFrame.byteLength,
  4669. cts: 0,
  4670. duration: 1024,
  4671. flags: {
  4672. isLeading: 0,
  4673. isDependedOn: 0,
  4674. hasRedundancy: 0,
  4675. degradPrio: 0,
  4676. dependsOn: 1
  4677. }
  4678. };
  4679. outputSamples.push(mp4Sample);
  4680. }
  4681. }
  4682. mdat.set(unit, offset);
  4683. var unitLen = unit.byteLength;
  4684. offset += unitLen;
  4685. //console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${audioSample.pts}/${audioSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(audioSample.pts/4294967296).toFixed(3)}');
  4686. mp4Sample = {
  4687. size: unitLen,
  4688. cts: 0,
  4689. duration: 0,
  4690. flags: {
  4691. isLeading: 0,
  4692. isDependedOn: 0,
  4693. hasRedundancy: 0,
  4694. degradPrio: 0,
  4695. dependsOn: 1
  4696. }
  4697. };
  4698. outputSamples.push(mp4Sample);
  4699. lastPTS = _pts;
  4700. }
  4701. var lastSampleDuration = 0;
  4702. var nbSamples = outputSamples.length;
  4703. //set last sample duration as being identical to previous sample
  4704. if (nbSamples >= 2) {
  4705. lastSampleDuration = outputSamples[nbSamples - 2].duration;
  4706. mp4Sample.duration = lastSampleDuration;
  4707. }
  4708. if (nbSamples) {
  4709. // next audio sample PTS should be equal to last sample PTS + duration
  4710. this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSampleDuration;
  4711. //logger.log('Audio/PTS/PTSend:' + audioSample.pts.toFixed(0) + '/' + this.nextAacDts.toFixed(0));
  4712. track.len = 0;
  4713. track.samples = outputSamples;
  4714. if (rawMPEG) {
  4715. moof = new Uint8Array();
  4716. } else {
  4717. moof = mp4_generator.moof(track.sequenceNumber++, firstPTS / scaleFactor, track);
  4718. }
  4719. track.samples = [];
  4720. var start = firstPTS / inputTimeScale;
  4721. var end = nextAudioPts / inputTimeScale;
  4722. var audioData = {
  4723. data1: moof,
  4724. data2: mdat,
  4725. startPTS: start,
  4726. endPTS: end,
  4727. startDTS: start,
  4728. endDTS: end,
  4729. type: 'audio',
  4730. nb: nbSamples
  4731. };
  4732. this.observer.trigger(events["a" /* default */].FRAG_PARSING_DATA, audioData);
  4733. return audioData;
  4734. }
  4735. return null;
  4736. };
  4737. MP4Remuxer.prototype.remuxEmptyAudio = function remuxEmptyAudio(track, timeOffset, contiguous, videoData) {
  4738. var inputTimeScale = track.inputTimeScale,
  4739. mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale,
  4740. scaleFactor = inputTimeScale / mp4timeScale,
  4741. nextAudioPts = this.nextAudioPts,
  4742. // sync with video's timestamp
  4743. startDTS = (nextAudioPts !== undefined ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS,
  4744. endDTS = videoData.endDTS * inputTimeScale + this._initDTS,
  4745. // one sample's duration value
  4746. sampleDuration = 1024,
  4747. frameDuration = scaleFactor * sampleDuration,
  4748. // samples count of this segment's duration
  4749. nbSamples = Math.ceil((endDTS - startDTS) / frameDuration),
  4750. // silent frame
  4751. silentFrame = aac.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  4752. logger["b" /* logger */].warn('remux empty Audio');
  4753. // Can't remux if we can't generate a silent frame...
  4754. if (!silentFrame) {
  4755. logger["b" /* logger */].trace('Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!');
  4756. return;
  4757. }
  4758. var samples = [];
  4759. for (var i = 0; i < nbSamples; i++) {
  4760. var stamp = startDTS + i * frameDuration;
  4761. samples.push({ unit: silentFrame, pts: stamp, dts: stamp });
  4762. track.len += silentFrame.length;
  4763. }
  4764. track.samples = samples;
  4765. this.remuxAudio(track, timeOffset, contiguous);
  4766. };
  4767. MP4Remuxer.prototype.remuxID3 = function remuxID3(track, timeOffset) {
  4768. var length = track.samples.length,
  4769. sample;
  4770. var inputTimeScale = track.inputTimeScale;
  4771. var initPTS = this._initPTS;
  4772. var initDTS = this._initDTS;
  4773. // consume samples
  4774. if (length) {
  4775. for (var index = 0; index < length; index++) {
  4776. sample = track.samples[index];
  4777. // setting id3 pts, dts to relative time
  4778. // using this._initPTS and this._initDTS to calculate relative time
  4779. sample.pts = (sample.pts - initPTS) / inputTimeScale;
  4780. sample.dts = (sample.dts - initDTS) / inputTimeScale;
  4781. }
  4782. this.observer.trigger(events["a" /* default */].FRAG_PARSING_METADATA, {
  4783. samples: track.samples
  4784. });
  4785. }
  4786. track.samples = [];
  4787. timeOffset = timeOffset;
  4788. };
  4789. MP4Remuxer.prototype.remuxText = function remuxText(track, timeOffset) {
  4790. track.samples.sort(function (a, b) {
  4791. return a.pts - b.pts;
  4792. });
  4793. var length = track.samples.length,
  4794. sample;
  4795. var inputTimeScale = track.inputTimeScale;
  4796. var initPTS = this._initPTS;
  4797. // consume samples
  4798. if (length) {
  4799. for (var index = 0; index < length; index++) {
  4800. sample = track.samples[index];
  4801. // setting text pts, dts to relative time
  4802. // using this._initPTS and this._initDTS to calculate relative time
  4803. sample.pts = (sample.pts - initPTS) / inputTimeScale;
  4804. }
  4805. this.observer.trigger(events["a" /* default */].FRAG_PARSING_USERDATA, {
  4806. samples: track.samples
  4807. });
  4808. }
  4809. track.samples = [];
  4810. timeOffset = timeOffset;
  4811. };
  4812. MP4Remuxer.prototype._PTSNormalize = function _PTSNormalize(value, reference) {
  4813. var offset;
  4814. if (reference === undefined) {
  4815. return value;
  4816. }
  4817. if (reference < value) {
  4818. // - 2^33
  4819. offset = -8589934592;
  4820. } else {
  4821. // + 2^33
  4822. offset = 8589934592;
  4823. }
  4824. /* PTS is 33bit (from 0 to 2^33 -1)
  4825. if diff between value and reference is bigger than half of the amplitude (2^32) then it means that
  4826. PTS looping occured. fill the gap */
  4827. while (Math.abs(value - reference) > 4294967296) {
  4828. value += offset;
  4829. }
  4830. return value;
  4831. };
  4832. return MP4Remuxer;
  4833. }();
  4834. /* harmony default export */ var mp4_remuxer = (mp4_remuxer_MP4Remuxer);
  4835. // CONCATENATED MODULE: ./src/remux/passthrough-remuxer.js
  4836. function passthrough_remuxer__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  4837. /**
  4838. * passthrough remuxer
  4839. */
  4840. var passthrough_remuxer_PassThroughRemuxer = function () {
  4841. function PassThroughRemuxer(observer) {
  4842. passthrough_remuxer__classCallCheck(this, PassThroughRemuxer);
  4843. this.observer = observer;
  4844. }
  4845. PassThroughRemuxer.prototype.destroy = function destroy() {};
  4846. PassThroughRemuxer.prototype.resetTimeStamp = function resetTimeStamp() {};
  4847. PassThroughRemuxer.prototype.resetInitSegment = function resetInitSegment() {};
  4848. PassThroughRemuxer.prototype.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset, rawData) {
  4849. var observer = this.observer;
  4850. var streamType = '';
  4851. if (audioTrack) {
  4852. streamType += 'audio';
  4853. }
  4854. if (videoTrack) {
  4855. streamType += 'video';
  4856. }
  4857. observer.trigger(events["a" /* default */].FRAG_PARSING_DATA, {
  4858. data1: rawData,
  4859. startPTS: timeOffset,
  4860. startDTS: timeOffset,
  4861. type: streamType,
  4862. nb: 1,
  4863. dropped: 0
  4864. });
  4865. //notify end of parsing
  4866. observer.trigger(events["a" /* default */].FRAG_PARSED);
  4867. };
  4868. return PassThroughRemuxer;
  4869. }();
  4870. /* harmony default export */ var passthrough_remuxer = (passthrough_remuxer_PassThroughRemuxer);
  4871. // CONCATENATED MODULE: ./src/demux/demuxer-inline.js
  4872. function demuxer_inline__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  4873. /* inline demuxer.
  4874. * probe fragments and instantiate appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...)
  4875. */
  4876. var demuxer_inline_DemuxerInline = function () {
  4877. function DemuxerInline(observer, typeSupported, config, vendor) {
  4878. demuxer_inline__classCallCheck(this, DemuxerInline);
  4879. this.observer = observer;
  4880. this.typeSupported = typeSupported;
  4881. this.config = config;
  4882. this.vendor = vendor;
  4883. }
  4884. DemuxerInline.prototype.destroy = function destroy() {
  4885. var demuxer = this.demuxer;
  4886. if (demuxer) {
  4887. demuxer.destroy();
  4888. }
  4889. };
  4890. DemuxerInline.prototype.push = function push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {
  4891. if (data.byteLength > 0 && decryptdata != null && decryptdata.key != null && decryptdata.method === 'AES-128') {
  4892. var decrypter = this.decrypter;
  4893. if (decrypter == null) {
  4894. decrypter = this.decrypter = new crypt_decrypter["a" /* default */](this.observer, this.config);
  4895. }
  4896. var localthis = this;
  4897. // performance.now() not available on WebWorker, at least on Safari Desktop
  4898. var startTime;
  4899. try {
  4900. startTime = performance.now();
  4901. } catch (error) {
  4902. startTime = Date.now();
  4903. }
  4904. decrypter.decrypt(data, decryptdata.key.buffer, decryptdata.iv.buffer, function (decryptedData) {
  4905. var endTime;
  4906. try {
  4907. endTime = performance.now();
  4908. } catch (error) {
  4909. endTime = Date.now();
  4910. }
  4911. localthis.observer.trigger(events["a" /* default */].FRAG_DECRYPTED, { stats: { tstart: startTime, tdecrypt: endTime } });
  4912. localthis.pushDecrypted(new Uint8Array(decryptedData), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
  4913. });
  4914. } else {
  4915. this.pushDecrypted(new Uint8Array(data), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
  4916. }
  4917. };
  4918. DemuxerInline.prototype.pushDecrypted = function pushDecrypted(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {
  4919. var demuxer = this.demuxer;
  4920. if (!demuxer ||
  4921. // in case of continuity change, we might switch from content type (AAC container to TS container for example)
  4922. // so let's check that current demuxer is still valid
  4923. discontinuity && !this.probe(data)) {
  4924. var observer = this.observer;
  4925. var typeSupported = this.typeSupported;
  4926. var config = this.config;
  4927. // probing order is TS/AAC/MP3/MP4
  4928. var muxConfig = [{ demux: tsdemuxer, remux: mp4_remuxer }, { demux: mp4demuxer["a" /* default */], remux: passthrough_remuxer }, { demux: aacdemuxer, remux: mp4_remuxer }, { demux: mp3demuxer, remux: mp4_remuxer }];
  4929. // probe for content type
  4930. for (var i = 0, len = muxConfig.length; i < len; i++) {
  4931. var mux = muxConfig[i];
  4932. var probe = mux.demux.probe;
  4933. if (probe(data)) {
  4934. var _remuxer = this.remuxer = new mux.remux(observer, config, typeSupported, this.vendor);
  4935. demuxer = new mux.demux(observer, _remuxer, config, typeSupported);
  4936. this.probe = probe;
  4937. break;
  4938. }
  4939. }
  4940. if (!demuxer) {
  4941. observer.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_PARSING_ERROR, fatal: true, reason: 'no demux matching with content found' });
  4942. return;
  4943. }
  4944. this.demuxer = demuxer;
  4945. }
  4946. var remuxer = this.remuxer;
  4947. if (discontinuity || trackSwitch) {
  4948. demuxer.resetInitSegment(initSegment, audioCodec, videoCodec, duration);
  4949. remuxer.resetInitSegment();
  4950. }
  4951. if (discontinuity) {
  4952. demuxer.resetTimeStamp(defaultInitPTS);
  4953. remuxer.resetTimeStamp(defaultInitPTS);
  4954. }
  4955. if (typeof demuxer.setDecryptData === 'function') {
  4956. demuxer.setDecryptData(decryptdata);
  4957. }
  4958. demuxer.append(data, timeOffset, contiguous, accurateTimeOffset);
  4959. };
  4960. return DemuxerInline;
  4961. }();
  4962. /* harmony default export */ var demuxer_inline = __webpack_exports__["a"] = (demuxer_inline_DemuxerInline);
  4963. /***/ }),
  4964. /* 9 */
  4965. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  4966. "use strict";
  4967. Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
  4968. var cues_namespaceObject = {};
  4969. __webpack_require__.d(cues_namespaceObject, "newCue", function() { return newCue; });
  4970. // EXTERNAL MODULE: ./node_modules/url-toolkit/src/url-toolkit.js
  4971. var url_toolkit = __webpack_require__(3);
  4972. var url_toolkit_default = /*#__PURE__*/__webpack_require__.n(url_toolkit);
  4973. // EXTERNAL MODULE: ./src/events.js
  4974. var events = __webpack_require__(1);
  4975. // EXTERNAL MODULE: ./src/errors.js
  4976. var errors = __webpack_require__(2);
  4977. // EXTERNAL MODULE: ./src/utils/logger.js
  4978. var logger = __webpack_require__(0);
  4979. // CONCATENATED MODULE: ./src/event-handler.js
  4980. 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; };
  4981. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  4982. /*
  4983. *
  4984. * All objects in the event handling chain should inherit from this class
  4985. *
  4986. */
  4987. var FORBIDDEN_EVENT_NAMES = new Set(['hlsEventGeneric', 'hlsHandlerDestroying', 'hlsHandlerDestroyed']);
  4988. var event_handler_EventHandler = function () {
  4989. function EventHandler(hls) {
  4990. _classCallCheck(this, EventHandler);
  4991. this.hls = hls;
  4992. this.onEvent = this.onEvent.bind(this);
  4993. for (var _len = arguments.length, events = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4994. events[_key - 1] = arguments[_key];
  4995. }
  4996. this.handledEvents = events;
  4997. this.useGenericHandler = true;
  4998. this.registerListeners();
  4999. }
  5000. EventHandler.prototype.destroy = function destroy() {
  5001. this.onHandlerDestroying();
  5002. this.unregisterListeners();
  5003. this.onHandlerDestroyed();
  5004. };
  5005. EventHandler.prototype.onHandlerDestroying = function onHandlerDestroying() {};
  5006. EventHandler.prototype.onHandlerDestroyed = function onHandlerDestroyed() {};
  5007. EventHandler.prototype.isEventHandler = function isEventHandler() {
  5008. return _typeof(this.handledEvents) === 'object' && this.handledEvents.length && typeof this.onEvent === 'function';
  5009. };
  5010. EventHandler.prototype.registerListeners = function registerListeners() {
  5011. if (this.isEventHandler()) {
  5012. this.handledEvents.forEach(function (event) {
  5013. if (FORBIDDEN_EVENT_NAMES.has(event)) {
  5014. throw new Error('Forbidden event-name: ' + event);
  5015. }
  5016. this.hls.on(event, this.onEvent);
  5017. }, this);
  5018. }
  5019. };
  5020. EventHandler.prototype.unregisterListeners = function unregisterListeners() {
  5021. if (this.isEventHandler()) {
  5022. this.handledEvents.forEach(function (event) {
  5023. this.hls.off(event, this.onEvent);
  5024. }, this);
  5025. }
  5026. };
  5027. /**
  5028. * arguments: event (string), data (any)
  5029. */
  5030. EventHandler.prototype.onEvent = function onEvent(event, data) {
  5031. this.onEventGeneric(event, data);
  5032. };
  5033. EventHandler.prototype.onEventGeneric = function onEventGeneric(event, data) {
  5034. var eventToFunction = function eventToFunction(event, data) {
  5035. var funcName = 'on' + event.replace('hls', '');
  5036. if (typeof this[funcName] !== 'function') {
  5037. throw new Error('Event ' + event + ' has no generic handler in this ' + this.constructor.name + ' class (tried ' + funcName + ')');
  5038. }
  5039. return this[funcName].bind(this, data);
  5040. };
  5041. try {
  5042. eventToFunction.call(this, event, data).call();
  5043. } catch (err) {
  5044. logger["b" /* logger */].error('An internal error happened while handling event ' + event + '. Error message: "' + err.message + '". Here is a stacktrace:', err);
  5045. this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].OTHER_ERROR, details: errors["a" /* ErrorDetails */].INTERNAL_EXCEPTION, fatal: false, event: event, err: err });
  5046. }
  5047. };
  5048. return EventHandler;
  5049. }();
  5050. /* harmony default export */ var event_handler = (event_handler_EventHandler);
  5051. // EXTERNAL MODULE: ./src/demux/mp4demuxer.js
  5052. var mp4demuxer = __webpack_require__(7);
  5053. // CONCATENATED MODULE: ./src/loader/level-key.js
  5054. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  5055. function level_key__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5056. var level_key_LevelKey = function () {
  5057. function LevelKey() {
  5058. level_key__classCallCheck(this, LevelKey);
  5059. this.method = null;
  5060. this.key = null;
  5061. this.iv = null;
  5062. this._uri = null;
  5063. }
  5064. _createClass(LevelKey, [{
  5065. key: 'uri',
  5066. get: function get() {
  5067. if (!this._uri && this.reluri) {
  5068. this._uri = url_toolkit_default.a.buildAbsoluteURL(this.baseuri, this.reluri, { alwaysNormalize: true });
  5069. }
  5070. return this._uri;
  5071. }
  5072. }]);
  5073. return LevelKey;
  5074. }();
  5075. /* harmony default export */ var level_key = (level_key_LevelKey);
  5076. // CONCATENATED MODULE: ./src/loader/fragment.js
  5077. var fragment__createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  5078. function fragment__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5079. var fragment_Fragment = function () {
  5080. function Fragment() {
  5081. fragment__classCallCheck(this, Fragment);
  5082. this._url = null;
  5083. this._byteRange = null;
  5084. this._decryptdata = null;
  5085. this.tagList = [];
  5086. }
  5087. /**
  5088. * Utility method for parseLevelPlaylist to create an initialization vector for a given segment
  5089. * @returns {Uint8Array}
  5090. */
  5091. Fragment.prototype.createInitializationVector = function createInitializationVector(segmentNumber) {
  5092. var uint8View = new Uint8Array(16);
  5093. for (var i = 12; i < 16; i++) {
  5094. uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff;
  5095. }
  5096. return uint8View;
  5097. };
  5098. /**
  5099. * Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data
  5100. * @param levelkey - a playlist's encryption info
  5101. * @param segmentNumber - the fragment's segment number
  5102. * @returns {*} - an object to be applied as a fragment's decryptdata
  5103. */
  5104. Fragment.prototype.fragmentDecryptdataFromLevelkey = function fragmentDecryptdataFromLevelkey(levelkey, segmentNumber) {
  5105. var decryptdata = levelkey;
  5106. if (levelkey && levelkey.method && levelkey.uri && !levelkey.iv) {
  5107. decryptdata = new level_key();
  5108. decryptdata.method = levelkey.method;
  5109. decryptdata.baseuri = levelkey.baseuri;
  5110. decryptdata.reluri = levelkey.reluri;
  5111. decryptdata.iv = this.createInitializationVector(segmentNumber);
  5112. }
  5113. return decryptdata;
  5114. };
  5115. Fragment.prototype.cloneObj = function cloneObj(obj) {
  5116. return JSON.parse(JSON.stringify(obj));
  5117. };
  5118. fragment__createClass(Fragment, [{
  5119. key: 'url',
  5120. get: function get() {
  5121. if (!this._url && this.relurl) {
  5122. this._url = url_toolkit_default.a.buildAbsoluteURL(this.baseurl, this.relurl, { alwaysNormalize: true });
  5123. }
  5124. return this._url;
  5125. },
  5126. set: function set(value) {
  5127. this._url = value;
  5128. }
  5129. }, {
  5130. key: 'programDateTime',
  5131. get: function get() {
  5132. if (!this._programDateTime && this.rawProgramDateTime) {
  5133. this._programDateTime = new Date(Date.parse(this.rawProgramDateTime));
  5134. }
  5135. return this._programDateTime;
  5136. }
  5137. }, {
  5138. key: 'byteRange',
  5139. get: function get() {
  5140. if (!this._byteRange && !this.rawByteRange) {
  5141. return [];
  5142. }
  5143. if (this._byteRange) {
  5144. return this._byteRange;
  5145. }
  5146. var byteRange = [];
  5147. if (this.rawByteRange) {
  5148. var params = this.rawByteRange.split('@', 2);
  5149. if (params.length === 1) {
  5150. var lastByteRangeEndOffset = this.lastByteRangeEndOffset;
  5151. byteRange[0] = lastByteRangeEndOffset ? lastByteRangeEndOffset : 0;
  5152. } else {
  5153. byteRange[0] = parseInt(params[1]);
  5154. }
  5155. byteRange[1] = parseInt(params[0]) + byteRange[0];
  5156. this._byteRange = byteRange;
  5157. }
  5158. return byteRange;
  5159. }
  5160. }, {
  5161. key: 'byteRangeStartOffset',
  5162. get: function get() {
  5163. return this.byteRange[0];
  5164. }
  5165. }, {
  5166. key: 'byteRangeEndOffset',
  5167. get: function get() {
  5168. return this.byteRange[1];
  5169. }
  5170. }, {
  5171. key: 'decryptdata',
  5172. get: function get() {
  5173. if (!this._decryptdata) {
  5174. this._decryptdata = this.fragmentDecryptdataFromLevelkey(this.levelkey, this.sn);
  5175. }
  5176. return this._decryptdata;
  5177. }
  5178. }]);
  5179. return Fragment;
  5180. }();
  5181. /* harmony default export */ var loader_fragment = (fragment_Fragment);
  5182. // CONCATENATED MODULE: ./src/utils/attr-list.js
  5183. function attr_list__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5184. var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/;
  5185. var ATTR_LIST_REGEX = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g;
  5186. // adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
  5187. var AttrList = function () {
  5188. function AttrList(attrs) {
  5189. attr_list__classCallCheck(this, AttrList);
  5190. if (typeof attrs === 'string') {
  5191. attrs = AttrList.parseAttrList(attrs);
  5192. }
  5193. for (var attr in attrs) {
  5194. if (attrs.hasOwnProperty(attr)) {
  5195. this[attr] = attrs[attr];
  5196. }
  5197. }
  5198. }
  5199. AttrList.prototype.decimalInteger = function decimalInteger(attrName) {
  5200. var intValue = parseInt(this[attrName], 10);
  5201. if (intValue > Number.MAX_SAFE_INTEGER) {
  5202. return Infinity;
  5203. }
  5204. return intValue;
  5205. };
  5206. AttrList.prototype.hexadecimalInteger = function hexadecimalInteger(attrName) {
  5207. if (this[attrName]) {
  5208. var stringValue = (this[attrName] || '0x').slice(2);
  5209. stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;
  5210. var value = new Uint8Array(stringValue.length / 2);
  5211. for (var i = 0; i < stringValue.length / 2; i++) {
  5212. value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
  5213. }
  5214. return value;
  5215. } else {
  5216. return null;
  5217. }
  5218. };
  5219. AttrList.prototype.hexadecimalIntegerAsNumber = function hexadecimalIntegerAsNumber(attrName) {
  5220. var intValue = parseInt(this[attrName], 16);
  5221. if (intValue > Number.MAX_SAFE_INTEGER) {
  5222. return Infinity;
  5223. }
  5224. return intValue;
  5225. };
  5226. AttrList.prototype.decimalFloatingPoint = function decimalFloatingPoint(attrName) {
  5227. return parseFloat(this[attrName]);
  5228. };
  5229. AttrList.prototype.enumeratedString = function enumeratedString(attrName) {
  5230. return this[attrName];
  5231. };
  5232. AttrList.prototype.decimalResolution = function decimalResolution(attrName) {
  5233. var res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
  5234. if (res === null) {
  5235. return undefined;
  5236. }
  5237. return {
  5238. width: parseInt(res[1], 10),
  5239. height: parseInt(res[2], 10)
  5240. };
  5241. };
  5242. AttrList.parseAttrList = function parseAttrList(input) {
  5243. var match,
  5244. attrs = {};
  5245. ATTR_LIST_REGEX.lastIndex = 0;
  5246. while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
  5247. var value = match[2],
  5248. quote = '"';
  5249. if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) {
  5250. value = value.slice(1, -1);
  5251. }
  5252. attrs[match[1]] = value;
  5253. }
  5254. return attrs;
  5255. };
  5256. return AttrList;
  5257. }();
  5258. /* harmony default export */ var attr_list = (AttrList);
  5259. // CONCATENATED MODULE: ./src/utils/codecs.js
  5260. // from http://mp4ra.org/codecs.html
  5261. var sampleEntryCodesISO = {
  5262. audio: {
  5263. 'a3ds': true,
  5264. 'ac-3': true,
  5265. 'ac-4': true,
  5266. 'alac': true,
  5267. 'alaw': true,
  5268. 'dra1': true,
  5269. 'dts+': true,
  5270. 'dts-': true,
  5271. 'dtsc': true,
  5272. 'dtse': true,
  5273. 'dtsh': true,
  5274. 'ec-3': true,
  5275. 'enca': true,
  5276. 'g719': true,
  5277. 'g726': true,
  5278. 'm4ae': true,
  5279. 'mha1': true,
  5280. 'mha2': true,
  5281. 'mhm1': true,
  5282. 'mhm2': true,
  5283. 'mlpa': true,
  5284. 'mp4a': true,
  5285. 'raw ': true,
  5286. 'Opus': true,
  5287. 'samr': true,
  5288. 'sawb': true,
  5289. 'sawp': true,
  5290. 'sevc': true,
  5291. 'sqcp': true,
  5292. 'ssmv': true,
  5293. 'twos': true,
  5294. 'ulaw': true
  5295. },
  5296. video: {
  5297. 'avc1': true,
  5298. 'avc2': true,
  5299. 'avc3': true,
  5300. 'avc4': true,
  5301. 'avcp': true,
  5302. 'drac': true,
  5303. 'dvav': true,
  5304. 'dvhe': true,
  5305. 'encv': true,
  5306. 'hev1': true,
  5307. 'hvc1': true,
  5308. 'mjp2': true,
  5309. 'mp4v': true,
  5310. 'mvc1': true,
  5311. 'mvc2': true,
  5312. 'mvc3': true,
  5313. 'mvc4': true,
  5314. 'resv': true,
  5315. 'rv60': true,
  5316. 's263': true,
  5317. 'svc1': true,
  5318. 'svc2': true,
  5319. 'vc-1': true,
  5320. 'vp08': true,
  5321. 'vp09': true
  5322. }
  5323. };
  5324. function isCodecType(codec, type) {
  5325. var typeCodes = sampleEntryCodesISO[type];
  5326. return !!typeCodes && typeCodes[codec.slice(0, 4)] === true;
  5327. }
  5328. function isCodecSupportedInMp4(codec, type) {
  5329. return MediaSource.isTypeSupported((type || 'video') + '/mp4;codecs="' + codec + '"');
  5330. }
  5331. // CONCATENATED MODULE: ./src/loader/m3u8-parser.js
  5332. function m3u8_parser__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5333. /**
  5334. * M3U8 parser
  5335. * @module
  5336. */
  5337. // https://regex101.com is your friend
  5338. var MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g;
  5339. var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
  5340. var LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source, // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
  5341. /|(?!#)(\S+)/.source, // segment URI, group 3 => the URI (note newline is not eaten)
  5342. /|#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y)
  5343. /|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec
  5344. /|#.*/.source // All other non-segment oriented tags will match with all groups empty
  5345. ].join(''), 'g');
  5346. 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?/;
  5347. var m3u8_parser_M3U8Parser = function () {
  5348. function M3U8Parser() {
  5349. m3u8_parser__classCallCheck(this, M3U8Parser);
  5350. }
  5351. M3U8Parser.findGroup = function findGroup(groups, mediaGroupId) {
  5352. if (!groups) {
  5353. return null;
  5354. }
  5355. var matchingGroup = null;
  5356. for (var i = 0; i < groups.length; i++) {
  5357. var group = groups[i];
  5358. if (group.id === mediaGroupId) {
  5359. matchingGroup = group;
  5360. }
  5361. }
  5362. return matchingGroup;
  5363. };
  5364. M3U8Parser.convertAVC1ToAVCOTI = function convertAVC1ToAVCOTI(codec) {
  5365. var result,
  5366. avcdata = codec.split('.');
  5367. if (avcdata.length > 2) {
  5368. result = avcdata.shift() + '.';
  5369. result += parseInt(avcdata.shift()).toString(16);
  5370. result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4);
  5371. } else {
  5372. result = codec;
  5373. }
  5374. return result;
  5375. };
  5376. M3U8Parser.resolve = function resolve(url, baseUrl) {
  5377. return url_toolkit_default.a.buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true });
  5378. };
  5379. M3U8Parser.parseMasterPlaylist = function parseMasterPlaylist(string, baseurl) {
  5380. var levels = [],
  5381. result = void 0;
  5382. MASTER_PLAYLIST_REGEX.lastIndex = 0;
  5383. function setCodecs(codecs, level) {
  5384. ['video', 'audio'].forEach(function (type) {
  5385. var filtered = codecs.filter(function (codec) {
  5386. return isCodecType(codec, type);
  5387. });
  5388. if (filtered.length) {
  5389. var preferred = filtered.filter(function (codec) {
  5390. return codec.lastIndexOf('avc1', 0) === 0 || codec.lastIndexOf('mp4a', 0) === 0;
  5391. });
  5392. level[type + 'Codec'] = preferred.length > 0 ? preferred[0] : filtered[0];
  5393. // remove from list
  5394. codecs = codecs.filter(function (codec) {
  5395. return filtered.indexOf(codec) === -1;
  5396. });
  5397. }
  5398. });
  5399. level.unknownCodecs = codecs;
  5400. }
  5401. while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
  5402. var level = {};
  5403. var attrs = level.attrs = new attr_list(result[1]);
  5404. level.url = M3U8Parser.resolve(result[2], baseurl);
  5405. var resolution = attrs.decimalResolution('RESOLUTION');
  5406. if (resolution) {
  5407. level.width = resolution.width;
  5408. level.height = resolution.height;
  5409. }
  5410. level.bitrate = attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH');
  5411. level.name = attrs.NAME;
  5412. setCodecs([].concat((attrs.CODECS || '').split(/[ ,]+/)), level);
  5413. if (level.videoCodec && level.videoCodec.indexOf('avc1') !== -1) {
  5414. level.videoCodec = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);
  5415. }
  5416. levels.push(level);
  5417. }
  5418. return levels;
  5419. };
  5420. M3U8Parser.parseMasterPlaylistMedia = function parseMasterPlaylistMedia(string, baseurl, type) {
  5421. var audioGroups = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
  5422. var result = void 0;
  5423. var medias = [];
  5424. var id = 0;
  5425. MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
  5426. while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
  5427. var media = {};
  5428. var attrs = new attr_list(result[1]);
  5429. if (attrs.TYPE === type) {
  5430. media.groupId = attrs['GROUP-ID'];
  5431. media.name = attrs.NAME;
  5432. media.type = type;
  5433. media.default = attrs.DEFAULT === 'YES';
  5434. media.autoselect = attrs.AUTOSELECT === 'YES';
  5435. media.forced = attrs.FORCED === 'YES';
  5436. if (attrs.URI) {
  5437. media.url = M3U8Parser.resolve(attrs.URI, baseurl);
  5438. }
  5439. media.lang = attrs.LANGUAGE;
  5440. if (!media.name) {
  5441. media.name = media.lang;
  5442. }
  5443. if (audioGroups.length) {
  5444. var groupCodec = M3U8Parser.findGroup(audioGroups, media.groupId);
  5445. media.audioCodec = groupCodec ? groupCodec.codec : audioGroups[0].codec;
  5446. }
  5447. media.id = id++;
  5448. medias.push(media);
  5449. }
  5450. }
  5451. return medias;
  5452. };
  5453. M3U8Parser.parseLevelPlaylist = function parseLevelPlaylist(string, baseurl, id, type) {
  5454. var currentSN = 0,
  5455. totalduration = 0,
  5456. level = { type: null, version: null, url: baseurl, fragments: [], live: true, startSN: 0 },
  5457. levelkey = new level_key(),
  5458. cc = 0,
  5459. prevFrag = null,
  5460. frag = new loader_fragment(),
  5461. result,
  5462. i;
  5463. LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
  5464. while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
  5465. var duration = result[1];
  5466. if (duration) {
  5467. // INF
  5468. frag.duration = parseFloat(duration);
  5469. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  5470. var title = (' ' + result[2]).slice(1);
  5471. frag.title = title ? title : null;
  5472. frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);
  5473. } else if (result[3]) {
  5474. // url
  5475. if (!isNaN(frag.duration)) {
  5476. var sn = currentSN++;
  5477. frag.type = type;
  5478. frag.start = totalduration;
  5479. frag.levelkey = levelkey;
  5480. frag.sn = sn;
  5481. frag.level = id;
  5482. frag.cc = cc;
  5483. frag.baseurl = baseurl;
  5484. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  5485. frag.relurl = (' ' + result[3]).slice(1);
  5486. level.fragments.push(frag);
  5487. prevFrag = frag;
  5488. totalduration += frag.duration;
  5489. frag = new loader_fragment();
  5490. }
  5491. } else if (result[4]) {
  5492. // X-BYTERANGE
  5493. frag.rawByteRange = (' ' + result[4]).slice(1);
  5494. if (prevFrag) {
  5495. var lastByteRangeEndOffset = prevFrag.byteRangeEndOffset;
  5496. if (lastByteRangeEndOffset) {
  5497. frag.lastByteRangeEndOffset = lastByteRangeEndOffset;
  5498. }
  5499. }
  5500. } else if (result[5]) {
  5501. // PROGRAM-DATE-TIME
  5502. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  5503. frag.rawProgramDateTime = (' ' + result[5]).slice(1);
  5504. frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);
  5505. if (level.programDateTime === undefined) {
  5506. level.programDateTime = new Date(new Date(Date.parse(result[5])) - 1000 * totalduration);
  5507. }
  5508. } else {
  5509. result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
  5510. for (i = 1; i < result.length; i++) {
  5511. if (result[i] !== undefined) {
  5512. break;
  5513. }
  5514. }
  5515. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  5516. var value1 = (' ' + result[i + 1]).slice(1);
  5517. var value2 = (' ' + result[i + 2]).slice(1);
  5518. switch (result[i]) {
  5519. case '#':
  5520. frag.tagList.push(value2 ? [value1, value2] : [value1]);
  5521. break;
  5522. case 'PLAYLIST-TYPE':
  5523. level.type = value1.toUpperCase();
  5524. break;
  5525. case 'MEDIA-SEQUENCE':
  5526. currentSN = level.startSN = parseInt(value1);
  5527. break;
  5528. case 'TARGETDURATION':
  5529. level.targetduration = parseFloat(value1);
  5530. break;
  5531. case 'VERSION':
  5532. level.version = parseInt(value1);
  5533. break;
  5534. case 'EXTM3U':
  5535. break;
  5536. case 'ENDLIST':
  5537. level.live = false;
  5538. break;
  5539. case 'DIS':
  5540. cc++;
  5541. frag.tagList.push(['DIS']);
  5542. break;
  5543. case 'DISCONTINUITY-SEQ':
  5544. cc = parseInt(value1);
  5545. break;
  5546. case 'KEY':
  5547. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-08#section-3.4.4
  5548. var decryptparams = value1;
  5549. var keyAttrs = new attr_list(decryptparams);
  5550. var decryptmethod = keyAttrs.enumeratedString('METHOD'),
  5551. decrypturi = keyAttrs.URI,
  5552. decryptiv = keyAttrs.hexadecimalInteger('IV');
  5553. if (decryptmethod) {
  5554. levelkey = new level_key();
  5555. if (decrypturi && ['AES-128', 'SAMPLE-AES', 'SAMPLE-AES-CENC'].indexOf(decryptmethod) >= 0) {
  5556. levelkey.method = decryptmethod;
  5557. // URI to get the key
  5558. levelkey.baseuri = baseurl;
  5559. levelkey.reluri = decrypturi;
  5560. levelkey.key = null;
  5561. // Initialization Vector (IV)
  5562. levelkey.iv = decryptiv;
  5563. }
  5564. }
  5565. break;
  5566. case 'START':
  5567. var startParams = value1;
  5568. var startAttrs = new attr_list(startParams);
  5569. var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');
  5570. //TIME-OFFSET can be 0
  5571. if (!isNaN(startTimeOffset)) {
  5572. level.startTimeOffset = startTimeOffset;
  5573. }
  5574. break;
  5575. case 'MAP':
  5576. var mapAttrs = new attr_list(value1);
  5577. frag.relurl = mapAttrs.URI;
  5578. frag.rawByteRange = mapAttrs.BYTERANGE;
  5579. frag.baseurl = baseurl;
  5580. frag.level = id;
  5581. frag.type = type;
  5582. frag.sn = 'initSegment';
  5583. level.initSegment = frag;
  5584. frag = new loader_fragment();
  5585. break;
  5586. default:
  5587. logger["b" /* logger */].warn('line parsed but not handled: ' + result);
  5588. break;
  5589. }
  5590. }
  5591. }
  5592. frag = prevFrag;
  5593. //logger.log('found ' + level.fragments.length + ' fragments');
  5594. if (frag && !frag.relurl) {
  5595. level.fragments.pop();
  5596. totalduration -= frag.duration;
  5597. }
  5598. level.totalduration = totalduration;
  5599. level.averagetargetduration = totalduration / level.fragments.length;
  5600. level.endSN = currentSN - 1;
  5601. level.startCC = level.fragments[0] ? level.fragments[0].cc : 0;
  5602. level.endCC = cc;
  5603. if (!level.initSegment && level.fragments.length) {
  5604. // this is a bit lurky but HLS really has no other way to tell us
  5605. // if the fragments are TS or MP4, except if we download them :/
  5606. // but this is to be able to handle SIDX.
  5607. // FIXME: replace string test by a regex that matches
  5608. // also `m4s` `m4a` `m4v` and other popular extensions
  5609. if (level.fragments.every(function (frag) {
  5610. return frag.relurl.endsWith('.mp4');
  5611. })) {
  5612. logger["b" /* logger */].warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX');
  5613. frag = new loader_fragment();
  5614. frag.relurl = level.fragments[0].relurl;
  5615. frag.baseurl = baseurl;
  5616. frag.level = id;
  5617. frag.type = type;
  5618. frag.sn = 'initSegment';
  5619. level.initSegment = frag;
  5620. level.needSidxRanges = true;
  5621. }
  5622. }
  5623. return level;
  5624. };
  5625. return M3U8Parser;
  5626. }();
  5627. /* harmony default export */ var m3u8_parser = (m3u8_parser_M3U8Parser);
  5628. // CONCATENATED MODULE: ./src/loader/playlist-loader.js
  5629. var playlist_loader__createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  5630. function playlist_loader__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5631. 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; }
  5632. 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; }
  5633. /**
  5634. * PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models.
  5635. *
  5636. * Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks.
  5637. *
  5638. * Uses loader(s) set in config to do actual internal loading of resource tasks.
  5639. *
  5640. * @module
  5641. *
  5642. */
  5643. /**
  5644. * `type` property values for this loaders' context object
  5645. * @enum
  5646. *
  5647. */
  5648. var ContextType = {
  5649. MANIFEST: 'manifest',
  5650. LEVEL: 'level',
  5651. AUDIO_TRACK: 'audioTrack',
  5652. SUBTITLE_TRACK: 'subtitleTrack'
  5653. };
  5654. /**
  5655. * @constructor
  5656. */
  5657. var playlist_loader_PlaylistLoader = function (_EventHandler) {
  5658. _inherits(PlaylistLoader, _EventHandler);
  5659. /**
  5660. * @constructs
  5661. * @param {Hls} hls
  5662. */
  5663. function PlaylistLoader(hls) {
  5664. playlist_loader__classCallCheck(this, PlaylistLoader);
  5665. var _this = _possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MANIFEST_LOADING, events["a" /* default */].LEVEL_LOADING, events["a" /* default */].AUDIO_TRACK_LOADING, events["a" /* default */].SUBTITLE_TRACK_LOADING));
  5666. _this.loaders = {};
  5667. return _this;
  5668. }
  5669. /**
  5670. * @param {ContextType} type
  5671. * @returns {boolean}
  5672. */
  5673. PlaylistLoader.canHaveQualityLevels = function canHaveQualityLevels(type) {
  5674. return type !== ContextType.AUDIO_TRACK && type !== ContextType.SUBTITLE_TRACK;
  5675. };
  5676. PlaylistLoader.mapContextToLevelType = function mapContextToLevelType(context) {
  5677. var type = context.type;
  5678. switch (type) {
  5679. case ContextType.AUDIO_TRACK:
  5680. return 'audio';
  5681. case ContextType.SUBTITLE_TRACK:
  5682. return 'subtitle';
  5683. default:
  5684. return 'main';
  5685. }
  5686. };
  5687. PlaylistLoader.getResponseUrl = function getResponseUrl(response, context) {
  5688. var url = response.url;
  5689. // responseURL not supported on some browsers (it is used to detect URL redirection)
  5690. // data-uri mode also not supported (but no need to detect redirection)
  5691. if (url === undefined || url.indexOf('data:') === 0) {
  5692. // fallback to initial URL
  5693. url = context.url;
  5694. }
  5695. return url;
  5696. };
  5697. /**
  5698. * Returns defaults or configured loader-type overloads (pLoader and loader config params)
  5699. * Default loader is XHRLoader (see utils)
  5700. * @param {object} context
  5701. * @returns {XHRLoader} or other compatible configured overload
  5702. */
  5703. PlaylistLoader.prototype.createInternalLoader = function createInternalLoader(context) {
  5704. var config = this.hls.config;
  5705. var PLoader = config.pLoader;
  5706. var Loader = config.loader;
  5707. var InternalLoader = PLoader || Loader;
  5708. var loader = new InternalLoader(config);
  5709. context.loader = Loader;
  5710. this.loaders[context.type] = loader;
  5711. return loader;
  5712. };
  5713. PlaylistLoader.prototype.getInternalLoader = function getInternalLoader(context) {
  5714. return this.loaders[context.type];
  5715. };
  5716. PlaylistLoader.prototype.resetInternalLoader = function resetInternalLoader(contextType) {
  5717. if (this.loaders[contextType]) {
  5718. delete this.loaders[contextType];
  5719. }
  5720. };
  5721. /**
  5722. * Call `destroy` on all internal loader instances mapped (one per context type)
  5723. */
  5724. PlaylistLoader.prototype.destroyInternalLoaders = function destroyInternalLoaders() {
  5725. for (var contextType in this.loaders) {
  5726. var loader = this.loaders[contextType];
  5727. if (loader) {
  5728. loader.destroy();
  5729. }
  5730. this.resetInternalLoader(contextType);
  5731. }
  5732. };
  5733. PlaylistLoader.prototype.destroy = function destroy() {
  5734. this.destroyInternalLoaders();
  5735. _EventHandler.prototype.destroy.call(this);
  5736. };
  5737. PlaylistLoader.prototype.onManifestLoading = function onManifestLoading(data) {
  5738. this.load(data.url, { type: ContextType.MANIFEST });
  5739. };
  5740. PlaylistLoader.prototype.onLevelLoading = function onLevelLoading(data) {
  5741. this.load(data.url, { type: ContextType.LEVEL, level: data.level, id: data.id });
  5742. };
  5743. PlaylistLoader.prototype.onAudioTrackLoading = function onAudioTrackLoading(data) {
  5744. this.load(data.url, { type: ContextType.AUDIO_TRACK, id: data.id });
  5745. };
  5746. PlaylistLoader.prototype.onSubtitleTrackLoading = function onSubtitleTrackLoading(data) {
  5747. this.load(data.url, { type: ContextType.SUBTITLE_TRACK, id: data.id });
  5748. };
  5749. PlaylistLoader.prototype.load = function load(url, context) {
  5750. var config = this.hls.config;
  5751. // Check if a loader for this context already exists
  5752. var loader = this.getInternalLoader(context);
  5753. if (loader) {
  5754. var loaderContext = loader.context;
  5755. if (loaderContext && loaderContext.url === url) {
  5756. // same URL can't overlap
  5757. logger["b" /* logger */].trace('playlist request ongoing');
  5758. return false;
  5759. } else {
  5760. logger["b" /* logger */].warn('aborting previous loader for type: ' + context.type);
  5761. loader.abort();
  5762. }
  5763. }
  5764. var maxRetry = void 0,
  5765. timeout = void 0,
  5766. retryDelay = void 0,
  5767. maxRetryDelay = void 0;
  5768. // apply different configs for retries depending on
  5769. // context (manifest, level, audio/subs playlist)
  5770. switch (context.type) {
  5771. case ContextType.MANIFEST:
  5772. maxRetry = config.manifestLoadingMaxRetry;
  5773. timeout = config.manifestLoadingTimeOut;
  5774. retryDelay = config.manifestLoadingRetryDelay;
  5775. maxRetryDelay = config.manifestLoadingMaxRetryTimeout;
  5776. break;
  5777. case ContextType.LEVEL:
  5778. // Disable internal loader retry logic, since we are managing retries in Level Controller
  5779. maxRetry = 0;
  5780. timeout = config.levelLoadingTimeOut;
  5781. // TODO Introduce retry settings for audio-track and subtitle-track, it should not use level retry config
  5782. break;
  5783. default:
  5784. maxRetry = config.levelLoadingMaxRetry;
  5785. timeout = config.levelLoadingTimeOut;
  5786. retryDelay = config.levelLoadingRetryDelay;
  5787. maxRetryDelay = config.levelLoadingMaxRetryTimeout;
  5788. logger["b" /* logger */].log('Playlist loader for ' + context.type + ' ' + (context.level || context.id));
  5789. break;
  5790. }
  5791. loader = this.createInternalLoader(context);
  5792. context.url = url;
  5793. context.responseType = context.responseType || ''; // FIXME: (should not be necessary to do this)
  5794. var loaderConfig = void 0,
  5795. loaderCallbacks = void 0;
  5796. loaderConfig = {
  5797. timeout: timeout,
  5798. maxRetry: maxRetry,
  5799. retryDelay: retryDelay,
  5800. maxRetryDelay: maxRetryDelay
  5801. };
  5802. loaderCallbacks = {
  5803. onSuccess: this.loadsuccess.bind(this),
  5804. onError: this.loaderror.bind(this),
  5805. onTimeout: this.loadtimeout.bind(this)
  5806. };
  5807. loader.load(context, loaderConfig, loaderCallbacks);
  5808. return true;
  5809. };
  5810. PlaylistLoader.prototype.loadsuccess = function loadsuccess(response, stats, context) {
  5811. var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
  5812. if (context.isSidxRequest) {
  5813. this._handleSidxRequest(response, context);
  5814. this._handlePlaylistLoaded(response, stats, context, networkDetails);
  5815. return;
  5816. }
  5817. this.resetInternalLoader(context.type);
  5818. var string = response.data;
  5819. stats.tload = performance.now();
  5820. //stats.mtime = new Date(target.getResponseHeader('Last-Modified'));
  5821. // Validate if it is an M3U8 at all
  5822. if (string.indexOf('#EXTM3U') !== 0) {
  5823. this._handleManifestParsingError(response, context, 'no EXTM3U delimiter', networkDetails);
  5824. return;
  5825. }
  5826. // Check if chunk-list or master
  5827. if (string.indexOf('#EXTINF:') > 0) {
  5828. this._handleTrackOrLevelPlaylist(response, stats, context, networkDetails);
  5829. } else {
  5830. this._handleMasterPlaylist(response, stats, context, networkDetails);
  5831. }
  5832. };
  5833. PlaylistLoader.prototype.loaderror = function loaderror(response, context) {
  5834. var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  5835. this._handleNetworkError(context, networkDetails);
  5836. };
  5837. PlaylistLoader.prototype.loadtimeout = function loadtimeout(stats, context) {
  5838. var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  5839. this._handleNetworkError(context, networkDetails);
  5840. };
  5841. PlaylistLoader.prototype._handleMasterPlaylist = function _handleMasterPlaylist(response, stats, context, networkDetails) {
  5842. var hls = this.hls;
  5843. var string = response.data;
  5844. var url = PlaylistLoader.getResponseUrl(response, context);
  5845. var levels = m3u8_parser.parseMasterPlaylist(string, url);
  5846. if (!levels.length) {
  5847. this._handleManifestParsingError(response, context, 'no level found in manifest', networkDetails);
  5848. return;
  5849. }
  5850. // multi level playlist, parse level info
  5851. var audioGroups = levels.map(function (level) {
  5852. return {
  5853. id: level.attrs.AUDIO,
  5854. codec: level.audioCodec
  5855. };
  5856. });
  5857. var audioTracks = m3u8_parser.parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups);
  5858. var subtitles = m3u8_parser.parseMasterPlaylistMedia(string, url, 'SUBTITLES');
  5859. if (audioTracks.length) {
  5860. // check if we have found an audio track embedded in main playlist (audio track without URI attribute)
  5861. var embeddedAudioFound = false;
  5862. audioTracks.forEach(function (audioTrack) {
  5863. if (!audioTrack.url) {
  5864. embeddedAudioFound = true;
  5865. }
  5866. });
  5867. // if no embedded audio track defined, but audio codec signaled in quality level,
  5868. // we need to signal this main audio track this could happen with playlists with
  5869. // alt audio rendition in which quality levels (main)
  5870. // contains both audio+video. but with mixed audio track not signaled
  5871. if (embeddedAudioFound === false && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
  5872. logger["b" /* logger */].log('audio codec signaled in quality level, but no embedded audio track signaled, create one');
  5873. audioTracks.unshift({
  5874. type: 'main',
  5875. name: 'main'
  5876. });
  5877. }
  5878. }
  5879. hls.trigger(events["a" /* default */].MANIFEST_LOADED, {
  5880. levels: levels,
  5881. audioTracks: audioTracks,
  5882. subtitles: subtitles,
  5883. url: url,
  5884. stats: stats,
  5885. networkDetails: networkDetails
  5886. });
  5887. };
  5888. PlaylistLoader.prototype._handleTrackOrLevelPlaylist = function _handleTrackOrLevelPlaylist(response, stats, context, networkDetails) {
  5889. var hls = this.hls;
  5890. var id = context.id,
  5891. level = context.level,
  5892. type = context.type;
  5893. var url = PlaylistLoader.getResponseUrl(response, context);
  5894. var levelId = !isNaN(level) ? level : !isNaN(id) ? id : 0; // level -> id -> 0
  5895. var levelType = PlaylistLoader.mapContextToLevelType(context);
  5896. var levelDetails = m3u8_parser.parseLevelPlaylist(response.data, url, levelId, levelType);
  5897. // set stats on level structure
  5898. levelDetails.tload = stats.tload;
  5899. // We have done our first request (Manifest-type) and receive
  5900. // not a master playlist but a chunk-list (track/level)
  5901. // We fire the manifest-loaded event anyway with the parsed level-details
  5902. // by creating a single-level structure for it.
  5903. if (type === ContextType.MANIFEST) {
  5904. var singleLevel = {
  5905. url: url,
  5906. details: levelDetails
  5907. };
  5908. hls.trigger(events["a" /* default */].MANIFEST_LOADED, {
  5909. levels: [singleLevel],
  5910. audioTracks: [],
  5911. url: url,
  5912. stats: stats,
  5913. networkDetails: networkDetails
  5914. });
  5915. }
  5916. // save parsing time
  5917. stats.tparsed = performance.now();
  5918. // in case we need SIDX ranges
  5919. // return early after calling load for
  5920. // the SIDX box.
  5921. if (levelDetails.needSidxRanges) {
  5922. var sidxUrl = levelDetails.initSegment.url;
  5923. this.load(sidxUrl, {
  5924. isSidxRequest: true,
  5925. type: type,
  5926. level: level,
  5927. levelDetails: levelDetails,
  5928. id: id,
  5929. rangeStart: 0,
  5930. rangeEnd: 2048,
  5931. responseType: 'arraybuffer'
  5932. });
  5933. return;
  5934. }
  5935. // extend the context with the new levelDetails property
  5936. context.levelDetails = levelDetails;
  5937. this._handlePlaylistLoaded(response, stats, context, networkDetails);
  5938. };
  5939. PlaylistLoader.prototype._handleSidxRequest = function _handleSidxRequest(response, context) {
  5940. var sidxInfo = mp4demuxer["a" /* default */].parseSegmentIndex(new Uint8Array(response.data));
  5941. sidxInfo.references.forEach(function (segmentRef, index) {
  5942. var segRefInfo = segmentRef.info;
  5943. var frag = context.levelDetails.fragments[index];
  5944. if (frag.byteRange.length === 0) {
  5945. frag.rawByteRange = String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start);
  5946. }
  5947. });
  5948. context.levelDetails.initSegment.rawByteRange = String(sidxInfo.moovEndOffset) + '@0';
  5949. };
  5950. PlaylistLoader.prototype._handleManifestParsingError = function _handleManifestParsingError(response, context, reason, networkDetails) {
  5951. this.hls.trigger(events["a" /* default */].ERROR, {
  5952. type: errors["b" /* ErrorTypes */].NETWORK_ERROR,
  5953. details: errors["a" /* ErrorDetails */].MANIFEST_PARSING_ERROR,
  5954. fatal: true,
  5955. url: response.url,
  5956. reason: reason,
  5957. networkDetails: networkDetails
  5958. });
  5959. };
  5960. PlaylistLoader.prototype._handleNetworkError = function _handleNetworkError(context, networkDetails) {
  5961. var details = void 0;
  5962. var fatal = void 0;
  5963. var loader = context.loader;
  5964. switch (context.type) {
  5965. case ContextType.MANIFEST:
  5966. details = errors["a" /* ErrorDetails */].MANIFEST_LOAD_TIMEOUT;
  5967. fatal = true;
  5968. break;
  5969. case ContextType.LEVEL:
  5970. details = errors["a" /* ErrorDetails */].LEVEL_LOAD_TIMEOUT;
  5971. fatal = false;
  5972. break;
  5973. case ContextType.AUDIO_TRACK:
  5974. details = errors["a" /* ErrorDetails */].AUDIO_TRACK_LOAD_TIMEOUT;
  5975. fatal = false;
  5976. break;
  5977. default:
  5978. // details = ...?
  5979. fatal = false;
  5980. }
  5981. if (loader) {
  5982. loader.abort();
  5983. this.resetInternalLoader(context.type);
  5984. }
  5985. this.hls.trigger(events["a" /* default */].ERROR, {
  5986. type: errors["b" /* ErrorTypes */].NETWORK_ERROR,
  5987. details: details,
  5988. fatal: fatal,
  5989. url: loader.url,
  5990. loader: loader,
  5991. context: context,
  5992. networkDetails: networkDetails
  5993. });
  5994. };
  5995. PlaylistLoader.prototype._handlePlaylistLoaded = function _handlePlaylistLoaded(response, stats, context, networkDetails) {
  5996. var type = context.type,
  5997. level = context.level,
  5998. id = context.id,
  5999. levelDetails = context.levelDetails;
  6000. if (!levelDetails.targetduration) {
  6001. this._handleManifestParsingError(response, context, 'invalid target duration', networkDetails);
  6002. return;
  6003. }
  6004. var canHaveLevels = PlaylistLoader.canHaveQualityLevels(context.type);
  6005. if (canHaveLevels) {
  6006. this.hls.trigger(events["a" /* default */].LEVEL_LOADED, {
  6007. details: levelDetails,
  6008. level: level || 0,
  6009. id: id || 0,
  6010. stats: stats,
  6011. networkDetails: networkDetails
  6012. });
  6013. } else {
  6014. switch (type) {
  6015. case ContextType.AUDIO_TRACK:
  6016. this.hls.trigger(events["a" /* default */].AUDIO_TRACK_LOADED, {
  6017. details: levelDetails,
  6018. id: id,
  6019. stats: stats,
  6020. networkDetails: networkDetails
  6021. });
  6022. break;
  6023. case ContextType.SUBTITLE_TRACK:
  6024. this.hls.trigger(events["a" /* default */].SUBTITLE_TRACK_LOADED, {
  6025. details: levelDetails,
  6026. id: id,
  6027. stats: stats,
  6028. networkDetails: networkDetails
  6029. });
  6030. break;
  6031. }
  6032. }
  6033. };
  6034. playlist_loader__createClass(PlaylistLoader, null, [{
  6035. key: 'ContextType',
  6036. get: function get() {
  6037. return ContextType;
  6038. }
  6039. }]);
  6040. return PlaylistLoader;
  6041. }(event_handler);
  6042. /* harmony default export */ var playlist_loader = (playlist_loader_PlaylistLoader);
  6043. // CONCATENATED MODULE: ./src/loader/fragment-loader.js
  6044. function fragment_loader__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6045. function fragment_loader__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; }
  6046. function fragment_loader__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; }
  6047. /*
  6048. * Fragment Loader
  6049. */
  6050. var fragment_loader_FragmentLoader = function (_EventHandler) {
  6051. fragment_loader__inherits(FragmentLoader, _EventHandler);
  6052. function FragmentLoader(hls) {
  6053. fragment_loader__classCallCheck(this, FragmentLoader);
  6054. var _this = fragment_loader__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].FRAG_LOADING));
  6055. _this.loaders = {};
  6056. return _this;
  6057. }
  6058. FragmentLoader.prototype.destroy = function destroy() {
  6059. var loaders = this.loaders;
  6060. for (var loaderName in loaders) {
  6061. var loader = loaders[loaderName];
  6062. if (loader) {
  6063. loader.destroy();
  6064. }
  6065. }
  6066. this.loaders = {};
  6067. _EventHandler.prototype.destroy.call(this);
  6068. };
  6069. FragmentLoader.prototype.onFragLoading = function onFragLoading(data) {
  6070. var frag = data.frag,
  6071. type = frag.type,
  6072. loaders = this.loaders,
  6073. config = this.hls.config,
  6074. FragmentILoader = config.fLoader,
  6075. DefaultILoader = config.loader;
  6076. // reset fragment state
  6077. frag.loaded = 0;
  6078. var loader = loaders[type];
  6079. if (loader) {
  6080. logger["b" /* logger */].warn('abort previous fragment loader for type: ' + type);
  6081. loader.abort();
  6082. }
  6083. loader = loaders[type] = frag.loader = !!config.fLoader ? new FragmentILoader(config) : new DefaultILoader(config);
  6084. var loaderContext = void 0,
  6085. loaderConfig = void 0,
  6086. loaderCallbacks = void 0;
  6087. loaderContext = { url: frag.url, frag: frag, responseType: 'arraybuffer', progressData: false };
  6088. var start = frag.byteRangeStartOffset,
  6089. end = frag.byteRangeEndOffset;
  6090. if (!isNaN(start) && !isNaN(end)) {
  6091. loaderContext.rangeStart = start;
  6092. loaderContext.rangeEnd = end;
  6093. }
  6094. loaderConfig = {
  6095. timeout: config.fragLoadingTimeOut,
  6096. maxRetry: 0,
  6097. retryDelay: 0,
  6098. maxRetryDelay: config.fragLoadingMaxRetryTimeout
  6099. };
  6100. loaderCallbacks = {
  6101. onSuccess: this.loadsuccess.bind(this),
  6102. onError: this.loaderror.bind(this),
  6103. onTimeout: this.loadtimeout.bind(this),
  6104. onProgress: this.loadprogress.bind(this)
  6105. };
  6106. loader.load(loaderContext, loaderConfig, loaderCallbacks);
  6107. };
  6108. FragmentLoader.prototype.loadsuccess = function loadsuccess(response, stats, context) {
  6109. var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
  6110. var payload = response.data,
  6111. frag = context.frag;
  6112. // detach fragment loader on load success
  6113. frag.loader = undefined;
  6114. this.loaders[frag.type] = undefined;
  6115. this.hls.trigger(events["a" /* default */].FRAG_LOADED, { payload: payload, frag: frag, stats: stats, networkDetails: networkDetails });
  6116. };
  6117. FragmentLoader.prototype.loaderror = function loaderror(response, context) {
  6118. var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  6119. var loader = context.loader;
  6120. if (loader) {
  6121. loader.abort();
  6122. }
  6123. this.loaders[context.type] = undefined;
  6124. this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].FRAG_LOAD_ERROR, fatal: false, frag: context.frag, response: response, networkDetails: networkDetails });
  6125. };
  6126. FragmentLoader.prototype.loadtimeout = function loadtimeout(stats, context) {
  6127. var networkDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  6128. var loader = context.loader;
  6129. if (loader) {
  6130. loader.abort();
  6131. }
  6132. this.loaders[context.type] = undefined;
  6133. this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].FRAG_LOAD_TIMEOUT, fatal: false, frag: context.frag, networkDetails: networkDetails });
  6134. };
  6135. // data will be used for progressive parsing
  6136. FragmentLoader.prototype.loadprogress = function loadprogress(stats, context, data) {
  6137. var networkDetails = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
  6138. // jshint ignore:line
  6139. var frag = context.frag;
  6140. frag.loaded = stats.loaded;
  6141. this.hls.trigger(events["a" /* default */].FRAG_LOAD_PROGRESS, { frag: frag, stats: stats, networkDetails: networkDetails });
  6142. };
  6143. return FragmentLoader;
  6144. }(event_handler);
  6145. /* harmony default export */ var fragment_loader = (fragment_loader_FragmentLoader);
  6146. // CONCATENATED MODULE: ./src/loader/key-loader.js
  6147. function key_loader__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6148. function key_loader__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; }
  6149. function key_loader__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; }
  6150. /*
  6151. * Decrypt key Loader
  6152. */
  6153. var key_loader_KeyLoader = function (_EventHandler) {
  6154. key_loader__inherits(KeyLoader, _EventHandler);
  6155. function KeyLoader(hls) {
  6156. key_loader__classCallCheck(this, KeyLoader);
  6157. var _this = key_loader__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].KEY_LOADING));
  6158. _this.loaders = {};
  6159. _this.decryptkey = null;
  6160. _this.decrypturl = null;
  6161. return _this;
  6162. }
  6163. KeyLoader.prototype.destroy = function destroy() {
  6164. for (var loaderName in this.loaders) {
  6165. var loader = this.loaders[loaderName];
  6166. if (loader) {
  6167. loader.destroy();
  6168. }
  6169. }
  6170. this.loaders = {};
  6171. event_handler.prototype.destroy.call(this);
  6172. };
  6173. KeyLoader.prototype.onKeyLoading = function onKeyLoading(data) {
  6174. var frag = data.frag,
  6175. type = frag.type,
  6176. loader = this.loaders[type],
  6177. decryptdata = frag.decryptdata,
  6178. uri = decryptdata.uri;
  6179. // if uri is different from previous one or if decrypt key not retrieved yet
  6180. if (uri !== this.decrypturl || this.decryptkey === null) {
  6181. var config = this.hls.config;
  6182. if (loader) {
  6183. logger["b" /* logger */].warn('abort previous key loader for type:' + type);
  6184. loader.abort();
  6185. }
  6186. frag.loader = this.loaders[type] = new config.loader(config);
  6187. this.decrypturl = uri;
  6188. this.decryptkey = null;
  6189. var loaderContext = void 0,
  6190. loaderConfig = void 0,
  6191. loaderCallbacks = void 0;
  6192. loaderContext = { url: uri, frag: frag, responseType: 'arraybuffer' };
  6193. loaderConfig = { timeout: config.fragLoadingTimeOut, maxRetry: config.fragLoadingMaxRetry, retryDelay: config.fragLoadingRetryDelay, maxRetryDelay: config.fragLoadingMaxRetryTimeout };
  6194. loaderCallbacks = { onSuccess: this.loadsuccess.bind(this), onError: this.loaderror.bind(this), onTimeout: this.loadtimeout.bind(this) };
  6195. frag.loader.load(loaderContext, loaderConfig, loaderCallbacks);
  6196. } else if (this.decryptkey) {
  6197. // we already loaded this key, return it
  6198. decryptdata.key = this.decryptkey;
  6199. this.hls.trigger(events["a" /* default */].KEY_LOADED, { frag: frag });
  6200. }
  6201. };
  6202. KeyLoader.prototype.loadsuccess = function loadsuccess(response, stats, context) {
  6203. var frag = context.frag;
  6204. this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data);
  6205. // detach fragment loader on load success
  6206. frag.loader = undefined;
  6207. this.loaders[frag.type] = undefined;
  6208. this.hls.trigger(events["a" /* default */].KEY_LOADED, { frag: frag });
  6209. };
  6210. KeyLoader.prototype.loaderror = function loaderror(response, context) {
  6211. var frag = context.frag,
  6212. loader = frag.loader;
  6213. if (loader) {
  6214. loader.abort();
  6215. }
  6216. this.loaders[context.type] = undefined;
  6217. this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].KEY_LOAD_ERROR, fatal: false, frag: frag, response: response });
  6218. };
  6219. KeyLoader.prototype.loadtimeout = function loadtimeout(stats, context) {
  6220. var frag = context.frag,
  6221. loader = frag.loader;
  6222. if (loader) {
  6223. loader.abort();
  6224. }
  6225. this.loaders[context.type] = undefined;
  6226. this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].NETWORK_ERROR, details: errors["a" /* ErrorDetails */].KEY_LOAD_TIMEOUT, fatal: false, frag: frag });
  6227. };
  6228. return KeyLoader;
  6229. }(event_handler);
  6230. /* harmony default export */ var key_loader = (key_loader_KeyLoader);
  6231. // CONCATENATED MODULE: ./src/utils/binary-search.js
  6232. var BinarySearch = {
  6233. /**
  6234. * Searches for an item in an array which matches a certain condition.
  6235. * This requires the condition to only match one item in the array,
  6236. * and for the array to be ordered.
  6237. *
  6238. * @param {Array} list The array to search.
  6239. * @param {Function} comparisonFunction
  6240. * Called and provided a candidate item as the first argument.
  6241. * Should return:
  6242. * > -1 if the item should be located at a lower index than the provided item.
  6243. * > 1 if the item should be located at a higher index than the provided item.
  6244. * > 0 if the item is the item you're looking for.
  6245. *
  6246. * @return {*} The object if it is found or null otherwise.
  6247. */
  6248. search: function search(list, comparisonFunction) {
  6249. var minIndex = 0;
  6250. var maxIndex = list.length - 1;
  6251. var currentIndex = null;
  6252. var currentElement = null;
  6253. while (minIndex <= maxIndex) {
  6254. currentIndex = (minIndex + maxIndex) / 2 | 0;
  6255. currentElement = list[currentIndex];
  6256. var comparisonResult = comparisonFunction(currentElement);
  6257. if (comparisonResult > 0) {
  6258. minIndex = currentIndex + 1;
  6259. } else if (comparisonResult < 0) {
  6260. maxIndex = currentIndex - 1;
  6261. } else {
  6262. return currentElement;
  6263. }
  6264. }
  6265. return null;
  6266. }
  6267. };
  6268. /* harmony default export */ var binary_search = (BinarySearch);
  6269. // CONCATENATED MODULE: ./src/helper/buffer-helper.js
  6270. /**
  6271. * Buffer Helper utils, providing methods dealing buffer length retrieval
  6272. */
  6273. var BufferHelper = {
  6274. isBuffered: function isBuffered(media, position) {
  6275. try {
  6276. if (media) {
  6277. var buffered = media.buffered;
  6278. for (var i = 0; i < buffered.length; i++) {
  6279. if (position >= buffered.start(i) && position <= buffered.end(i)) {
  6280. return true;
  6281. }
  6282. }
  6283. }
  6284. } catch (error) {
  6285. // this is to catch
  6286. // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
  6287. // This SourceBuffer has been removed from the parent media source
  6288. }
  6289. return false;
  6290. },
  6291. bufferInfo: function bufferInfo(media, pos, maxHoleDuration) {
  6292. try {
  6293. if (media) {
  6294. var vbuffered = media.buffered,
  6295. buffered = [],
  6296. i;
  6297. for (i = 0; i < vbuffered.length; i++) {
  6298. buffered.push({ start: vbuffered.start(i), end: vbuffered.end(i) });
  6299. }
  6300. return this.bufferedInfo(buffered, pos, maxHoleDuration);
  6301. }
  6302. } catch (error) {
  6303. // this is to catch
  6304. // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
  6305. // This SourceBuffer has been removed from the parent media source
  6306. }
  6307. return { len: 0, start: pos, end: pos, nextStart: undefined };
  6308. },
  6309. bufferedInfo: function bufferedInfo(buffered, pos, maxHoleDuration) {
  6310. var buffered2 = [],
  6311. // bufferStart and bufferEnd are buffer boundaries around current video position
  6312. bufferLen,
  6313. bufferStart,
  6314. bufferEnd,
  6315. bufferStartNext,
  6316. i;
  6317. // sort on buffer.start/smaller end (IE does not always return sorted buffered range)
  6318. buffered.sort(function (a, b) {
  6319. var diff = a.start - b.start;
  6320. if (diff) {
  6321. return diff;
  6322. } else {
  6323. return b.end - a.end;
  6324. }
  6325. });
  6326. // there might be some small holes between buffer time range
  6327. // consider that holes smaller than maxHoleDuration are irrelevant and build another
  6328. // buffer time range representations that discards those holes
  6329. for (i = 0; i < buffered.length; i++) {
  6330. var buf2len = buffered2.length;
  6331. if (buf2len) {
  6332. var buf2end = buffered2[buf2len - 1].end;
  6333. // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)
  6334. if (buffered[i].start - buf2end < maxHoleDuration) {
  6335. // merge overlapping time ranges
  6336. // update lastRange.end only if smaller than item.end
  6337. // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)
  6338. // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])
  6339. if (buffered[i].end > buf2end) {
  6340. buffered2[buf2len - 1].end = buffered[i].end;
  6341. }
  6342. } else {
  6343. // big hole
  6344. buffered2.push(buffered[i]);
  6345. }
  6346. } else {
  6347. // first value
  6348. buffered2.push(buffered[i]);
  6349. }
  6350. }
  6351. for (i = 0, bufferLen = 0, bufferStart = bufferEnd = pos; i < buffered2.length; i++) {
  6352. var start = buffered2[i].start,
  6353. end = buffered2[i].end;
  6354. //logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));
  6355. if (pos + maxHoleDuration >= start && pos < end) {
  6356. // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
  6357. bufferStart = start;
  6358. bufferEnd = end;
  6359. bufferLen = bufferEnd - pos;
  6360. } else if (pos + maxHoleDuration < start) {
  6361. bufferStartNext = start;
  6362. break;
  6363. }
  6364. }
  6365. return { len: bufferLen, start: bufferStart, end: bufferEnd, nextStart: bufferStartNext };
  6366. }
  6367. };
  6368. /* harmony default export */ var buffer_helper = (BufferHelper);
  6369. // EXTERNAL MODULE: ./src/demux/demuxer-inline.js + 11 modules
  6370. var demuxer_inline = __webpack_require__(8);
  6371. // EXTERNAL MODULE: ./node_modules/events/events.js
  6372. var events_events = __webpack_require__(6);
  6373. var events_default = /*#__PURE__*/__webpack_require__.n(events_events);
  6374. // EXTERNAL MODULE: ./node_modules/webworkify-webpack/index.js
  6375. var webworkify_webpack = __webpack_require__(10);
  6376. var webworkify_webpack_default = /*#__PURE__*/__webpack_require__.n(webworkify_webpack);
  6377. // CONCATENATED MODULE: ./src/helper/mediasource-helper.js
  6378. /**
  6379. * MediaSource helper
  6380. */
  6381. function getMediaSource() {
  6382. if (typeof window !== 'undefined') {
  6383. return window.MediaSource || window.WebKitMediaSource;
  6384. }
  6385. }
  6386. // CONCATENATED MODULE: ./src/demux/demuxer.js
  6387. function demuxer__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6388. var demuxer_MediaSource = getMediaSource();
  6389. var demuxer_Demuxer = function () {
  6390. function Demuxer(hls, id) {
  6391. demuxer__classCallCheck(this, Demuxer);
  6392. this.hls = hls;
  6393. this.id = id;
  6394. // observer setup
  6395. var observer = this.observer = new events_default.a();
  6396. var config = hls.config;
  6397. observer.trigger = function trigger(event) {
  6398. for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  6399. data[_key - 1] = arguments[_key];
  6400. }
  6401. observer.emit.apply(observer, [event, event].concat(data));
  6402. };
  6403. observer.off = function off(event) {
  6404. for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  6405. data[_key2 - 1] = arguments[_key2];
  6406. }
  6407. observer.removeListener.apply(observer, [event].concat(data));
  6408. };
  6409. var forwardMessage = function (ev, data) {
  6410. data = data || {};
  6411. data.frag = this.frag;
  6412. data.id = this.id;
  6413. hls.trigger(ev, data);
  6414. }.bind(this);
  6415. // forward events to main thread
  6416. observer.on(events["a" /* default */].FRAG_DECRYPTED, forwardMessage);
  6417. observer.on(events["a" /* default */].FRAG_PARSING_INIT_SEGMENT, forwardMessage);
  6418. observer.on(events["a" /* default */].FRAG_PARSING_DATA, forwardMessage);
  6419. observer.on(events["a" /* default */].FRAG_PARSED, forwardMessage);
  6420. observer.on(events["a" /* default */].ERROR, forwardMessage);
  6421. observer.on(events["a" /* default */].FRAG_PARSING_METADATA, forwardMessage);
  6422. observer.on(events["a" /* default */].FRAG_PARSING_USERDATA, forwardMessage);
  6423. observer.on(events["a" /* default */].INIT_PTS_FOUND, forwardMessage);
  6424. var typeSupported = {
  6425. mp4: demuxer_MediaSource.isTypeSupported('video/mp4'),
  6426. mpeg: demuxer_MediaSource.isTypeSupported('audio/mpeg'),
  6427. mp3: demuxer_MediaSource.isTypeSupported('audio/mp4; codecs="mp3"')
  6428. };
  6429. // navigator.vendor is not always available in Web Worker
  6430. // refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator
  6431. var vendor = navigator.vendor;
  6432. if (config.enableWorker && typeof Worker !== 'undefined') {
  6433. logger["b" /* logger */].log('demuxing in webworker');
  6434. var w = void 0;
  6435. try {
  6436. w = this.w = webworkify_webpack_default()(/*require.resolve*/(11));
  6437. this.onwmsg = this.onWorkerMessage.bind(this);
  6438. w.addEventListener('message', this.onwmsg);
  6439. w.onerror = function (event) {
  6440. hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].OTHER_ERROR, details: errors["a" /* ErrorDetails */].INTERNAL_EXCEPTION, fatal: true, event: 'demuxerWorker', err: { message: event.message + ' (' + event.filename + ':' + event.lineno + ')' } });
  6441. };
  6442. w.postMessage({ cmd: 'init', typeSupported: typeSupported, vendor: vendor, id: id, config: JSON.stringify(config) });
  6443. } catch (err) {
  6444. logger["b" /* logger */].error('error while initializing DemuxerWorker, fallback on DemuxerInline');
  6445. if (w) {
  6446. // revoke the Object URL that was used to create demuxer worker, so as not to leak it
  6447. URL.revokeObjectURL(w.objectURL);
  6448. }
  6449. this.demuxer = new demuxer_inline["a" /* default */](observer, typeSupported, config, vendor);
  6450. this.w = undefined;
  6451. }
  6452. } else {
  6453. this.demuxer = new demuxer_inline["a" /* default */](observer, typeSupported, config, vendor);
  6454. }
  6455. }
  6456. Demuxer.prototype.destroy = function destroy() {
  6457. var w = this.w;
  6458. if (w) {
  6459. w.removeEventListener('message', this.onwmsg);
  6460. w.terminate();
  6461. this.w = null;
  6462. } else {
  6463. var demuxer = this.demuxer;
  6464. if (demuxer) {
  6465. demuxer.destroy();
  6466. this.demuxer = null;
  6467. }
  6468. }
  6469. var observer = this.observer;
  6470. if (observer) {
  6471. observer.removeAllListeners();
  6472. this.observer = null;
  6473. }
  6474. };
  6475. Demuxer.prototype.push = function push(data, initSegment, audioCodec, videoCodec, frag, duration, accurateTimeOffset, defaultInitPTS) {
  6476. var w = this.w;
  6477. var timeOffset = !isNaN(frag.startDTS) ? frag.startDTS : frag.start;
  6478. var decryptdata = frag.decryptdata;
  6479. var lastFrag = this.frag;
  6480. var discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
  6481. var trackSwitch = !(lastFrag && frag.level === lastFrag.level);
  6482. var nextSN = lastFrag && frag.sn === lastFrag.sn + 1;
  6483. var contiguous = !trackSwitch && nextSN;
  6484. if (discontinuity) {
  6485. logger["b" /* logger */].log(this.id + ':discontinuity detected');
  6486. }
  6487. if (trackSwitch) {
  6488. logger["b" /* logger */].log(this.id + ':switch detected');
  6489. }
  6490. this.frag = frag;
  6491. if (w) {
  6492. // post fragment payload as transferable objects for ArrayBuffer (no copy)
  6493. w.postMessage({ cmd: 'demux', data: data, decryptdata: decryptdata, initSegment: initSegment, audioCodec: audioCodec, videoCodec: videoCodec, timeOffset: timeOffset, discontinuity: discontinuity, trackSwitch: trackSwitch, contiguous: contiguous, duration: duration, accurateTimeOffset: accurateTimeOffset, defaultInitPTS: defaultInitPTS }, data instanceof ArrayBuffer ? [data] : []);
  6494. } else {
  6495. var demuxer = this.demuxer;
  6496. if (demuxer) {
  6497. demuxer.push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
  6498. }
  6499. }
  6500. };
  6501. Demuxer.prototype.onWorkerMessage = function onWorkerMessage(ev) {
  6502. var data = ev.data,
  6503. hls = this.hls;
  6504. switch (data.event) {
  6505. case 'init':
  6506. // revoke the Object URL that was used to create demuxer worker, so as not to leak it
  6507. URL.revokeObjectURL(this.w.objectURL);
  6508. break;
  6509. // special case for FRAG_PARSING_DATA: data1 and data2 are transferable objects
  6510. case events["a" /* default */].FRAG_PARSING_DATA:
  6511. data.data.data1 = new Uint8Array(data.data1);
  6512. if (data.data2) {
  6513. data.data.data2 = new Uint8Array(data.data2);
  6514. }
  6515. /* falls through */
  6516. default:
  6517. data.data = data.data || {};
  6518. data.data.frag = this.frag;
  6519. data.data.id = this.id;
  6520. hls.trigger(data.event, data.data);
  6521. break;
  6522. }
  6523. };
  6524. return Demuxer;
  6525. }();
  6526. /* harmony default export */ var demux_demuxer = (demuxer_Demuxer);
  6527. // CONCATENATED MODULE: ./src/helper/level-helper.js
  6528. /**
  6529. * Level Helper class, providing methods dealing with playlist sliding and drift
  6530. */
  6531. function updatePTS(fragments, fromIdx, toIdx) {
  6532. var fragFrom = fragments[fromIdx],
  6533. fragTo = fragments[toIdx],
  6534. fragToPTS = fragTo.startPTS;
  6535. // if we know startPTS[toIdx]
  6536. if (!isNaN(fragToPTS)) {
  6537. // update fragment duration.
  6538. // it helps to fix drifts between playlist reported duration and fragment real duration
  6539. if (toIdx > fromIdx) {
  6540. fragFrom.duration = fragToPTS - fragFrom.start;
  6541. if (fragFrom.duration < 0) {
  6542. logger["b" /* logger */].warn('negative duration computed for frag ' + fragFrom.sn + ',level ' + fragFrom.level + ', there should be some duration drift between playlist and fragment!');
  6543. }
  6544. } else {
  6545. fragTo.duration = fragFrom.start - fragToPTS;
  6546. if (fragTo.duration < 0) {
  6547. logger["b" /* logger */].warn('negative duration computed for frag ' + fragTo.sn + ',level ' + fragTo.level + ', there should be some duration drift between playlist and fragment!');
  6548. }
  6549. }
  6550. } else {
  6551. // we dont know startPTS[toIdx]
  6552. if (toIdx > fromIdx) {
  6553. fragTo.start = fragFrom.start + fragFrom.duration;
  6554. } else {
  6555. fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);
  6556. }
  6557. }
  6558. }
  6559. function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
  6560. // update frag PTS/DTS
  6561. var maxStartPTS = startPTS;
  6562. if (!isNaN(frag.startPTS)) {
  6563. // delta PTS between audio and video
  6564. var deltaPTS = Math.abs(frag.startPTS - startPTS);
  6565. if (isNaN(frag.deltaPTS)) {
  6566. frag.deltaPTS = deltaPTS;
  6567. } else {
  6568. frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
  6569. }
  6570. maxStartPTS = Math.max(startPTS, frag.startPTS);
  6571. startPTS = Math.min(startPTS, frag.startPTS);
  6572. endPTS = Math.max(endPTS, frag.endPTS);
  6573. startDTS = Math.min(startDTS, frag.startDTS);
  6574. endDTS = Math.max(endDTS, frag.endDTS);
  6575. }
  6576. var drift = startPTS - frag.start;
  6577. frag.start = frag.startPTS = startPTS;
  6578. frag.maxStartPTS = maxStartPTS;
  6579. frag.endPTS = endPTS;
  6580. frag.startDTS = startDTS;
  6581. frag.endDTS = endDTS;
  6582. frag.duration = endPTS - startPTS;
  6583. var sn = frag.sn;
  6584. // exit if sn out of range
  6585. if (!details || sn < details.startSN || sn > details.endSN) {
  6586. return 0;
  6587. }
  6588. var fragIdx, fragments, i;
  6589. fragIdx = sn - details.startSN;
  6590. fragments = details.fragments;
  6591. // update frag reference in fragments array
  6592. // rationale is that fragments array might not contain this frag object.
  6593. // this will happpen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()
  6594. // if we don't update frag, we won't be able to propagate PTS info on the playlist
  6595. // resulting in invalid sliding computation
  6596. fragments[fragIdx] = frag;
  6597. // adjust fragment PTS/duration from seqnum-1 to frag 0
  6598. for (i = fragIdx; i > 0; i--) {
  6599. updatePTS(fragments, i, i - 1);
  6600. }
  6601. // adjust fragment PTS/duration from seqnum to last frag
  6602. for (i = fragIdx; i < fragments.length - 1; i++) {
  6603. updatePTS(fragments, i, i + 1);
  6604. }
  6605. details.PTSKnown = true;
  6606. //logger.log(` frag start/end:${startPTS.toFixed(3)}/${endPTS.toFixed(3)}`);
  6607. return drift;
  6608. }
  6609. function mergeDetails(oldDetails, newDetails) {
  6610. var start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN,
  6611. end = Math.min(oldDetails.endSN, newDetails.endSN) - newDetails.startSN,
  6612. delta = newDetails.startSN - oldDetails.startSN,
  6613. oldfragments = oldDetails.fragments,
  6614. newfragments = newDetails.fragments,
  6615. ccOffset = 0,
  6616. PTSFrag;
  6617. // check if old/new playlists have fragments in common
  6618. if (end < start) {
  6619. newDetails.PTSKnown = false;
  6620. return;
  6621. }
  6622. // loop through overlapping SN and update startPTS , cc, and duration if any found
  6623. for (var i = start; i <= end; i++) {
  6624. var oldFrag = oldfragments[delta + i],
  6625. newFrag = newfragments[i];
  6626. if (newFrag && oldFrag) {
  6627. ccOffset = oldFrag.cc - newFrag.cc;
  6628. if (!isNaN(oldFrag.startPTS)) {
  6629. newFrag.start = newFrag.startPTS = oldFrag.startPTS;
  6630. newFrag.endPTS = oldFrag.endPTS;
  6631. newFrag.duration = oldFrag.duration;
  6632. newFrag.backtracked = oldFrag.backtracked;
  6633. newFrag.dropped = oldFrag.dropped;
  6634. PTSFrag = newFrag;
  6635. }
  6636. }
  6637. }
  6638. if (ccOffset) {
  6639. logger["b" /* logger */].log('discontinuity sliding from playlist, take drift into account');
  6640. for (i = 0; i < newfragments.length; i++) {
  6641. newfragments[i].cc += ccOffset;
  6642. }
  6643. }
  6644. // if at least one fragment contains PTS info, recompute PTS information for all fragments
  6645. if (PTSFrag) {
  6646. updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
  6647. } else {
  6648. // ensure that delta is within oldfragments range
  6649. // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])
  6650. // in that case we also need to adjust start offset of all fragments
  6651. if (delta >= 0 && delta < oldfragments.length) {
  6652. // adjust start by sliding offset
  6653. var sliding = oldfragments[delta].start;
  6654. for (i = 0; i < newfragments.length; i++) {
  6655. newfragments[i].start += sliding;
  6656. }
  6657. }
  6658. }
  6659. // if we are here, it means we have fragments overlapping between
  6660. // old and new level. reliable PTS info is thus relying on old level
  6661. newDetails.PTSKnown = oldDetails.PTSKnown;
  6662. }
  6663. // CONCATENATED MODULE: ./src/utils/timeRanges.js
  6664. /**
  6665. * TimeRanges to string helper
  6666. */
  6667. var TimeRanges = {
  6668. toString: function toString(r) {
  6669. var log = '',
  6670. len = r.length;
  6671. for (var i = 0; i < len; i++) {
  6672. log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']';
  6673. }
  6674. return log;
  6675. }
  6676. };
  6677. /* harmony default export */ var timeRanges = (TimeRanges);
  6678. // CONCATENATED MODULE: ./src/utils/discontinuities.js
  6679. function findFirstFragWithCC(fragments, cc) {
  6680. var firstFrag = null;
  6681. for (var i = 0; i < fragments.length; i += 1) {
  6682. var currentFrag = fragments[i];
  6683. if (currentFrag && currentFrag.cc === cc) {
  6684. firstFrag = currentFrag;
  6685. break;
  6686. }
  6687. }
  6688. return firstFrag;
  6689. }
  6690. function findFragWithCC(fragments, CC) {
  6691. return binary_search.search(fragments, function (candidate) {
  6692. if (candidate.cc < CC) {
  6693. return 1;
  6694. } else if (candidate.cc > CC) {
  6695. return -1;
  6696. } else {
  6697. return 0;
  6698. }
  6699. });
  6700. }
  6701. function shouldAlignOnDiscontinuities(lastFrag, lastLevel, details) {
  6702. var shouldAlign = false;
  6703. if (lastLevel && lastLevel.details && details) {
  6704. if (details.endCC > details.startCC || lastFrag && lastFrag.cc < details.startCC) {
  6705. shouldAlign = true;
  6706. }
  6707. }
  6708. return shouldAlign;
  6709. }
  6710. // Find the first frag in the previous level which matches the CC of the first frag of the new level
  6711. function findDiscontinuousReferenceFrag(prevDetails, curDetails) {
  6712. var prevFrags = prevDetails.fragments;
  6713. var curFrags = curDetails.fragments;
  6714. if (!curFrags.length || !prevFrags.length) {
  6715. logger["b" /* logger */].log('No fragments to align');
  6716. return;
  6717. }
  6718. var prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);
  6719. if (!prevStartFrag || prevStartFrag && !prevStartFrag.startPTS) {
  6720. logger["b" /* logger */].log('No frag in previous level to align on');
  6721. return;
  6722. }
  6723. return prevStartFrag;
  6724. }
  6725. function adjustPts(sliding, details) {
  6726. details.fragments.forEach(function (frag) {
  6727. if (frag) {
  6728. var start = frag.start + sliding;
  6729. frag.start = frag.startPTS = start;
  6730. frag.endPTS = start + frag.duration;
  6731. }
  6732. });
  6733. details.PTSKnown = true;
  6734. }
  6735. // If a change in CC is detected, the PTS can no longer be relied upon
  6736. // Attempt to align the level by using the last level - find the last frag matching the current CC and use it's PTS
  6737. // as a reference
  6738. function alignDiscontinuities(lastFrag, lastLevel, details) {
  6739. if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) {
  6740. var referenceFrag = findDiscontinuousReferenceFrag(lastLevel.details, details);
  6741. if (referenceFrag) {
  6742. logger["b" /* logger */].log('Adjusting PTS using last level due to CC increase within current level');
  6743. adjustPts(referenceFrag.start, details);
  6744. }
  6745. }
  6746. // try to align using programDateTime attribute (if available)
  6747. if (details.PTSKnown === false && lastLevel && lastLevel.details) {
  6748. // if last level sliding is 1000 and its first frag PROGRAM-DATE-TIME is 2017-08-20 1:10:00 AM
  6749. // and if new details first frag PROGRAM DATE-TIME is 2017-08-20 1:10:08 AM
  6750. // then we can deduce that playlist B sliding is 1000+8 = 1008s
  6751. var lastPDT = lastLevel.details.programDateTime;
  6752. var newPDT = details.programDateTime;
  6753. // date diff is in ms. frag.start is in seconds
  6754. var sliding = (newPDT - lastPDT) / 1000 + lastLevel.details.fragments[0].start;
  6755. if (!isNaN(sliding)) {
  6756. logger["b" /* logger */].log('adjusting PTS using programDateTime delta, sliding:' + sliding.toFixed(3));
  6757. adjustPts(sliding, details);
  6758. }
  6759. }
  6760. }
  6761. // CONCATENATED MODULE: ./src/task-loop.js
  6762. function task_loop__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6763. function task_loop__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; }
  6764. function task_loop__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; }
  6765. var TaskLoop = function (_EventHandler) {
  6766. task_loop__inherits(TaskLoop, _EventHandler);
  6767. function TaskLoop(hls) {
  6768. task_loop__classCallCheck(this, TaskLoop);
  6769. for (var _len = arguments.length, events = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  6770. events[_key - 1] = arguments[_key];
  6771. }
  6772. var _this = task_loop__possibleConstructorReturn(this, _EventHandler.call.apply(_EventHandler, [this, hls].concat(events)));
  6773. _this._tickInterval = null;
  6774. _this._tickCallCount = 0;
  6775. return _this;
  6776. }
  6777. /**
  6778. * @override
  6779. */
  6780. TaskLoop.prototype.destroy = function destroy() {
  6781. this.clearInterval();
  6782. _EventHandler.prototype.destroy.call(this);
  6783. };
  6784. /**
  6785. * @returns {boolean}
  6786. */
  6787. TaskLoop.prototype.hasInterval = function hasInterval() {
  6788. return !isNaN(this._tickInterval);
  6789. };
  6790. /**
  6791. * @param {number} millis Interval time (ms)
  6792. * @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect)
  6793. */
  6794. TaskLoop.prototype.setInterval = function (_setInterval) {
  6795. function setInterval(_x) {
  6796. return _setInterval.apply(this, arguments);
  6797. }
  6798. setInterval.toString = function () {
  6799. return _setInterval.toString();
  6800. };
  6801. return setInterval;
  6802. }(function (millis) {
  6803. if (!this._tickInterval) {
  6804. this._tickInterval = setInterval(this.tick.bind(this, false), millis);
  6805. return true;
  6806. }
  6807. return false;
  6808. });
  6809. /**
  6810. * @returns {boolean} True when interval was cleared, false when none was set (no effect)
  6811. */
  6812. TaskLoop.prototype.clearInterval = function (_clearInterval) {
  6813. function clearInterval() {
  6814. return _clearInterval.apply(this, arguments);
  6815. }
  6816. clearInterval.toString = function () {
  6817. return _clearInterval.toString();
  6818. };
  6819. return clearInterval;
  6820. }(function () {
  6821. if (this._tickInterval) {
  6822. clearInterval(this._tickInterval);
  6823. return true;
  6824. }
  6825. return false;
  6826. });
  6827. /**
  6828. *
  6829. * @param {Wether to force async} forceAsync
  6830. * @returns {boolean} True when async, false when sync
  6831. */
  6832. TaskLoop.prototype.tick = function tick() {
  6833. this._tickCallCount++;
  6834. if (this._tickCallCount === 1) {
  6835. this.doTick();
  6836. if (this._tickCallCount > 1) {
  6837. setTimeout(this.tick.bind(this), 0);
  6838. }
  6839. this._tickCallCount = 0;
  6840. }
  6841. };
  6842. /**
  6843. * For subclass to implement task logic
  6844. * @abstract
  6845. */
  6846. TaskLoop.prototype.doTick = function doTick() {
  6847. throw new Error('TaskLoop is abstract and `doLoop` must be implemented');
  6848. };
  6849. return TaskLoop;
  6850. }(event_handler);
  6851. /* harmony default export */ var task_loop = (TaskLoop);
  6852. // CONCATENATED MODULE: ./src/controller/stream-controller.js
  6853. var stream_controller__createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  6854. function stream_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6855. function stream_controller__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; }
  6856. function stream_controller__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; }
  6857. /*
  6858. * Stream Controller
  6859. */
  6860. var State = {
  6861. STOPPED: 'STOPPED',
  6862. IDLE: 'IDLE',
  6863. KEY_LOADING: 'KEY_LOADING',
  6864. FRAG_LOADING: 'FRAG_LOADING',
  6865. FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
  6866. WAITING_LEVEL: 'WAITING_LEVEL',
  6867. PARSING: 'PARSING',
  6868. PARSED: 'PARSED',
  6869. BUFFER_FLUSHING: 'BUFFER_FLUSHING',
  6870. ENDED: 'ENDED',
  6871. ERROR: 'ERROR'
  6872. };
  6873. var stream_controller_StreamController = function (_TaskLoop) {
  6874. stream_controller__inherits(StreamController, _TaskLoop);
  6875. function StreamController(hls) {
  6876. stream_controller__classCallCheck(this, StreamController);
  6877. var _this = stream_controller__possibleConstructorReturn(this, _TaskLoop.call(this, hls, events["a" /* default */].MEDIA_ATTACHED, events["a" /* default */].MEDIA_DETACHING, events["a" /* default */].MANIFEST_LOADING, events["a" /* default */].MANIFEST_PARSED, events["a" /* default */].LEVEL_LOADED, events["a" /* default */].KEY_LOADED, events["a" /* default */].FRAG_LOADED, events["a" /* default */].FRAG_LOAD_EMERGENCY_ABORTED, events["a" /* default */].FRAG_PARSING_INIT_SEGMENT, events["a" /* default */].FRAG_PARSING_DATA, events["a" /* default */].FRAG_PARSED, events["a" /* default */].ERROR, events["a" /* default */].AUDIO_TRACK_SWITCHING, events["a" /* default */].AUDIO_TRACK_SWITCHED, events["a" /* default */].BUFFER_CREATED, events["a" /* default */].BUFFER_APPENDED, events["a" /* default */].BUFFER_FLUSHED));
  6878. _this.config = hls.config;
  6879. _this.audioCodecSwap = false;
  6880. _this._state = State.STOPPED;
  6881. return _this;
  6882. }
  6883. StreamController.prototype.onHandlerDestroying = function onHandlerDestroying() {
  6884. this.stopLoad();
  6885. };
  6886. StreamController.prototype.onHandlerDestroyed = function onHandlerDestroyed() {
  6887. this.state = State.STOPPED;
  6888. };
  6889. StreamController.prototype.startLoad = function startLoad(startPosition) {
  6890. if (this.levels) {
  6891. var lastCurrentTime = this.lastCurrentTime,
  6892. hls = this.hls;
  6893. this.stopLoad();
  6894. this.setInterval(100);
  6895. this.level = -1;
  6896. this.fragLoadError = 0;
  6897. if (!this.startFragRequested) {
  6898. // determine load level
  6899. var startLevel = hls.startLevel;
  6900. if (startLevel === -1) {
  6901. // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
  6902. startLevel = 0;
  6903. this.bitrateTest = true;
  6904. }
  6905. // set new level to playlist loader : this will trigger start level load
  6906. // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
  6907. this.level = hls.nextLoadLevel = startLevel;
  6908. this.loadedmetadata = false;
  6909. }
  6910. // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime
  6911. if (lastCurrentTime > 0 && startPosition === -1) {
  6912. logger["b" /* logger */].log('override startPosition with lastCurrentTime @' + lastCurrentTime.toFixed(3));
  6913. startPosition = lastCurrentTime;
  6914. }
  6915. this.state = State.IDLE;
  6916. this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
  6917. this.tick();
  6918. } else {
  6919. this.forceStartLoad = true;
  6920. this.state = State.STOPPED;
  6921. }
  6922. };
  6923. StreamController.prototype.stopLoad = function stopLoad() {
  6924. var frag = this.fragCurrent;
  6925. if (frag) {
  6926. if (frag.loader) {
  6927. frag.loader.abort();
  6928. }
  6929. this.fragCurrent = null;
  6930. }
  6931. this.fragPrevious = null;
  6932. if (this.demuxer) {
  6933. this.demuxer.destroy();
  6934. this.demuxer = null;
  6935. }
  6936. this.state = State.STOPPED;
  6937. this.forceStartLoad = false;
  6938. };
  6939. StreamController.prototype.doTick = function doTick() {
  6940. switch (this.state) {
  6941. case State.ERROR:
  6942. //don't do anything in error state to avoid breaking further ...
  6943. break;
  6944. case State.BUFFER_FLUSHING:
  6945. // in buffer flushing state, reset fragLoadError counter
  6946. this.fragLoadError = 0;
  6947. break;
  6948. case State.IDLE:
  6949. this._doTickIdle();
  6950. break;
  6951. case State.WAITING_LEVEL:
  6952. var level = this.levels[this.level];
  6953. // check if playlist is already loaded
  6954. if (level && level.details) {
  6955. this.state = State.IDLE;
  6956. }
  6957. break;
  6958. case State.FRAG_LOADING_WAITING_RETRY:
  6959. var now = performance.now();
  6960. var retryDate = this.retryDate;
  6961. // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  6962. if (!retryDate || now >= retryDate || this.media && this.media.seeking) {
  6963. logger["b" /* logger */].log('mediaController: retryDate reached, switch back to IDLE state');
  6964. this.state = State.IDLE;
  6965. }
  6966. break;
  6967. case State.ERROR:
  6968. case State.STOPPED:
  6969. case State.FRAG_LOADING:
  6970. case State.PARSING:
  6971. case State.PARSED:
  6972. case State.ENDED:
  6973. break;
  6974. default:
  6975. break;
  6976. }
  6977. // check buffer
  6978. this._checkBuffer();
  6979. // check/update current fragment
  6980. this._checkFragmentChanged();
  6981. };
  6982. // Ironically the "idle" state is the on we do the most logic in it seems ....
  6983. // NOTE: Maybe we could rather schedule a check for buffer length after half of the currently
  6984. // played segment, or on pause/play/seek instead of naively checking every 100ms?
  6985. StreamController.prototype._doTickIdle = function _doTickIdle() {
  6986. var hls = this.hls,
  6987. config = hls.config,
  6988. media = this.media;
  6989. // if start level not parsed yet OR
  6990. // if video not attached AND start fragment already requested OR start frag prefetch disable
  6991. // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment
  6992. if (this.levelLastLoaded === undefined || !media && (this.startFragRequested || !config.startFragPrefetch)) {
  6993. return;
  6994. }
  6995. // if we have not yet loaded any fragment, start loading from start position
  6996. var pos = void 0;
  6997. if (this.loadedmetadata) {
  6998. pos = media.currentTime;
  6999. } else {
  7000. pos = this.nextLoadPosition;
  7001. }
  7002. // determine next load level
  7003. var level = hls.nextLoadLevel,
  7004. levelInfo = this.levels[level];
  7005. if (!levelInfo) {
  7006. return;
  7007. }
  7008. var levelBitrate = levelInfo.bitrate,
  7009. maxBufLen = void 0;
  7010. // 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
  7011. if (levelBitrate) {
  7012. maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
  7013. } else {
  7014. maxBufLen = config.maxBufferLength;
  7015. }
  7016. maxBufLen = Math.min(maxBufLen, config.maxMaxBufferLength);
  7017. // determine next candidate fragment to be loaded, based on current position and end of buffer position
  7018. // ensure up to `config.maxMaxBufferLength` of buffer upfront
  7019. var bufferInfo = buffer_helper.bufferInfo(this.mediaBuffer ? this.mediaBuffer : media, pos, config.maxBufferHole),
  7020. bufferLen = bufferInfo.len;
  7021. // Stay idle if we are still with buffer margins
  7022. if (bufferLen >= maxBufLen) {
  7023. return;
  7024. }
  7025. // if buffer length is less than maxBufLen try to load a new fragment ...
  7026. logger["b" /* logger */].trace('buffer length of ' + bufferLen.toFixed(3) + ' is below max of ' + maxBufLen.toFixed(3) + '. checking for more payload ...');
  7027. // set next load level : this will trigger a playlist load if needed
  7028. this.level = hls.nextLoadLevel = level;
  7029. var levelDetails = levelInfo.details;
  7030. // if level info not retrieved yet, switch state and wait for level retrieval
  7031. // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
  7032. // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
  7033. if (levelDetails === undefined || levelDetails.live === true && this.levelLastLoaded !== level) {
  7034. this.state = State.WAITING_LEVEL;
  7035. return;
  7036. }
  7037. // we just got done loading the final fragment and there is no other buffered range after ...
  7038. // rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between
  7039. // so we should not switch to ENDED in that case, to be able to buffer them
  7040. // dont switch to ENDED if we need to backtrack last fragment
  7041. var fragPrevious = this.fragPrevious;
  7042. if (!levelDetails.live && fragPrevious && !fragPrevious.backtracked && fragPrevious.sn === levelDetails.endSN && !bufferInfo.nextStart) {
  7043. // fragPrevious is last fragment. retrieve level duration using last frag start offset + duration
  7044. // real duration might be lower than initial duration if there are drifts between real frag duration and playlist signaling
  7045. var duration = Math.min(media.duration, fragPrevious.start + fragPrevious.duration);
  7046. // if everything (almost) til the end is buffered, let's signal eos
  7047. // we don't compare exactly media.duration === bufferInfo.end as there could be some subtle media duration difference (audio/video offsets...)
  7048. // tolerate up to one frag duration to cope with these cases.
  7049. // 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
  7050. if (duration - Math.max(bufferInfo.end, fragPrevious.start) <= Math.max(0.2, fragPrevious.duration)) {
  7051. // Finalize the media stream
  7052. var data = {};
  7053. if (this.altAudio) {
  7054. data.type = 'video';
  7055. }
  7056. this.hls.trigger(events["a" /* default */].BUFFER_EOS, data);
  7057. this.state = State.ENDED;
  7058. return;
  7059. }
  7060. }
  7061. // if we have the levelDetails for the selected variant, lets continue enrichen our stream (load keys/fragments or trigger EOS, etc..)
  7062. this._fetchPayloadOrEos(pos, bufferInfo, levelDetails);
  7063. };
  7064. StreamController.prototype._fetchPayloadOrEos = function _fetchPayloadOrEos(pos, bufferInfo, levelDetails) {
  7065. var fragPrevious = this.fragPrevious,
  7066. level = this.level,
  7067. fragments = levelDetails.fragments,
  7068. fragLen = fragments.length;
  7069. // empty playlist
  7070. if (fragLen === 0) {
  7071. return;
  7072. }
  7073. // find fragment index, contiguous with end of buffer position
  7074. var start = fragments[0].start,
  7075. end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,
  7076. bufferEnd = bufferInfo.end,
  7077. frag = void 0;
  7078. if (levelDetails.initSegment && !levelDetails.initSegment.data) {
  7079. frag = levelDetails.initSegment;
  7080. } else {
  7081. // in case of live playlist we need to ensure that requested position is not located before playlist start
  7082. if (levelDetails.live) {
  7083. var initialLiveManifestSize = this.config.initialLiveManifestSize;
  7084. if (fragLen < initialLiveManifestSize) {
  7085. logger["b" /* logger */].warn('Can not start playback of a level, reason: not enough fragments ' + fragLen + ' < ' + initialLiveManifestSize);
  7086. return;
  7087. }
  7088. frag = this._ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen);
  7089. // if it explicitely returns null don't load any fragment and exit function now
  7090. if (frag === null) {
  7091. return;
  7092. }
  7093. } else {
  7094. // VoD playlist: if bufferEnd before start of playlist, load first fragment
  7095. if (bufferEnd < start) {
  7096. frag = fragments[0];
  7097. }
  7098. }
  7099. }
  7100. if (!frag) {
  7101. frag = this._findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails);
  7102. }
  7103. if (frag) {
  7104. this._loadFragmentOrKey(frag, level, levelDetails, pos, bufferEnd);
  7105. }
  7106. return;
  7107. };
  7108. StreamController.prototype._ensureFragmentAtLivePoint = function _ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen) {
  7109. var config = this.hls.config,
  7110. media = this.media;
  7111. var frag = void 0;
  7112. // check if requested position is within seekable boundaries :
  7113. //logger.log(`start/pos/bufEnd/seeking:${start.toFixed(3)}/${pos.toFixed(3)}/${bufferEnd.toFixed(3)}/${this.media.seeking}`);
  7114. var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
  7115. if (bufferEnd < Math.max(start - config.maxFragLookUpTolerance, end - maxLatency)) {
  7116. var liveSyncPosition = this.liveSyncPosition = this.computeLivePosition(start, levelDetails);
  7117. logger["b" /* logger */].log('buffer end: ' + bufferEnd.toFixed(3) + ' is located too far from the end of live sliding playlist, reset currentTime to : ' + liveSyncPosition.toFixed(3));
  7118. bufferEnd = liveSyncPosition;
  7119. if (media && media.readyState && media.duration > liveSyncPosition) {
  7120. media.currentTime = liveSyncPosition;
  7121. }
  7122. this.nextLoadPosition = liveSyncPosition;
  7123. }
  7124. // if end of buffer greater than live edge, don't load any fragment
  7125. // this could happen if live playlist intermittently slides in the past.
  7126. // level 1 loaded [182580161,182580167]
  7127. // level 1 loaded [182580162,182580169]
  7128. // Loading 182580168 of [182580162 ,182580169],level 1 ..
  7129. // Loading 182580169 of [182580162 ,182580169],level 1 ..
  7130. // level 1 loaded [182580162,182580168] <============= here we should have bufferEnd > end. in that case break to avoid reloading 182580168
  7131. // level 1 loaded [182580164,182580171]
  7132. //
  7133. // don't return null in case media not loaded yet (readystate === 0)
  7134. if (levelDetails.PTSKnown && bufferEnd > end && media && media.readyState) {
  7135. return null;
  7136. }
  7137. if (this.startFragRequested && !levelDetails.PTSKnown) {
  7138. /* we are switching level on live playlist, but we don't have any PTS info for that quality level ...
  7139. try to load frag matching with next SN.
  7140. even if SN are not synchronized between playlists, loading this frag will help us
  7141. compute playlist sliding and find the right one after in case it was not the right consecutive one */
  7142. if (fragPrevious) {
  7143. var targetSN = fragPrevious.sn + 1;
  7144. if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
  7145. var fragNext = fragments[targetSN - levelDetails.startSN];
  7146. if (fragPrevious.cc === fragNext.cc) {
  7147. frag = fragNext;
  7148. logger["b" /* logger */].log('live playlist, switching playlist, load frag with next SN: ' + frag.sn);
  7149. }
  7150. }
  7151. // next frag SN not available (or not with same continuity counter)
  7152. // look for a frag sharing the same CC
  7153. if (!frag) {
  7154. frag = binary_search.search(fragments, function (frag) {
  7155. return fragPrevious.cc - frag.cc;
  7156. });
  7157. if (frag) {
  7158. logger["b" /* logger */].log('live playlist, switching playlist, load frag with same CC: ' + frag.sn);
  7159. }
  7160. }
  7161. }
  7162. if (!frag) {
  7163. /* we have no idea about which fragment should be loaded.
  7164. so let's load mid fragment. it will help computing playlist sliding and find the right one
  7165. */
  7166. frag = fragments[Math.min(fragLen - 1, Math.round(fragLen / 2))];
  7167. logger["b" /* logger */].log('live playlist, switching playlist, unknown, load middle frag : ' + frag.sn);
  7168. }
  7169. }
  7170. return frag;
  7171. };
  7172. StreamController.prototype._findFragment = function _findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails) {
  7173. var config = this.hls.config;
  7174. var frag = void 0;
  7175. var foundFrag = void 0;
  7176. var maxFragLookUpTolerance = config.maxFragLookUpTolerance;
  7177. var fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : undefined;
  7178. var fragmentWithinToleranceTest = function fragmentWithinToleranceTest(candidate) {
  7179. // offset should be within fragment boundary - config.maxFragLookUpTolerance
  7180. // this is to cope with situations like
  7181. // bufferEnd = 9.991
  7182. // frag[Ø] : [0,10]
  7183. // frag[1] : [10,20]
  7184. // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
  7185. // frag start frag start+duration
  7186. // |-----------------------------|
  7187. // <---> <--->
  7188. // ...--------><-----------------------------><---------....
  7189. // previous frag matching fragment next frag
  7190. // return -1 return 0 return 1
  7191. //logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
  7192. // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
  7193. var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
  7194. if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
  7195. return 1;
  7196. } // if maxFragLookUpTolerance will have negative value then don't return -1 for first element
  7197. else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
  7198. return -1;
  7199. }
  7200. return 0;
  7201. };
  7202. if (bufferEnd < end) {
  7203. if (bufferEnd > end - maxFragLookUpTolerance) {
  7204. maxFragLookUpTolerance = 0;
  7205. }
  7206. // Prefer the next fragment if it's within tolerance
  7207. if (fragNext && !fragmentWithinToleranceTest(fragNext)) {
  7208. foundFrag = fragNext;
  7209. } else {
  7210. foundFrag = binary_search.search(fragments, fragmentWithinToleranceTest);
  7211. }
  7212. } else {
  7213. // reach end of playlist
  7214. foundFrag = fragments[fragLen - 1];
  7215. }
  7216. if (foundFrag) {
  7217. frag = foundFrag;
  7218. var curSNIdx = frag.sn - levelDetails.startSN;
  7219. var sameLevel = fragPrevious && frag.level === fragPrevious.level;
  7220. var prevFrag = fragments[curSNIdx - 1];
  7221. var nextFrag = fragments[curSNIdx + 1];
  7222. //logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);
  7223. if (fragPrevious && frag.sn === fragPrevious.sn) {
  7224. if (sameLevel && !frag.backtracked) {
  7225. if (frag.sn < levelDetails.endSN) {
  7226. var deltaPTS = fragPrevious.deltaPTS;
  7227. // if there is a significant delta between audio and video, larger than max allowed hole,
  7228. // and if previous remuxed fragment did not start with a keyframe. (fragPrevious.dropped)
  7229. // let's try to load previous fragment again to get last keyframe
  7230. // then we will reload again current fragment (that way we should be able to fill the buffer hole ...)
  7231. if (deltaPTS && deltaPTS > config.maxBufferHole && fragPrevious.dropped && curSNIdx) {
  7232. frag = prevFrag;
  7233. logger["b" /* 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');
  7234. // decrement previous frag load counter to avoid frag loop loading error when next fragment will get reloaded
  7235. fragPrevious.loadCounter--;
  7236. } else {
  7237. frag = nextFrag;
  7238. logger["b" /* logger */].log('SN just loaded, load next one: ' + frag.sn);
  7239. }
  7240. } else {
  7241. frag = null;
  7242. }
  7243. } else if (frag.backtracked) {
  7244. // Only backtrack a max of 1 consecutive fragment to prevent sliding back too far when little or no frags start with keyframes
  7245. if (nextFrag && nextFrag.backtracked) {
  7246. logger["b" /* logger */].warn('Already backtracked from fragment ' + nextFrag.sn + ', will not backtrack to fragment ' + frag.sn + '. Loading fragment ' + nextFrag.sn);
  7247. frag = nextFrag;
  7248. } else {
  7249. // If a fragment has dropped frames and it's in a same level/sequence, load the previous fragment to try and find the keyframe
  7250. // 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
  7251. logger["b" /* logger */].warn('Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe');
  7252. frag.dropped = 0;
  7253. if (prevFrag) {
  7254. if (prevFrag.loadCounter) {
  7255. prevFrag.loadCounter--;
  7256. }
  7257. frag = prevFrag;
  7258. frag.backtracked = true;
  7259. } else if (curSNIdx) {
  7260. // can't backtrack on very first fragment
  7261. frag = null;
  7262. }
  7263. }
  7264. }
  7265. }
  7266. }
  7267. return frag;
  7268. };
  7269. StreamController.prototype._loadFragmentOrKey = function _loadFragmentOrKey(frag, level, levelDetails, pos, bufferEnd) {
  7270. var hls = this.hls,
  7271. config = hls.config;
  7272. //logger.log('loading frag ' + i +',pos/bufEnd:' + pos.toFixed(3) + '/' + bufferEnd.toFixed(3));
  7273. if (frag.decryptdata && frag.decryptdata.uri != null && frag.decryptdata.key == null) {
  7274. logger["b" /* logger */].log('Loading key for ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level);
  7275. this.state = State.KEY_LOADING;
  7276. hls.trigger(events["a" /* default */].KEY_LOADING, { frag: frag });
  7277. } else {
  7278. logger["b" /* logger */].log('Loading ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level + ', currentTime:' + pos.toFixed(3) + ',bufferEnd:' + bufferEnd.toFixed(3));
  7279. // ensure that we are not reloading the same fragments in loop ...
  7280. if (this.fragLoadIdx !== undefined) {
  7281. this.fragLoadIdx++;
  7282. } else {
  7283. this.fragLoadIdx = 0;
  7284. }
  7285. if (frag.loadCounter) {
  7286. frag.loadCounter++;
  7287. var maxThreshold = config.fragLoadingLoopThreshold;
  7288. // if this frag has already been loaded 3 times, and if it has been reloaded recently
  7289. if (frag.loadCounter > maxThreshold && Math.abs(this.fragLoadIdx - frag.loadIdx) < maxThreshold) {
  7290. hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_LOOP_LOADING_ERROR, fatal: false, frag: frag });
  7291. return;
  7292. }
  7293. } else {
  7294. frag.loadCounter = 1;
  7295. }
  7296. frag.loadIdx = this.fragLoadIdx;
  7297. frag.autoLevel = hls.autoLevelEnabled;
  7298. frag.bitrateTest = this.bitrateTest;
  7299. this.fragCurrent = frag;
  7300. this.startFragRequested = true;
  7301. // Don't update nextLoadPosition for fragments which are not buffered
  7302. if (!isNaN(frag.sn) && !frag.bitrateTest) {
  7303. this.nextLoadPosition = frag.start + frag.duration;
  7304. }
  7305. hls.trigger(events["a" /* default */].FRAG_LOADING, { frag: frag });
  7306. // lazy demuxer init, as this could take some time ... do it during frag loading
  7307. if (!this.demuxer) {
  7308. this.demuxer = new demux_demuxer(hls, 'main');
  7309. }
  7310. this.state = State.FRAG_LOADING;
  7311. return;
  7312. }
  7313. };
  7314. StreamController.prototype.getBufferedFrag = function getBufferedFrag(position) {
  7315. return binary_search.search(this._bufferedFrags, function (frag) {
  7316. if (position < frag.startPTS) {
  7317. return -1;
  7318. } else if (position > frag.endPTS) {
  7319. return 1;
  7320. }
  7321. return 0;
  7322. });
  7323. };
  7324. StreamController.prototype.followingBufferedFrag = function followingBufferedFrag(frag) {
  7325. if (frag) {
  7326. // try to get range of next fragment (500ms after this range)
  7327. return this.getBufferedFrag(frag.endPTS + 0.5);
  7328. }
  7329. return null;
  7330. };
  7331. StreamController.prototype._checkFragmentChanged = function _checkFragmentChanged() {
  7332. var fragPlayingCurrent,
  7333. currentTime,
  7334. video = this.media;
  7335. if (video && video.readyState && video.seeking === false) {
  7336. currentTime = video.currentTime;
  7337. /* if video element is in seeked state, currentTime can only increase.
  7338. (assuming that playback rate is positive ...)
  7339. As sometimes currentTime jumps back to zero after a
  7340. media decode error, check this, to avoid seeking back to
  7341. wrong position after a media decode error
  7342. */
  7343. if (currentTime > video.playbackRate * this.lastCurrentTime) {
  7344. this.lastCurrentTime = currentTime;
  7345. }
  7346. if (buffer_helper.isBuffered(video, currentTime)) {
  7347. fragPlayingCurrent = this.getBufferedFrag(currentTime);
  7348. } else if (buffer_helper.isBuffered(video, currentTime + 0.1)) {
  7349. /* ensure that FRAG_CHANGED event is triggered at startup,
  7350. when first video frame is displayed and playback is paused.
  7351. add a tolerance of 100ms, in case current position is not buffered,
  7352. check if current pos+100ms is buffered and use that buffer range
  7353. for FRAG_CHANGED event reporting */
  7354. fragPlayingCurrent = this.getBufferedFrag(currentTime + 0.1);
  7355. }
  7356. if (fragPlayingCurrent) {
  7357. var fragPlaying = fragPlayingCurrent;
  7358. if (fragPlaying !== this.fragPlaying) {
  7359. this.hls.trigger(events["a" /* default */].FRAG_CHANGED, { frag: fragPlaying });
  7360. var fragPlayingLevel = fragPlaying.level;
  7361. if (!this.fragPlaying || this.fragPlaying.level !== fragPlayingLevel) {
  7362. this.hls.trigger(events["a" /* default */].LEVEL_SWITCHED, { level: fragPlayingLevel });
  7363. }
  7364. this.fragPlaying = fragPlaying;
  7365. }
  7366. }
  7367. }
  7368. };
  7369. /*
  7370. on immediate level switch :
  7371. - pause playback if playing
  7372. - cancel any pending load request
  7373. - and trigger a buffer flush
  7374. */
  7375. StreamController.prototype.immediateLevelSwitch = function immediateLevelSwitch() {
  7376. logger["b" /* logger */].log('immediateLevelSwitch');
  7377. if (!this.immediateSwitch) {
  7378. this.immediateSwitch = true;
  7379. var media = this.media,
  7380. previouslyPaused = void 0;
  7381. if (media) {
  7382. previouslyPaused = media.paused;
  7383. media.pause();
  7384. } else {
  7385. // don't restart playback after instant level switch in case media not attached
  7386. previouslyPaused = true;
  7387. }
  7388. this.previouslyPaused = previouslyPaused;
  7389. }
  7390. var fragCurrent = this.fragCurrent;
  7391. if (fragCurrent && fragCurrent.loader) {
  7392. fragCurrent.loader.abort();
  7393. }
  7394. this.fragCurrent = null;
  7395. // increase fragment load Index to avoid frag loop loading error after buffer flush
  7396. if (this.fragLoadIdx !== undefined) {
  7397. this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;
  7398. }
  7399. // flush everything
  7400. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  7401. };
  7402. /*
  7403. on immediate level switch end, after new fragment has been buffered :
  7404. - nudge video decoder by slightly adjusting video currentTime (if currentTime buffered)
  7405. - resume the playback if needed
  7406. */
  7407. StreamController.prototype.immediateLevelSwitchEnd = function immediateLevelSwitchEnd() {
  7408. var media = this.media;
  7409. if (media && media.buffered.length) {
  7410. this.immediateSwitch = false;
  7411. if (buffer_helper.isBuffered(media, media.currentTime)) {
  7412. // only nudge if currentTime is buffered
  7413. media.currentTime -= 0.0001;
  7414. }
  7415. if (!this.previouslyPaused) {
  7416. media.play();
  7417. }
  7418. }
  7419. };
  7420. StreamController.prototype.nextLevelSwitch = function nextLevelSwitch() {
  7421. /* try to switch ASAP without breaking video playback :
  7422. in order to ensure smooth but quick level switching,
  7423. we need to find the next flushable buffer range
  7424. we should take into account new segment fetch time
  7425. */
  7426. var media = this.media;
  7427. // ensure that media is defined and that metadata are available (to retrieve currentTime)
  7428. if (media && media.readyState) {
  7429. var fetchdelay = void 0,
  7430. fragPlayingCurrent = void 0,
  7431. nextBufferedFrag = void 0;
  7432. if (this.fragLoadIdx !== undefined) {
  7433. // increase fragment load Index to avoid frag loop loading error after buffer flush
  7434. this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;
  7435. }
  7436. fragPlayingCurrent = this.getBufferedFrag(media.currentTime);
  7437. if (fragPlayingCurrent && fragPlayingCurrent.startPTS > 1) {
  7438. // flush buffer preceding current fragment (flush until current fragment start offset)
  7439. // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
  7440. this.flushMainBuffer(0, fragPlayingCurrent.startPTS - 1);
  7441. }
  7442. if (!media.paused) {
  7443. // add a safety delay of 1s
  7444. var nextLevelId = this.hls.nextLoadLevel,
  7445. nextLevel = this.levels[nextLevelId],
  7446. fragLastKbps = this.fragLastKbps;
  7447. if (fragLastKbps && this.fragCurrent) {
  7448. fetchdelay = this.fragCurrent.duration * nextLevel.bitrate / (1000 * fragLastKbps) + 1;
  7449. } else {
  7450. fetchdelay = 0;
  7451. }
  7452. } else {
  7453. fetchdelay = 0;
  7454. }
  7455. //logger.log('fetchdelay:'+fetchdelay);
  7456. // find buffer range that will be reached once new fragment will be fetched
  7457. nextBufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
  7458. if (nextBufferedFrag) {
  7459. // we can flush buffer range following this one without stalling playback
  7460. nextBufferedFrag = this.followingBufferedFrag(nextBufferedFrag);
  7461. if (nextBufferedFrag) {
  7462. // if we are here, we can also cancel any loading/demuxing in progress, as they are useless
  7463. var fragCurrent = this.fragCurrent;
  7464. if (fragCurrent && fragCurrent.loader) {
  7465. fragCurrent.loader.abort();
  7466. }
  7467. this.fragCurrent = null;
  7468. // start flush position is the start PTS of next buffered frag.
  7469. // we use frag.naxStartPTS which is max(audio startPTS, video startPTS).
  7470. // in case there is a small PTS Delta between audio and video, using maxStartPTS avoids flushing last samples from current fragment
  7471. this.flushMainBuffer(nextBufferedFrag.maxStartPTS, Number.POSITIVE_INFINITY);
  7472. }
  7473. }
  7474. }
  7475. };
  7476. StreamController.prototype.flushMainBuffer = function flushMainBuffer(startOffset, endOffset) {
  7477. this.state = State.BUFFER_FLUSHING;
  7478. var flushScope = { startOffset: startOffset, endOffset: endOffset };
  7479. // if alternate audio tracks are used, only flush video, otherwise flush everything
  7480. if (this.altAudio) {
  7481. flushScope.type = 'video';
  7482. }
  7483. this.hls.trigger(events["a" /* default */].BUFFER_FLUSHING, flushScope);
  7484. };
  7485. StreamController.prototype.onMediaAttached = function onMediaAttached(data) {
  7486. var media = this.media = this.mediaBuffer = data.media;
  7487. this.onvseeking = this.onMediaSeeking.bind(this);
  7488. this.onvseeked = this.onMediaSeeked.bind(this);
  7489. this.onvended = this.onMediaEnded.bind(this);
  7490. media.addEventListener('seeking', this.onvseeking);
  7491. media.addEventListener('seeked', this.onvseeked);
  7492. media.addEventListener('ended', this.onvended);
  7493. var config = this.config;
  7494. if (this.levels && config.autoStartLoad) {
  7495. this.hls.startLoad(config.startPosition);
  7496. }
  7497. };
  7498. StreamController.prototype.onMediaDetaching = function onMediaDetaching() {
  7499. var media = this.media;
  7500. if (media && media.ended) {
  7501. logger["b" /* logger */].log('MSE detaching and video ended, reset startPosition');
  7502. this.startPosition = this.lastCurrentTime = 0;
  7503. }
  7504. // reset fragment loading counter on MSE detaching to avoid reporting FRAG_LOOP_LOADING_ERROR after error recovery
  7505. var levels = this.levels;
  7506. if (levels) {
  7507. // reset fragment load counter
  7508. levels.forEach(function (level) {
  7509. if (level.details) {
  7510. level.details.fragments.forEach(function (fragment) {
  7511. fragment.loadCounter = undefined;
  7512. fragment.backtracked = undefined;
  7513. });
  7514. }
  7515. });
  7516. }
  7517. // remove video listeners
  7518. if (media) {
  7519. media.removeEventListener('seeking', this.onvseeking);
  7520. media.removeEventListener('seeked', this.onvseeked);
  7521. media.removeEventListener('ended', this.onvended);
  7522. this.onvseeking = this.onvseeked = this.onvended = null;
  7523. }
  7524. this.media = this.mediaBuffer = null;
  7525. this.loadedmetadata = false;
  7526. this.stopLoad();
  7527. };
  7528. StreamController.prototype.onMediaSeeking = function onMediaSeeking() {
  7529. var media = this.media,
  7530. currentTime = media ? media.currentTime : undefined,
  7531. config = this.config;
  7532. if (!isNaN(currentTime)) {
  7533. logger["b" /* logger */].log('media seeking to ' + currentTime.toFixed(3));
  7534. }
  7535. var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;
  7536. var bufferInfo = buffer_helper.bufferInfo(mediaBuffer, currentTime, this.config.maxBufferHole);
  7537. if (this.state === State.FRAG_LOADING) {
  7538. var fragCurrent = this.fragCurrent;
  7539. // check if we are seeking to a unbuffered area AND if frag loading is in progress
  7540. if (bufferInfo.len === 0 && fragCurrent) {
  7541. var tolerance = config.maxFragLookUpTolerance,
  7542. fragStartOffset = fragCurrent.start - tolerance,
  7543. fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;
  7544. // check if we seek position will be out of currently loaded frag range : if out cancel frag load, if in, don't do anything
  7545. if (currentTime < fragStartOffset || currentTime > fragEndOffset) {
  7546. if (fragCurrent.loader) {
  7547. logger["b" /* logger */].log('seeking outside of buffer while fragment load in progress, cancel fragment load');
  7548. fragCurrent.loader.abort();
  7549. }
  7550. this.fragCurrent = null;
  7551. this.fragPrevious = null;
  7552. // switch to IDLE state to load new fragment
  7553. this.state = State.IDLE;
  7554. } else {
  7555. logger["b" /* logger */].log('seeking outside of buffer but within currently loaded fragment range');
  7556. }
  7557. }
  7558. } else if (this.state === State.ENDED) {
  7559. // if seeking to unbuffered area, clean up fragPrevious
  7560. if (bufferInfo.len === 0) {
  7561. this.fragPrevious = 0;
  7562. }
  7563. // switch to IDLE state to check for potential new fragment
  7564. this.state = State.IDLE;
  7565. }
  7566. if (media) {
  7567. this.lastCurrentTime = currentTime;
  7568. }
  7569. // avoid reporting fragment loop loading error in case user is seeking several times on same position
  7570. if (this.state !== State.FRAG_LOADING && this.fragLoadIdx !== undefined) {
  7571. this.fragLoadIdx += 2 * config.fragLoadingLoopThreshold;
  7572. }
  7573. // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
  7574. if (!this.loadedmetadata) {
  7575. this.nextLoadPosition = this.startPosition = currentTime;
  7576. }
  7577. // tick to speed up processing
  7578. this.tick();
  7579. };
  7580. StreamController.prototype.onMediaSeeked = function onMediaSeeked() {
  7581. var media = this.media,
  7582. currentTime = media ? media.currentTime : undefined;
  7583. if (!isNaN(currentTime)) {
  7584. logger["b" /* logger */].log('media seeked to ' + currentTime.toFixed(3));
  7585. }
  7586. // tick to speed up FRAGMENT_PLAYING triggering
  7587. this.tick();
  7588. };
  7589. StreamController.prototype.onMediaEnded = function onMediaEnded() {
  7590. logger["b" /* logger */].log('media ended');
  7591. // reset startPosition and lastCurrentTime to restart playback @ stream beginning
  7592. this.startPosition = this.lastCurrentTime = 0;
  7593. };
  7594. StreamController.prototype.onManifestLoading = function onManifestLoading() {
  7595. // reset buffer on manifest loading
  7596. logger["b" /* logger */].log('trigger BUFFER_RESET');
  7597. this.hls.trigger(events["a" /* default */].BUFFER_RESET);
  7598. this._bufferedFrags = [];
  7599. this.stalled = false;
  7600. this.startPosition = this.lastCurrentTime = 0;
  7601. };
  7602. StreamController.prototype.onManifestParsed = function onManifestParsed(data) {
  7603. var aac = false,
  7604. heaac = false,
  7605. codec;
  7606. data.levels.forEach(function (level) {
  7607. // detect if we have different kind of audio codecs used amongst playlists
  7608. codec = level.audioCodec;
  7609. if (codec) {
  7610. if (codec.indexOf('mp4a.40.2') !== -1) {
  7611. aac = true;
  7612. }
  7613. if (codec.indexOf('mp4a.40.5') !== -1) {
  7614. heaac = true;
  7615. }
  7616. }
  7617. });
  7618. this.audioCodecSwitch = aac && heaac;
  7619. if (this.audioCodecSwitch) {
  7620. logger["b" /* logger */].log('both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
  7621. }
  7622. this.levels = data.levels;
  7623. this.startFragRequested = false;
  7624. var config = this.config;
  7625. if (config.autoStartLoad || this.forceStartLoad) {
  7626. this.hls.startLoad(config.startPosition);
  7627. }
  7628. };
  7629. StreamController.prototype.onLevelLoaded = function onLevelLoaded(data) {
  7630. var newDetails = data.details;
  7631. var newLevelId = data.level;
  7632. var lastLevel = this.levels[this.levelLastLoaded];
  7633. var curLevel = this.levels[newLevelId];
  7634. var duration = newDetails.totalduration;
  7635. var sliding = 0;
  7636. logger["b" /* logger */].log('level ' + newLevelId + ' loaded [' + newDetails.startSN + ',' + newDetails.endSN + '],duration:' + duration);
  7637. if (newDetails.live) {
  7638. var curDetails = curLevel.details;
  7639. if (curDetails && newDetails.fragments.length > 0) {
  7640. // we already have details for that level, merge them
  7641. mergeDetails(curDetails, newDetails);
  7642. sliding = newDetails.fragments[0].start;
  7643. this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);
  7644. if (newDetails.PTSKnown && !isNaN(sliding)) {
  7645. logger["b" /* logger */].log('live playlist sliding:' + sliding.toFixed(3));
  7646. } else {
  7647. logger["b" /* logger */].log('live playlist - outdated PTS, unknown sliding');
  7648. alignDiscontinuities(this.fragPrevious, lastLevel, newDetails);
  7649. }
  7650. } else {
  7651. logger["b" /* logger */].log('live playlist - first load, unknown sliding');
  7652. newDetails.PTSKnown = false;
  7653. alignDiscontinuities(this.fragPrevious, lastLevel, newDetails);
  7654. }
  7655. } else {
  7656. newDetails.PTSKnown = false;
  7657. }
  7658. // override level info
  7659. curLevel.details = newDetails;
  7660. this.levelLastLoaded = newLevelId;
  7661. this.hls.trigger(events["a" /* default */].LEVEL_UPDATED, { details: newDetails, level: newLevelId });
  7662. if (this.startFragRequested === false) {
  7663. // compute start position if set to -1. use it straight away if value is defined
  7664. if (this.startPosition === -1 || this.lastCurrentTime === -1) {
  7665. // first, check if start time offset has been set in playlist, if yes, use this value
  7666. var startTimeOffset = newDetails.startTimeOffset;
  7667. if (!isNaN(startTimeOffset)) {
  7668. if (startTimeOffset < 0) {
  7669. logger["b" /* logger */].log('negative start time offset ' + startTimeOffset + ', count from end of last fragment');
  7670. startTimeOffset = sliding + duration + startTimeOffset;
  7671. }
  7672. logger["b" /* logger */].log('start time offset found in playlist, adjust startPosition to ' + startTimeOffset);
  7673. this.startPosition = startTimeOffset;
  7674. } else {
  7675. // if live playlist, set start position to be fragment N-this.config.liveSyncDurationCount (usually 3)
  7676. if (newDetails.live) {
  7677. this.startPosition = this.computeLivePosition(sliding, newDetails);
  7678. logger["b" /* logger */].log('configure startPosition to ' + this.startPosition);
  7679. } else {
  7680. this.startPosition = 0;
  7681. }
  7682. }
  7683. this.lastCurrentTime = this.startPosition;
  7684. }
  7685. this.nextLoadPosition = this.startPosition;
  7686. }
  7687. // only switch batck to IDLE state if we were waiting for level to start downloading a new fragment
  7688. if (this.state === State.WAITING_LEVEL) {
  7689. this.state = State.IDLE;
  7690. }
  7691. //trigger handler right now
  7692. this.tick();
  7693. };
  7694. StreamController.prototype.onKeyLoaded = function onKeyLoaded() {
  7695. if (this.state === State.KEY_LOADING) {
  7696. this.state = State.IDLE;
  7697. this.tick();
  7698. }
  7699. };
  7700. StreamController.prototype.onFragLoaded = function onFragLoaded(data) {
  7701. var fragCurrent = this.fragCurrent,
  7702. fragLoaded = data.frag;
  7703. if (this.state === State.FRAG_LOADING && fragCurrent && fragLoaded.type === 'main' && fragLoaded.level === fragCurrent.level && fragLoaded.sn === fragCurrent.sn) {
  7704. var stats = data.stats,
  7705. currentLevel = this.levels[fragCurrent.level],
  7706. details = currentLevel.details;
  7707. logger["b" /* logger */].log('Loaded ' + fragCurrent.sn + ' of [' + details.startSN + ' ,' + details.endSN + '],level ' + fragCurrent.level);
  7708. // reset frag bitrate test in any case after frag loaded event
  7709. this.bitrateTest = false;
  7710. this.stats = stats;
  7711. // if this frag was loaded to perform a bitrate test AND if hls.nextLoadLevel is greater than 0
  7712. // then this means that we should be able to load a fragment at a higher quality level
  7713. if (fragLoaded.bitrateTest === true && this.hls.nextLoadLevel) {
  7714. // switch back to IDLE state ... we just loaded a fragment to determine adequate start bitrate and initialize autoswitch algo
  7715. this.state = State.IDLE;
  7716. this.startFragRequested = false;
  7717. stats.tparsed = stats.tbuffered = performance.now();
  7718. this.hls.trigger(events["a" /* default */].FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' });
  7719. this.tick();
  7720. } else if (fragLoaded.sn === 'initSegment') {
  7721. this.state = State.IDLE;
  7722. stats.tparsed = stats.tbuffered = performance.now();
  7723. details.initSegment.data = data.payload;
  7724. this.hls.trigger(events["a" /* default */].FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' });
  7725. this.tick();
  7726. } else {
  7727. this.state = State.PARSING;
  7728. // transmux the MPEG-TS data to ISO-BMFF segments
  7729. var duration = details.totalduration,
  7730. level = fragCurrent.level,
  7731. sn = fragCurrent.sn,
  7732. audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
  7733. if (this.audioCodecSwap) {
  7734. logger["b" /* logger */].log('swapping playlist audio codec');
  7735. if (audioCodec === undefined) {
  7736. audioCodec = this.lastAudioCodec;
  7737. }
  7738. if (audioCodec) {
  7739. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  7740. audioCodec = 'mp4a.40.2';
  7741. } else {
  7742. audioCodec = 'mp4a.40.5';
  7743. }
  7744. }
  7745. }
  7746. this.pendingBuffering = true;
  7747. this.appended = false;
  7748. logger["b" /* logger */].log('Parsing ' + sn + ' of [' + details.startSN + ' ,' + details.endSN + '],level ' + level + ', cc ' + fragCurrent.cc);
  7749. var demuxer = this.demuxer;
  7750. if (!demuxer) {
  7751. demuxer = this.demuxer = new demux_demuxer(this.hls, 'main');
  7752. }
  7753. // 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)
  7754. var media = this.media;
  7755. var mediaSeeking = media && media.seeking;
  7756. var accurateTimeOffset = !mediaSeeking && (details.PTSKnown || !details.live);
  7757. var initSegmentData = details.initSegment ? details.initSegment.data : [];
  7758. demuxer.push(data.payload, initSegmentData, audioCodec, currentLevel.videoCodec, fragCurrent, duration, accurateTimeOffset, undefined);
  7759. }
  7760. }
  7761. this.fragLoadError = 0;
  7762. };
  7763. StreamController.prototype.onFragParsingInitSegment = function onFragParsingInitSegment(data) {
  7764. var fragCurrent = this.fragCurrent;
  7765. var fragNew = data.frag;
  7766. if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {
  7767. var tracks = data.tracks,
  7768. trackName,
  7769. track;
  7770. // if audio track is expected to come from audio stream controller, discard any coming from main
  7771. if (tracks.audio && this.altAudio) {
  7772. delete tracks.audio;
  7773. }
  7774. // include levelCodec in audio and video tracks
  7775. track = tracks.audio;
  7776. if (track) {
  7777. var audioCodec = this.levels[this.level].audioCodec,
  7778. ua = navigator.userAgent.toLowerCase();
  7779. if (audioCodec && this.audioCodecSwap) {
  7780. logger["b" /* logger */].log('swapping playlist audio codec');
  7781. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  7782. audioCodec = 'mp4a.40.2';
  7783. } else {
  7784. audioCodec = 'mp4a.40.5';
  7785. }
  7786. }
  7787. // in case AAC and HE-AAC audio codecs are signalled in manifest
  7788. // force HE-AAC , as it seems that most browsers prefers that way,
  7789. // except for mono streams OR on FF
  7790. // these conditions might need to be reviewed ...
  7791. if (this.audioCodecSwitch) {
  7792. // don't force HE-AAC if mono stream
  7793. if (track.metadata.channelCount !== 1 &&
  7794. // don't force HE-AAC if firefox
  7795. ua.indexOf('firefox') === -1) {
  7796. audioCodec = 'mp4a.40.5';
  7797. }
  7798. }
  7799. // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise
  7800. if (ua.indexOf('android') !== -1 && track.container !== 'audio/mpeg') {
  7801. // Exclude mpeg audio
  7802. audioCodec = 'mp4a.40.2';
  7803. logger["b" /* logger */].log('Android: force audio codec to ' + audioCodec);
  7804. }
  7805. track.levelCodec = audioCodec;
  7806. track.id = data.id;
  7807. }
  7808. track = tracks.video;
  7809. if (track) {
  7810. track.levelCodec = this.levels[this.level].videoCodec;
  7811. track.id = data.id;
  7812. }
  7813. this.hls.trigger(events["a" /* default */].BUFFER_CODECS, tracks);
  7814. // loop through tracks that are going to be provided to bufferController
  7815. for (trackName in tracks) {
  7816. track = tracks[trackName];
  7817. logger["b" /* logger */].log('main track:' + trackName + ',container:' + track.container + ',codecs[level/parsed]=[' + track.levelCodec + '/' + track.codec + ']');
  7818. var initSegment = track.initSegment;
  7819. if (initSegment) {
  7820. this.appended = true;
  7821. // arm pending Buffering flag before appending a segment
  7822. this.pendingBuffering = true;
  7823. this.hls.trigger(events["a" /* default */].BUFFER_APPENDING, { type: trackName, data: initSegment, parent: 'main', content: 'initSegment' });
  7824. }
  7825. }
  7826. //trigger handler right now
  7827. this.tick();
  7828. }
  7829. };
  7830. StreamController.prototype.onFragParsingData = function onFragParsingData(data) {
  7831. var _this2 = this;
  7832. var fragCurrent = this.fragCurrent;
  7833. var fragNew = data.frag;
  7834. 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
  7835. this.state === State.PARSING) {
  7836. var level = this.levels[this.level],
  7837. frag = fragCurrent;
  7838. if (isNaN(data.endPTS)) {
  7839. data.endPTS = data.startPTS + fragCurrent.duration;
  7840. data.endDTS = data.startDTS + fragCurrent.duration;
  7841. }
  7842. logger["b" /* 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));
  7843. // Detect gaps in a fragment and try to fix it by finding a keyframe in the previous fragment (see _findFragments)
  7844. if (data.type === 'video') {
  7845. frag.dropped = data.dropped;
  7846. if (frag.dropped) {
  7847. if (!frag.backtracked) {
  7848. var levelDetails = level.details;
  7849. if (levelDetails && frag.sn === levelDetails.startSN) {
  7850. logger["b" /* logger */].warn('missing video frame(s) on first frag, appending with gap');
  7851. } else {
  7852. logger["b" /* logger */].warn('missing video frame(s), backtracking fragment');
  7853. // Return back to the IDLE state without appending to buffer
  7854. // Causes findFragments to backtrack a segment and find the keyframe
  7855. // Audio fragments arriving before video sets the nextLoadPosition, causing _findFragments to skip the backtracked fragment
  7856. frag.backtracked = true;
  7857. this.nextLoadPosition = data.startPTS;
  7858. this.state = State.IDLE;
  7859. this.fragPrevious = frag;
  7860. this.tick();
  7861. return;
  7862. }
  7863. } else {
  7864. logger["b" /* logger */].warn('Already backtracked on this fragment, appending with the gap');
  7865. }
  7866. } else {
  7867. // Only reset the backtracked flag if we've loaded the frag without any dropped frames
  7868. frag.backtracked = false;
  7869. }
  7870. }
  7871. var drift = updateFragPTSDTS(level.details, frag, data.startPTS, data.endPTS, data.startDTS, data.endDTS),
  7872. hls = this.hls;
  7873. hls.trigger(events["a" /* default */].LEVEL_PTS_UPDATED, { details: level.details, level: this.level, drift: drift, type: data.type, start: data.startPTS, end: data.endPTS });
  7874. // has remuxer dropped video frames located before first keyframe ?
  7875. [data.data1, data.data2].forEach(function (buffer) {
  7876. // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)
  7877. // in that case it is useless to append following segments
  7878. if (buffer && buffer.length && _this2.state === State.PARSING) {
  7879. _this2.appended = true;
  7880. // arm pending Buffering flag before appending a segment
  7881. _this2.pendingBuffering = true;
  7882. hls.trigger(events["a" /* default */].BUFFER_APPENDING, { type: data.type, data: buffer, parent: 'main', content: 'data' });
  7883. }
  7884. });
  7885. //trigger handler right now
  7886. this.tick();
  7887. }
  7888. };
  7889. StreamController.prototype.onFragParsed = function onFragParsed(data) {
  7890. var fragCurrent = this.fragCurrent;
  7891. var fragNew = data.frag;
  7892. if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {
  7893. this.stats.tparsed = performance.now();
  7894. this.state = State.PARSED;
  7895. this._checkAppendedParsed();
  7896. }
  7897. };
  7898. StreamController.prototype.onAudioTrackSwitching = function onAudioTrackSwitching(data) {
  7899. // if any URL found on new audio track, it is an alternate audio track
  7900. var altAudio = !!data.url,
  7901. trackId = data.id;
  7902. // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered
  7903. // don't do anything if we switch to alt audio: audio stream controller is handling it.
  7904. // we will just have to change buffer scheduling on audioTrackSwitched
  7905. if (!altAudio) {
  7906. if (this.mediaBuffer !== this.media) {
  7907. logger["b" /* logger */].log('switching on main audio, use media.buffered to schedule main fragment loading');
  7908. this.mediaBuffer = this.media;
  7909. var fragCurrent = this.fragCurrent;
  7910. // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch
  7911. if (fragCurrent.loader) {
  7912. logger["b" /* logger */].log('switching to main audio track, cancel main fragment load');
  7913. fragCurrent.loader.abort();
  7914. }
  7915. this.fragCurrent = null;
  7916. this.fragPrevious = null;
  7917. // destroy demuxer to force init segment generation (following audio switch)
  7918. if (this.demuxer) {
  7919. this.demuxer.destroy();
  7920. this.demuxer = null;
  7921. }
  7922. // switch to IDLE state to load new fragment
  7923. this.state = State.IDLE;
  7924. }
  7925. var hls = this.hls;
  7926. // switching to main audio, flush all audio and trigger track switched
  7927. hls.trigger(events["a" /* default */].BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });
  7928. hls.trigger(events["a" /* default */].AUDIO_TRACK_SWITCHED, { id: trackId });
  7929. this.altAudio = false;
  7930. }
  7931. };
  7932. StreamController.prototype.onAudioTrackSwitched = function onAudioTrackSwitched(data) {
  7933. var trackId = data.id,
  7934. altAudio = !!this.hls.audioTracks[trackId].url;
  7935. if (altAudio) {
  7936. var videoBuffer = this.videoBuffer;
  7937. // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered
  7938. if (videoBuffer && this.mediaBuffer !== videoBuffer) {
  7939. logger["b" /* logger */].log('switching on alternate audio, use video.buffered to schedule main fragment loading');
  7940. this.mediaBuffer = videoBuffer;
  7941. }
  7942. }
  7943. this.altAudio = altAudio;
  7944. this.tick();
  7945. };
  7946. StreamController.prototype.onBufferCreated = function onBufferCreated(data) {
  7947. var tracks = data.tracks,
  7948. mediaTrack = void 0,
  7949. name = void 0,
  7950. alternate = false;
  7951. for (var type in tracks) {
  7952. var track = tracks[type];
  7953. if (track.id === 'main') {
  7954. name = type;
  7955. mediaTrack = track;
  7956. // keep video source buffer reference
  7957. if (type === 'video') {
  7958. this.videoBuffer = tracks[type].buffer;
  7959. }
  7960. } else {
  7961. alternate = true;
  7962. }
  7963. }
  7964. if (alternate && mediaTrack) {
  7965. logger["b" /* logger */].log('alternate track found, use ' + name + '.buffered to schedule main fragment loading');
  7966. this.mediaBuffer = mediaTrack.buffer;
  7967. } else {
  7968. this.mediaBuffer = this.media;
  7969. }
  7970. };
  7971. StreamController.prototype.onBufferAppended = function onBufferAppended(data) {
  7972. if (data.parent === 'main') {
  7973. var state = this.state;
  7974. if (state === State.PARSING || state === State.PARSED) {
  7975. // check if all buffers have been appended
  7976. this.pendingBuffering = data.pending > 0;
  7977. this._checkAppendedParsed();
  7978. }
  7979. }
  7980. };
  7981. StreamController.prototype._checkAppendedParsed = function _checkAppendedParsed() {
  7982. //trigger handler right now
  7983. if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) {
  7984. var frag = this.fragCurrent;
  7985. if (frag) {
  7986. var media = this.mediaBuffer ? this.mediaBuffer : this.media;
  7987. logger["b" /* logger */].log('main buffered : ' + timeRanges.toString(media.buffered));
  7988. // filter fragments potentially evicted from buffer. this is to avoid memleak on live streams
  7989. var bufferedFrags = this._bufferedFrags.filter(function (frag) {
  7990. return buffer_helper.isBuffered(media, (frag.startPTS + frag.endPTS) / 2);
  7991. });
  7992. // push new range
  7993. bufferedFrags.push(frag);
  7994. // sort frags, as we use BinarySearch for lookup in getBufferedFrag ...
  7995. this._bufferedFrags = bufferedFrags.sort(function (a, b) {
  7996. return a.startPTS - b.startPTS;
  7997. });
  7998. this.fragPrevious = frag;
  7999. var stats = this.stats;
  8000. stats.tbuffered = performance.now();
  8001. // we should get rid of this.fragLastKbps
  8002. this.fragLastKbps = Math.round(8 * stats.total / (stats.tbuffered - stats.tfirst));
  8003. this.hls.trigger(events["a" /* default */].FRAG_BUFFERED, { stats: stats, frag: frag, id: 'main' });
  8004. this.state = State.IDLE;
  8005. }
  8006. this.tick();
  8007. }
  8008. };
  8009. StreamController.prototype.onError = function onError(data) {
  8010. var frag = data.frag || this.fragCurrent;
  8011. // don't handle frag error not related to main fragment
  8012. if (frag && frag.type !== 'main') {
  8013. return;
  8014. }
  8015. // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
  8016. var mediaBuffered = !!this.media && buffer_helper.isBuffered(this.media, this.media.currentTime) && buffer_helper.isBuffered(this.media, this.media.currentTime + 0.5);
  8017. switch (data.details) {
  8018. case errors["a" /* ErrorDetails */].FRAG_LOAD_ERROR:
  8019. case errors["a" /* ErrorDetails */].FRAG_LOAD_TIMEOUT:
  8020. case errors["a" /* ErrorDetails */].KEY_LOAD_ERROR:
  8021. case errors["a" /* ErrorDetails */].KEY_LOAD_TIMEOUT:
  8022. if (!data.fatal) {
  8023. // keep retrying until the limit will be reached
  8024. if (this.fragLoadError + 1 <= this.config.fragLoadingMaxRetry) {
  8025. // exponential backoff capped to config.fragLoadingMaxRetryTimeout
  8026. var delay = Math.min(Math.pow(2, this.fragLoadError) * this.config.fragLoadingRetryDelay, this.config.fragLoadingMaxRetryTimeout);
  8027. // reset load counter to avoid frag loop loading error
  8028. frag.loadCounter = 0;
  8029. logger["b" /* logger */].warn('mediaController: frag loading failed, retry in ' + delay + ' ms');
  8030. this.retryDate = performance.now() + delay;
  8031. // retry loading state
  8032. // if loadedmetadata is not set, it means that we are emergency switch down on first frag
  8033. // in that case, reset startFragRequested flag
  8034. if (!this.loadedmetadata) {
  8035. this.startFragRequested = false;
  8036. this.nextLoadPosition = this.startPosition;
  8037. }
  8038. this.fragLoadError++;
  8039. this.state = State.FRAG_LOADING_WAITING_RETRY;
  8040. } else {
  8041. logger["b" /* logger */].error('mediaController: ' + data.details + ' reaches max retry, redispatch as fatal ...');
  8042. // switch error to fatal
  8043. data.fatal = true;
  8044. this.state = State.ERROR;
  8045. }
  8046. }
  8047. break;
  8048. case errors["a" /* ErrorDetails */].FRAG_LOOP_LOADING_ERROR:
  8049. if (!data.fatal) {
  8050. // if buffer is not empty
  8051. if (mediaBuffered) {
  8052. // try to reduce max buffer length : rationale is that we could get
  8053. // frag loop loading error because of buffer eviction
  8054. this._reduceMaxBufferLength(frag.duration);
  8055. this.state = State.IDLE;
  8056. } else {
  8057. // buffer empty. report as fatal if in manual mode or if lowest level.
  8058. // level controller takes care of emergency switch down logic
  8059. if (!frag.autoLevel || frag.level === 0) {
  8060. // switch error to fatal
  8061. data.fatal = true;
  8062. this.state = State.ERROR;
  8063. }
  8064. }
  8065. }
  8066. break;
  8067. case errors["a" /* ErrorDetails */].LEVEL_LOAD_ERROR:
  8068. case errors["a" /* ErrorDetails */].LEVEL_LOAD_TIMEOUT:
  8069. if (this.state !== State.ERROR) {
  8070. if (data.fatal) {
  8071. // if fatal error, stop processing
  8072. this.state = State.ERROR;
  8073. logger["b" /* logger */].warn('streamController: ' + data.details + ',switch to ' + this.state + ' state ...');
  8074. } else {
  8075. // in case of non fatal error while loading level, if level controller is not retrying to load level , switch back to IDLE
  8076. if (!data.levelRetry && this.state === State.WAITING_LEVEL) {
  8077. this.state = State.IDLE;
  8078. }
  8079. }
  8080. }
  8081. break;
  8082. case errors["a" /* ErrorDetails */].BUFFER_FULL_ERROR:
  8083. // if in appending state
  8084. if (data.parent === 'main' && (this.state === State.PARSING || this.state === State.PARSED)) {
  8085. // reduce max buf len if current position is buffered
  8086. if (mediaBuffered) {
  8087. this._reduceMaxBufferLength(this.config.maxBufferLength);
  8088. this.state = State.IDLE;
  8089. } else {
  8090. // current position is not buffered, but browser is still complaining about buffer full error
  8091. // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
  8092. // in that case flush the whole buffer to recover
  8093. logger["b" /* logger */].warn('buffer full error also media.currentTime is not buffered, flush everything');
  8094. this.fragCurrent = null;
  8095. // flush everything
  8096. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  8097. }
  8098. }
  8099. break;
  8100. default:
  8101. break;
  8102. }
  8103. };
  8104. StreamController.prototype._reduceMaxBufferLength = function _reduceMaxBufferLength(minLength) {
  8105. var config = this.config;
  8106. if (config.maxMaxBufferLength >= minLength) {
  8107. // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
  8108. config.maxMaxBufferLength /= 2;
  8109. logger["b" /* logger */].warn('main:reduce max buffer length to ' + config.maxMaxBufferLength + 's');
  8110. if (this.fragLoadIdx !== undefined) {
  8111. // increase fragment load Index to avoid frag loop loading error after buffer flush
  8112. this.fragLoadIdx += 2 * config.fragLoadingLoopThreshold;
  8113. }
  8114. }
  8115. };
  8116. StreamController.prototype._checkBuffer = function _checkBuffer() {
  8117. var media = this.media,
  8118. config = this.config;
  8119. // if ready state different from HAVE_NOTHING (numeric value 0), we are allowed to seek
  8120. if (media && media.readyState) {
  8121. var currentTime = media.currentTime,
  8122. mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media,
  8123. buffered = mediaBuffer.buffered;
  8124. // adjust currentTime to start position on loaded metadata
  8125. if (!this.loadedmetadata && buffered.length) {
  8126. this.loadedmetadata = true;
  8127. // only adjust currentTime if different from startPosition or if startPosition not buffered
  8128. // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered
  8129. var startPosition = media.seeking ? currentTime : this.startPosition,
  8130. startPositionBuffered = buffer_helper.isBuffered(mediaBuffer, startPosition),
  8131. firstbufferedPosition = buffered.start(0),
  8132. startNotBufferedButClose = !startPositionBuffered && Math.abs(startPosition - firstbufferedPosition) < config.maxSeekHole;
  8133. // if currentTime not matching with expected startPosition or startPosition not buffered but close to first buffered
  8134. if (currentTime !== startPosition || startNotBufferedButClose) {
  8135. logger["b" /* logger */].log('target start position:' + startPosition);
  8136. // if startPosition not buffered, let's seek to buffered.start(0)
  8137. if (startNotBufferedButClose) {
  8138. startPosition = firstbufferedPosition;
  8139. logger["b" /* logger */].log('target start position not buffered, seek to buffered.start(0) ' + startPosition);
  8140. }
  8141. logger["b" /* logger */].log('adjust currentTime from ' + currentTime + ' to ' + startPosition);
  8142. media.currentTime = startPosition;
  8143. }
  8144. } else if (this.immediateSwitch) {
  8145. this.immediateLevelSwitchEnd();
  8146. } else {
  8147. var bufferInfo = buffer_helper.bufferInfo(media, currentTime, 0),
  8148. expectedPlaying = !(media.paused || // not playing when media is paused
  8149. media.ended || // not playing when media is ended
  8150. media.buffered.length === 0),
  8151. // not playing if nothing buffered
  8152. jumpThreshold = 0.5,
  8153. // tolerance needed as some browsers stalls playback before reaching buffered range end
  8154. playheadMoving = currentTime !== this.lastCurrentTime;
  8155. if (playheadMoving) {
  8156. // played moving, but was previously stalled => now not stuck anymore
  8157. if (this.stallReported) {
  8158. logger["b" /* logger */].warn('playback not stuck anymore @' + currentTime + ', after ' + Math.round(performance.now() - this.stalled) + 'ms');
  8159. this.stallReported = false;
  8160. }
  8161. this.stalled = undefined;
  8162. this.nudgeRetry = 0;
  8163. } else {
  8164. // playhead not moving
  8165. if (expectedPlaying) {
  8166. // playhead not moving BUT media expected to play
  8167. var tnow = performance.now();
  8168. var hls = this.hls;
  8169. if (!this.stalled) {
  8170. // stall just detected, store current time
  8171. this.stalled = tnow;
  8172. this.stallReported = false;
  8173. } else {
  8174. // playback already stalled, check stalling duration
  8175. // if stalling for more than a given threshold, let's try to recover
  8176. var stalledDuration = tnow - this.stalled;
  8177. var bufferLen = bufferInfo.len;
  8178. var nudgeRetry = this.nudgeRetry || 0;
  8179. // have we reached stall deadline ?
  8180. if (bufferLen <= jumpThreshold && stalledDuration > config.lowBufferWatchdogPeriod * 1000) {
  8181. // report stalled error once
  8182. if (!this.stallReported) {
  8183. this.stallReported = true;
  8184. logger["b" /* logger */].warn('playback stalling in low buffer @' + currentTime);
  8185. hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_STALLED_ERROR, fatal: false, buffer: bufferLen });
  8186. }
  8187. // if buffer len is below threshold, try to jump to start of next buffer range if close
  8188. // no buffer available @ currentTime, check if next buffer is close (within a config.maxSeekHole second range)
  8189. var nextBufferStart = bufferInfo.nextStart,
  8190. delta = nextBufferStart - currentTime;
  8191. if (nextBufferStart && delta < config.maxSeekHole && delta > 0) {
  8192. this.nudgeRetry = ++nudgeRetry;
  8193. var nudgeOffset = nudgeRetry * config.nudgeOffset;
  8194. // next buffer is close ! adjust currentTime to nextBufferStart
  8195. // this will ensure effective video decoding
  8196. logger["b" /* logger */].log('adjust currentTime from ' + media.currentTime + ' to next buffered @ ' + nextBufferStart + ' + nudge ' + nudgeOffset);
  8197. media.currentTime = nextBufferStart + nudgeOffset;
  8198. // reset stalled so to rearm watchdog timer
  8199. this.stalled = undefined;
  8200. hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_SEEK_OVER_HOLE, fatal: false, hole: nextBufferStart + nudgeOffset - currentTime });
  8201. }
  8202. } else if (bufferLen > jumpThreshold && stalledDuration > config.highBufferWatchdogPeriod * 1000) {
  8203. // report stalled error once
  8204. if (!this.stallReported) {
  8205. this.stallReported = true;
  8206. logger["b" /* logger */].warn('playback stalling in high buffer @' + currentTime);
  8207. hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_STALLED_ERROR, fatal: false, buffer: bufferLen });
  8208. }
  8209. // reset stalled so to rearm watchdog timer
  8210. this.stalled = undefined;
  8211. this.nudgeRetry = ++nudgeRetry;
  8212. if (nudgeRetry < config.nudgeMaxRetry) {
  8213. var _currentTime = media.currentTime;
  8214. var targetTime = _currentTime + nudgeRetry * config.nudgeOffset;
  8215. logger["b" /* logger */].log('adjust currentTime from ' + _currentTime + ' to ' + targetTime);
  8216. // playback stalled in buffered area ... let's nudge currentTime to try to overcome this
  8217. media.currentTime = targetTime;
  8218. hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_NUDGE_ON_STALL, fatal: false });
  8219. } else {
  8220. logger["b" /* logger */].error('still stuck in high buffer @' + currentTime + ' after ' + config.nudgeMaxRetry + ', raise fatal error');
  8221. hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_STALLED_ERROR, fatal: true });
  8222. }
  8223. }
  8224. }
  8225. }
  8226. }
  8227. }
  8228. }
  8229. };
  8230. StreamController.prototype.onFragLoadEmergencyAborted = function onFragLoadEmergencyAborted() {
  8231. this.state = State.IDLE;
  8232. // if loadedmetadata is not set, it means that we are emergency switch down on first frag
  8233. // in that case, reset startFragRequested flag
  8234. if (!this.loadedmetadata) {
  8235. this.startFragRequested = false;
  8236. this.nextLoadPosition = this.startPosition;
  8237. }
  8238. this.tick();
  8239. };
  8240. StreamController.prototype.onBufferFlushed = function onBufferFlushed() {
  8241. /* after successful buffer flushing, filter flushed fragments from bufferedFrags
  8242. use mediaBuffered instead of media (so that we will check against video.buffered ranges in case of alt audio track)
  8243. */
  8244. var media = this.mediaBuffer ? this.mediaBuffer : this.media;
  8245. this._bufferedFrags = this._bufferedFrags.filter(function (frag) {
  8246. return buffer_helper.isBuffered(media, (frag.startPTS + frag.endPTS) / 2);
  8247. });
  8248. if (this.fragLoadIdx !== undefined) {
  8249. // increase fragment load Index to avoid frag loop loading error after buffer flush
  8250. this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;
  8251. }
  8252. // move to IDLE once flush complete. this should trigger new fragment loading
  8253. this.state = State.IDLE;
  8254. // reset reference to frag
  8255. this.fragPrevious = null;
  8256. };
  8257. StreamController.prototype.swapAudioCodec = function swapAudioCodec() {
  8258. this.audioCodecSwap = !this.audioCodecSwap;
  8259. };
  8260. StreamController.prototype.computeLivePosition = function computeLivePosition(sliding, levelDetails) {
  8261. var targetLatency = this.config.liveSyncDuration !== undefined ? this.config.liveSyncDuration : this.config.liveSyncDurationCount * levelDetails.targetduration;
  8262. return sliding + Math.max(0, levelDetails.totalduration - targetLatency);
  8263. };
  8264. stream_controller__createClass(StreamController, [{
  8265. key: 'state',
  8266. set: function set(nextState) {
  8267. if (this.state !== nextState) {
  8268. var previousState = this.state;
  8269. this._state = nextState;
  8270. logger["b" /* logger */].log('main stream:' + previousState + '->' + nextState);
  8271. this.hls.trigger(events["a" /* default */].STREAM_STATE_TRANSITION, { previousState: previousState, nextState: nextState });
  8272. }
  8273. },
  8274. get: function get() {
  8275. return this._state;
  8276. }
  8277. }, {
  8278. key: 'currentLevel',
  8279. get: function get() {
  8280. var media = this.media;
  8281. if (media) {
  8282. var frag = this.getBufferedFrag(media.currentTime);
  8283. if (frag) {
  8284. return frag.level;
  8285. }
  8286. }
  8287. return -1;
  8288. }
  8289. }, {
  8290. key: 'nextBufferedFrag',
  8291. get: function get() {
  8292. var media = this.media;
  8293. if (media) {
  8294. // first get end range of current fragment
  8295. return this.followingBufferedFrag(this.getBufferedFrag(media.currentTime));
  8296. } else {
  8297. return null;
  8298. }
  8299. }
  8300. }, {
  8301. key: 'nextLevel',
  8302. get: function get() {
  8303. var frag = this.nextBufferedFrag;
  8304. if (frag) {
  8305. return frag.level;
  8306. } else {
  8307. return -1;
  8308. }
  8309. }
  8310. }, {
  8311. key: 'liveSyncPosition',
  8312. get: function get() {
  8313. return this._liveSyncPosition;
  8314. },
  8315. set: function set(value) {
  8316. this._liveSyncPosition = value;
  8317. }
  8318. }]);
  8319. return StreamController;
  8320. }(task_loop);
  8321. /* harmony default export */ var stream_controller = (stream_controller_StreamController);
  8322. // CONCATENATED MODULE: ./src/controller/level-controller.js
  8323. var level_controller__createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  8324. function level_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8325. function level_controller__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; }
  8326. function level_controller__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; }
  8327. /*
  8328. * Level Controller
  8329. */
  8330. var level_controller_LevelController = function (_EventHandler) {
  8331. level_controller__inherits(LevelController, _EventHandler);
  8332. function LevelController(hls) {
  8333. level_controller__classCallCheck(this, LevelController);
  8334. var _this = level_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MANIFEST_LOADED, events["a" /* default */].LEVEL_LOADED, events["a" /* default */].FRAG_LOADED, events["a" /* default */].ERROR));
  8335. _this.canload = false;
  8336. _this.currentLevelIndex = null;
  8337. _this.manualLevelIndex = -1;
  8338. _this.timer = null;
  8339. return _this;
  8340. }
  8341. LevelController.prototype.onHandlerDestroying = function onHandlerDestroying() {
  8342. this.cleanTimer();
  8343. this.manualLevelIndex = -1;
  8344. };
  8345. LevelController.prototype.cleanTimer = function cleanTimer() {
  8346. if (this.timer !== null) {
  8347. clearTimeout(this.timer);
  8348. this.timer = null;
  8349. }
  8350. };
  8351. LevelController.prototype.startLoad = function startLoad() {
  8352. var levels = this._levels;
  8353. this.canload = true;
  8354. this.levelRetryCount = 0;
  8355. // clean up live level details to force reload them, and reset load errors
  8356. if (levels) {
  8357. levels.forEach(function (level) {
  8358. level.loadError = 0;
  8359. var levelDetails = level.details;
  8360. if (levelDetails && levelDetails.live) {
  8361. level.details = undefined;
  8362. }
  8363. });
  8364. }
  8365. // speed up live playlist refresh if timer exists
  8366. if (this.timer !== null) {
  8367. this.loadLevel();
  8368. }
  8369. };
  8370. LevelController.prototype.stopLoad = function stopLoad() {
  8371. this.canload = false;
  8372. };
  8373. LevelController.prototype.onManifestLoaded = function onManifestLoaded(data) {
  8374. var levels = [];
  8375. var bitrateStart = void 0;
  8376. var levelSet = {};
  8377. var levelFromSet = null;
  8378. var videoCodecFound = false;
  8379. var audioCodecFound = false;
  8380. var chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase());
  8381. var audioTracks = [];
  8382. // regroup redundant levels together
  8383. data.levels.forEach(function (level) {
  8384. level.loadError = 0;
  8385. level.fragmentError = false;
  8386. videoCodecFound = videoCodecFound || !!level.videoCodec;
  8387. audioCodecFound = audioCodecFound || !!level.audioCodec || !!(level.attrs && level.attrs.AUDIO);
  8388. // erase audio codec info if browser does not support mp4a.40.34.
  8389. // demuxer will autodetect codec and fallback to mpeg/audio
  8390. if (chromeOrFirefox === true && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) {
  8391. level.audioCodec = undefined;
  8392. }
  8393. levelFromSet = levelSet[level.bitrate];
  8394. if (levelFromSet === undefined) {
  8395. level.url = [level.url];
  8396. level.urlId = 0;
  8397. levelSet[level.bitrate] = level;
  8398. levels.push(level);
  8399. } else {
  8400. levelFromSet.url.push(level.url);
  8401. }
  8402. });
  8403. // remove audio-only level if we also have levels with audio+video codecs signalled
  8404. if (videoCodecFound === true && audioCodecFound === true) {
  8405. levels = levels.filter(function (_ref) {
  8406. var videoCodec = _ref.videoCodec;
  8407. return !!videoCodec;
  8408. });
  8409. }
  8410. // only keep levels with supported audio/video codecs
  8411. levels = levels.filter(function (_ref2) {
  8412. var audioCodec = _ref2.audioCodec,
  8413. videoCodec = _ref2.videoCodec;
  8414. return (!audioCodec || isCodecSupportedInMp4(audioCodec)) && (!videoCodec || isCodecSupportedInMp4(videoCodec));
  8415. });
  8416. if (data.audioTracks) {
  8417. audioTracks = data.audioTracks.filter(function (track) {
  8418. return !track.audioCodec || isCodecSupportedInMp4(track.audioCodec, 'audio');
  8419. });
  8420. }
  8421. if (levels.length > 0) {
  8422. // start bitrate is the first bitrate of the manifest
  8423. bitrateStart = levels[0].bitrate;
  8424. // sort level on bitrate
  8425. levels.sort(function (a, b) {
  8426. return a.bitrate - b.bitrate;
  8427. });
  8428. this._levels = levels;
  8429. // find index of first level in sorted levels
  8430. for (var i = 0; i < levels.length; i++) {
  8431. if (levels[i].bitrate === bitrateStart) {
  8432. this._firstLevel = i;
  8433. logger["b" /* logger */].log('manifest loaded,' + levels.length + ' level(s) found, first bitrate:' + bitrateStart);
  8434. break;
  8435. }
  8436. }
  8437. this.hls.trigger(events["a" /* default */].MANIFEST_PARSED, {
  8438. levels: levels,
  8439. audioTracks: audioTracks,
  8440. firstLevel: this._firstLevel,
  8441. stats: data.stats,
  8442. audio: audioCodecFound,
  8443. video: videoCodecFound,
  8444. altAudio: audioTracks.length > 0
  8445. });
  8446. } else {
  8447. this.hls.trigger(events["a" /* default */].ERROR, {
  8448. type: errors["b" /* ErrorTypes */].MEDIA_ERROR,
  8449. details: errors["a" /* ErrorDetails */].MANIFEST_INCOMPATIBLE_CODECS_ERROR,
  8450. fatal: true,
  8451. url: this.hls.url,
  8452. reason: 'no level with compatible codecs found in manifest'
  8453. });
  8454. }
  8455. };
  8456. LevelController.prototype.setLevelInternal = function setLevelInternal(newLevel) {
  8457. var levels = this._levels;
  8458. var hls = this.hls;
  8459. // check if level idx is valid
  8460. if (newLevel >= 0 && newLevel < levels.length) {
  8461. // stopping live reloading timer if any
  8462. this.cleanTimer();
  8463. if (this.currentLevelIndex !== newLevel) {
  8464. logger["b" /* logger */].log('switching to level ' + newLevel);
  8465. this.currentLevelIndex = newLevel;
  8466. var levelProperties = levels[newLevel];
  8467. levelProperties.level = newLevel;
  8468. // LEVEL_SWITCH to be deprecated in next major release
  8469. hls.trigger(events["a" /* default */].LEVEL_SWITCH, levelProperties);
  8470. hls.trigger(events["a" /* default */].LEVEL_SWITCHING, levelProperties);
  8471. }
  8472. var level = levels[newLevel],
  8473. levelDetails = level.details;
  8474. // check if we need to load playlist for this level
  8475. if (!levelDetails || levelDetails.live === true) {
  8476. // level not retrieved yet, or live playlist we need to (re)load it
  8477. var urlId = level.urlId;
  8478. hls.trigger(events["a" /* default */].LEVEL_LOADING, { url: level.url[urlId], level: newLevel, id: urlId });
  8479. }
  8480. } else {
  8481. // invalid level id given, trigger error
  8482. hls.trigger(events["a" /* default */].ERROR, {
  8483. type: errors["b" /* ErrorTypes */].OTHER_ERROR,
  8484. details: errors["a" /* ErrorDetails */].LEVEL_SWITCH_ERROR,
  8485. level: newLevel,
  8486. fatal: false,
  8487. reason: 'invalid level idx'
  8488. });
  8489. }
  8490. };
  8491. LevelController.prototype.onError = function onError(data) {
  8492. if (data.fatal === true) {
  8493. if (data.type === errors["b" /* ErrorTypes */].NETWORK_ERROR) {
  8494. this.cleanTimer();
  8495. }
  8496. return;
  8497. }
  8498. var levelError = false,
  8499. fragmentError = false;
  8500. var levelIndex = void 0;
  8501. // try to recover not fatal errors
  8502. switch (data.details) {
  8503. case errors["a" /* ErrorDetails */].FRAG_LOAD_ERROR:
  8504. case errors["a" /* ErrorDetails */].FRAG_LOAD_TIMEOUT:
  8505. case errors["a" /* ErrorDetails */].FRAG_LOOP_LOADING_ERROR:
  8506. case errors["a" /* ErrorDetails */].KEY_LOAD_ERROR:
  8507. case errors["a" /* ErrorDetails */].KEY_LOAD_TIMEOUT:
  8508. levelIndex = data.frag.level;
  8509. fragmentError = true;
  8510. break;
  8511. case errors["a" /* ErrorDetails */].LEVEL_LOAD_ERROR:
  8512. case errors["a" /* ErrorDetails */].LEVEL_LOAD_TIMEOUT:
  8513. levelIndex = data.context.level;
  8514. levelError = true;
  8515. break;
  8516. case errors["a" /* ErrorDetails */].REMUX_ALLOC_ERROR:
  8517. levelIndex = data.level;
  8518. levelError = true;
  8519. break;
  8520. }
  8521. if (levelIndex !== undefined) {
  8522. this.recoverLevel(data, levelIndex, levelError, fragmentError);
  8523. }
  8524. };
  8525. /**
  8526. * Switch to a redundant stream if any available.
  8527. * If redundant stream is not available, emergency switch down if ABR mode is enabled.
  8528. *
  8529. * @param {Object} errorEvent
  8530. * @param {Number} levelIndex current level index
  8531. * @param {Boolean} levelError
  8532. * @param {Boolean} fragmentError
  8533. */
  8534. // FIXME Find a better abstraction where fragment/level retry management is well decoupled
  8535. LevelController.prototype.recoverLevel = function recoverLevel(errorEvent, levelIndex, levelError, fragmentError) {
  8536. var _this2 = this;
  8537. var config = this.hls.config;
  8538. var errorDetails = errorEvent.details;
  8539. var level = this._levels[levelIndex];
  8540. var redundantLevels = void 0,
  8541. delay = void 0,
  8542. nextLevel = void 0;
  8543. level.loadError++;
  8544. level.fragmentError = fragmentError;
  8545. if (levelError === true) {
  8546. if (this.levelRetryCount + 1 <= config.levelLoadingMaxRetry) {
  8547. // exponential backoff capped to max retry timeout
  8548. delay = Math.min(Math.pow(2, this.levelRetryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout);
  8549. // Schedule level reload
  8550. this.timer = setTimeout(function () {
  8551. return _this2.loadLevel();
  8552. }, delay);
  8553. // boolean used to inform stream controller not to switch back to IDLE on non fatal error
  8554. errorEvent.levelRetry = true;
  8555. this.levelRetryCount++;
  8556. logger["b" /* logger */].warn('level controller, ' + errorDetails + ', retry in ' + delay + ' ms, current retry count is ' + this.levelRetryCount);
  8557. } else {
  8558. logger["b" /* logger */].error('level controller, cannot recover from ' + errorDetails + ' error');
  8559. this.currentLevelIndex = null;
  8560. // stopping live reloading timer if any
  8561. this.cleanTimer();
  8562. // switch error to fatal
  8563. errorEvent.fatal = true;
  8564. return;
  8565. }
  8566. }
  8567. // Try any redundant streams if available for both errors: level and fragment
  8568. // If level.loadError reaches redundantLevels it means that we tried them all, no hope => let's switch down
  8569. if (levelError === true || fragmentError === true) {
  8570. redundantLevels = level.url.length;
  8571. if (redundantLevels > 1 && level.loadError < redundantLevels) {
  8572. logger["b" /* logger */].warn('level controller, ' + errorDetails + ' for level ' + levelIndex + ': switching to redundant stream id ' + level.urlId);
  8573. level.urlId = (level.urlId + 1) % redundantLevels;
  8574. level.details = undefined;
  8575. } else {
  8576. // Search for available level
  8577. if (this.manualLevelIndex === -1) {
  8578. // When lowest level has been reached, let's start hunt from the top
  8579. nextLevel = levelIndex === 0 ? this._levels.length - 1 : levelIndex - 1;
  8580. logger["b" /* logger */].warn('level controller, ' + errorDetails + ': switch to ' + nextLevel);
  8581. this.hls.nextAutoLevel = this.currentLevelIndex = nextLevel;
  8582. } else if (fragmentError === true) {
  8583. // Allow fragment retry as long as configuration allows.
  8584. // reset this._level so that another call to set level() will trigger again a frag load
  8585. logger["b" /* logger */].warn('level controller, ' + errorDetails + ': reload a fragment');
  8586. this.currentLevelIndex = null;
  8587. }
  8588. }
  8589. }
  8590. };
  8591. // reset errors on the successful load of a fragment
  8592. LevelController.prototype.onFragLoaded = function onFragLoaded(_ref3) {
  8593. var frag = _ref3.frag;
  8594. if (frag !== undefined && frag.type === 'main') {
  8595. var level = this._levels[frag.level];
  8596. if (level !== undefined) {
  8597. level.fragmentError = false;
  8598. level.loadError = 0;
  8599. this.levelRetryCount = 0;
  8600. }
  8601. }
  8602. };
  8603. LevelController.prototype.onLevelLoaded = function onLevelLoaded(data) {
  8604. var _this3 = this;
  8605. var levelId = data.level;
  8606. // only process level loaded events matching with expected level
  8607. if (levelId === this.currentLevelIndex) {
  8608. var curLevel = this._levels[levelId];
  8609. // reset level load error counter on successful level loaded only if there is no issues with fragments
  8610. if (curLevel.fragmentError === false) {
  8611. curLevel.loadError = 0;
  8612. this.levelRetryCount = 0;
  8613. }
  8614. var newDetails = data.details;
  8615. // if current playlist is a live playlist, arm a timer to reload it
  8616. if (newDetails.live) {
  8617. var reloadInterval = 1000 * (newDetails.averagetargetduration ? newDetails.averagetargetduration : newDetails.targetduration),
  8618. curDetails = curLevel.details;
  8619. if (curDetails && newDetails.endSN === curDetails.endSN) {
  8620. // follow HLS Spec, If the client reloads a Playlist file and finds that it has not
  8621. // changed then it MUST wait for a period of one-half the target
  8622. // duration before retrying.
  8623. reloadInterval /= 2;
  8624. logger["b" /* logger */].log('same live playlist, reload twice faster');
  8625. }
  8626. // decrement reloadInterval with level loading delay
  8627. reloadInterval -= performance.now() - data.stats.trequest;
  8628. // in any case, don't reload more than every second
  8629. reloadInterval = Math.max(1000, Math.round(reloadInterval));
  8630. logger["b" /* logger */].log('live playlist, reload in ' + reloadInterval + ' ms');
  8631. this.timer = setTimeout(function () {
  8632. return _this3.loadLevel();
  8633. }, reloadInterval);
  8634. } else {
  8635. this.cleanTimer();
  8636. }
  8637. }
  8638. };
  8639. LevelController.prototype.loadLevel = function loadLevel() {
  8640. var level = void 0,
  8641. urlIndex = void 0;
  8642. if (this.currentLevelIndex !== null && this.canload === true) {
  8643. level = this._levels[this.currentLevelIndex];
  8644. if (level !== undefined && level.url.length > 0) {
  8645. urlIndex = level.urlId;
  8646. this.hls.trigger(events["a" /* default */].LEVEL_LOADING, { url: level.url[urlIndex], level: this.currentLevelIndex, id: urlIndex });
  8647. }
  8648. }
  8649. };
  8650. level_controller__createClass(LevelController, [{
  8651. key: 'levels',
  8652. get: function get() {
  8653. return this._levels;
  8654. }
  8655. }, {
  8656. key: 'level',
  8657. get: function get() {
  8658. return this.currentLevelIndex;
  8659. },
  8660. set: function set(newLevel) {
  8661. var levels = this._levels;
  8662. if (levels) {
  8663. newLevel = Math.min(newLevel, levels.length - 1);
  8664. if (this.currentLevelIndex !== newLevel || levels[newLevel].details === undefined) {
  8665. this.setLevelInternal(newLevel);
  8666. }
  8667. }
  8668. }
  8669. }, {
  8670. key: 'manualLevel',
  8671. get: function get() {
  8672. return this.manualLevelIndex;
  8673. },
  8674. set: function set(newLevel) {
  8675. this.manualLevelIndex = newLevel;
  8676. if (this._startLevel === undefined) {
  8677. this._startLevel = newLevel;
  8678. }
  8679. if (newLevel !== -1) {
  8680. this.level = newLevel;
  8681. }
  8682. }
  8683. }, {
  8684. key: 'firstLevel',
  8685. get: function get() {
  8686. return this._firstLevel;
  8687. },
  8688. set: function set(newLevel) {
  8689. this._firstLevel = newLevel;
  8690. }
  8691. }, {
  8692. key: 'startLevel',
  8693. get: function get() {
  8694. // hls.startLevel takes precedence over config.startLevel
  8695. // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)
  8696. if (this._startLevel === undefined) {
  8697. var configStartLevel = this.hls.config.startLevel;
  8698. if (configStartLevel !== undefined) {
  8699. return configStartLevel;
  8700. } else {
  8701. return this._firstLevel;
  8702. }
  8703. } else {
  8704. return this._startLevel;
  8705. }
  8706. },
  8707. set: function set(newLevel) {
  8708. this._startLevel = newLevel;
  8709. }
  8710. }, {
  8711. key: 'nextLoadLevel',
  8712. get: function get() {
  8713. if (this.manualLevelIndex !== -1) {
  8714. return this.manualLevelIndex;
  8715. } else {
  8716. return this.hls.nextAutoLevel;
  8717. }
  8718. },
  8719. set: function set(nextLevel) {
  8720. this.level = nextLevel;
  8721. if (this.manualLevelIndex === -1) {
  8722. this.hls.nextAutoLevel = nextLevel;
  8723. }
  8724. }
  8725. }]);
  8726. return LevelController;
  8727. }(event_handler);
  8728. /* harmony default export */ var level_controller = (level_controller_LevelController);
  8729. // EXTERNAL MODULE: ./src/demux/id3.js
  8730. var id3 = __webpack_require__(4);
  8731. // CONCATENATED MODULE: ./src/controller/id3-track-controller.js
  8732. function id3_track_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8733. function id3_track_controller__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; }
  8734. function id3_track_controller__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; }
  8735. /*
  8736. * id3 metadata track controller
  8737. */
  8738. var id3_track_controller_ID3TrackController = function (_EventHandler) {
  8739. id3_track_controller__inherits(ID3TrackController, _EventHandler);
  8740. function ID3TrackController(hls) {
  8741. id3_track_controller__classCallCheck(this, ID3TrackController);
  8742. var _this = id3_track_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MEDIA_ATTACHED, events["a" /* default */].MEDIA_DETACHING, events["a" /* default */].FRAG_PARSING_METADATA));
  8743. _this.id3Track = undefined;
  8744. _this.media = undefined;
  8745. return _this;
  8746. }
  8747. ID3TrackController.prototype.destroy = function destroy() {
  8748. event_handler.prototype.destroy.call(this);
  8749. };
  8750. // Add ID3 metatadata text track.
  8751. ID3TrackController.prototype.onMediaAttached = function onMediaAttached(data) {
  8752. this.media = data.media;
  8753. if (!this.media) {
  8754. return;
  8755. }
  8756. };
  8757. ID3TrackController.prototype.onMediaDetaching = function onMediaDetaching() {
  8758. this.media = undefined;
  8759. };
  8760. ID3TrackController.prototype.onFragParsingMetadata = function onFragParsingMetadata(data) {
  8761. var fragment = data.frag;
  8762. var samples = data.samples;
  8763. // create track dynamically
  8764. if (!this.id3Track) {
  8765. this.id3Track = this.media.addTextTrack('metadata', 'id3');
  8766. this.id3Track.mode = 'hidden';
  8767. }
  8768. // Attempt to recreate Safari functionality by creating
  8769. // WebKitDataCue objects when available and store the decoded
  8770. // ID3 data in the value property of the cue
  8771. var Cue = window.WebKitDataCue || window.VTTCue || window.TextTrackCue;
  8772. for (var i = 0; i < samples.length; i++) {
  8773. var frames = id3["a" /* default */].getID3Frames(samples[i].data);
  8774. if (frames) {
  8775. var startTime = samples[i].pts;
  8776. var endTime = i < samples.length - 1 ? samples[i + 1].pts : fragment.endPTS;
  8777. // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE
  8778. if (startTime === endTime) {
  8779. endTime += 0.0001;
  8780. }
  8781. for (var j = 0; j < frames.length; j++) {
  8782. var frame = frames[j];
  8783. // Safari doesn't put the timestamp frame in the TextTrack
  8784. if (!id3["a" /* default */].isTimeStampFrame(frame)) {
  8785. var cue = new Cue(startTime, endTime, '');
  8786. cue.value = frame;
  8787. this.id3Track.addCue(cue);
  8788. }
  8789. }
  8790. }
  8791. }
  8792. };
  8793. return ID3TrackController;
  8794. }(event_handler);
  8795. /* harmony default export */ var id3_track_controller = (id3_track_controller_ID3TrackController);
  8796. // CONCATENATED MODULE: ./src/helper/is-supported.js
  8797. function is_supported_isSupported() {
  8798. var mediaSource = getMediaSource();
  8799. var sourceBuffer = window.SourceBuffer || window.WebKitSourceBuffer;
  8800. var isTypeSupported = mediaSource && typeof mediaSource.isTypeSupported === 'function' && mediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"');
  8801. // if SourceBuffer is exposed ensure its API is valid
  8802. // safari and old version of Chrome doe not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible
  8803. var sourceBufferValidAPI = !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function';
  8804. return !!isTypeSupported && !!sourceBufferValidAPI;
  8805. }
  8806. // CONCATENATED MODULE: ./src/utils/ewma.js
  8807. function ewma__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8808. /*
  8809. * compute an Exponential Weighted moving average
  8810. * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  8811. * - heavily inspired from shaka-player
  8812. */
  8813. var EWMA = function () {
  8814. // About half of the estimated value will be from the last |halfLife| samples by weight.
  8815. function EWMA(halfLife) {
  8816. ewma__classCallCheck(this, EWMA);
  8817. // Larger values of alpha expire historical data more slowly.
  8818. this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
  8819. this.estimate_ = 0;
  8820. this.totalWeight_ = 0;
  8821. }
  8822. EWMA.prototype.sample = function sample(weight, value) {
  8823. var adjAlpha = Math.pow(this.alpha_, weight);
  8824. this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
  8825. this.totalWeight_ += weight;
  8826. };
  8827. EWMA.prototype.getTotalWeight = function getTotalWeight() {
  8828. return this.totalWeight_;
  8829. };
  8830. EWMA.prototype.getEstimate = function getEstimate() {
  8831. if (this.alpha_) {
  8832. var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
  8833. return this.estimate_ / zeroFactor;
  8834. } else {
  8835. return this.estimate_;
  8836. }
  8837. };
  8838. return EWMA;
  8839. }();
  8840. /* harmony default export */ var ewma = (EWMA);
  8841. // CONCATENATED MODULE: ./src/utils/ewma-bandwidth-estimator.js
  8842. function ewma_bandwidth_estimator__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8843. /*
  8844. * EWMA Bandwidth Estimator
  8845. * - heavily inspired from shaka-player
  8846. * Tracks bandwidth samples and estimates available bandwidth.
  8847. * Based on the minimum of two exponentially-weighted moving averages with
  8848. * different half-lives.
  8849. */
  8850. var ewma_bandwidth_estimator_EwmaBandWidthEstimator = function () {
  8851. function EwmaBandWidthEstimator(hls, slow, fast, defaultEstimate) {
  8852. ewma_bandwidth_estimator__classCallCheck(this, EwmaBandWidthEstimator);
  8853. this.hls = hls;
  8854. this.defaultEstimate_ = defaultEstimate;
  8855. this.minWeight_ = 0.001;
  8856. this.minDelayMs_ = 50;
  8857. this.slow_ = new ewma(slow);
  8858. this.fast_ = new ewma(fast);
  8859. }
  8860. EwmaBandWidthEstimator.prototype.sample = function sample(durationMs, numBytes) {
  8861. durationMs = Math.max(durationMs, this.minDelayMs_);
  8862. var bandwidth = 8000 * numBytes / durationMs,
  8863. //console.log('instant bw:'+ Math.round(bandwidth));
  8864. // we weight sample using loading duration....
  8865. weight = durationMs / 1000;
  8866. this.fast_.sample(weight, bandwidth);
  8867. this.slow_.sample(weight, bandwidth);
  8868. };
  8869. EwmaBandWidthEstimator.prototype.canEstimate = function canEstimate() {
  8870. var fast = this.fast_;
  8871. return fast && fast.getTotalWeight() >= this.minWeight_;
  8872. };
  8873. EwmaBandWidthEstimator.prototype.getEstimate = function getEstimate() {
  8874. if (this.canEstimate()) {
  8875. //console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));
  8876. //console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));
  8877. // Take the minimum of these two estimates. This should have the effect of
  8878. // adapting down quickly, but up more slowly.
  8879. return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
  8880. } else {
  8881. return this.defaultEstimate_;
  8882. }
  8883. };
  8884. EwmaBandWidthEstimator.prototype.destroy = function destroy() {};
  8885. return EwmaBandWidthEstimator;
  8886. }();
  8887. /* harmony default export */ var ewma_bandwidth_estimator = (ewma_bandwidth_estimator_EwmaBandWidthEstimator);
  8888. // CONCATENATED MODULE: ./src/controller/abr-controller.js
  8889. var abr_controller__createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  8890. function abr_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8891. function abr_controller__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; }
  8892. function abr_controller__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; }
  8893. /*
  8894. * simple ABR Controller
  8895. * - compute next level based on last fragment bw heuristics
  8896. * - implement an abandon rules triggered if we have less than 2 frag buffered and if computed bw shows that we risk buffer stalling
  8897. */
  8898. var abr_controller_AbrController = function (_EventHandler) {
  8899. abr_controller__inherits(AbrController, _EventHandler);
  8900. function AbrController(hls) {
  8901. abr_controller__classCallCheck(this, AbrController);
  8902. var _this = abr_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].FRAG_LOADING, events["a" /* default */].FRAG_LOADED, events["a" /* default */].FRAG_BUFFERED, events["a" /* default */].ERROR));
  8903. _this.lastLoadedFragLevel = 0;
  8904. _this._nextAutoLevel = -1;
  8905. _this.hls = hls;
  8906. _this.timer = null;
  8907. _this._bwEstimator = null;
  8908. _this.onCheck = _this._abandonRulesCheck.bind(_this);
  8909. return _this;
  8910. }
  8911. AbrController.prototype.destroy = function destroy() {
  8912. this.clearTimer();
  8913. event_handler.prototype.destroy.call(this);
  8914. };
  8915. AbrController.prototype.onFragLoading = function onFragLoading(data) {
  8916. var frag = data.frag;
  8917. if (frag.type === 'main') {
  8918. if (!this.timer) {
  8919. this.timer = setInterval(this.onCheck, 100);
  8920. }
  8921. // lazy init of bw Estimator, rationale is that we use different params for Live/VoD
  8922. // so we need to wait for stream manifest / playlist type to instantiate it.
  8923. if (!this._bwEstimator) {
  8924. var hls = this.hls,
  8925. level = data.frag.level,
  8926. isLive = hls.levels[level].details.live,
  8927. config = hls.config,
  8928. ewmaFast = void 0,
  8929. ewmaSlow = void 0;
  8930. if (isLive) {
  8931. ewmaFast = config.abrEwmaFastLive;
  8932. ewmaSlow = config.abrEwmaSlowLive;
  8933. } else {
  8934. ewmaFast = config.abrEwmaFastVoD;
  8935. ewmaSlow = config.abrEwmaSlowVoD;
  8936. }
  8937. this._bwEstimator = new ewma_bandwidth_estimator(hls, ewmaSlow, ewmaFast, config.abrEwmaDefaultEstimate);
  8938. }
  8939. this.fragCurrent = frag;
  8940. }
  8941. };
  8942. AbrController.prototype._abandonRulesCheck = function _abandonRulesCheck() {
  8943. /*
  8944. monitor fragment retrieval time...
  8945. we compute expected time of arrival of the complete fragment.
  8946. we compare it to expected time of buffer starvation
  8947. */
  8948. var hls = this.hls,
  8949. v = hls.media,
  8950. frag = this.fragCurrent,
  8951. loader = frag.loader,
  8952. minAutoLevel = hls.minAutoLevel;
  8953. // if loader has been destroyed or loading has been aborted, stop timer and return
  8954. if (!loader || loader.stats && loader.stats.aborted) {
  8955. logger["b" /* logger */].warn('frag loader destroy or aborted, disarm abandonRules');
  8956. this.clearTimer();
  8957. // reset forced auto level value so that next level will be selected
  8958. this._nextAutoLevel = -1;
  8959. return;
  8960. }
  8961. var stats = loader.stats;
  8962. /* only monitor frag retrieval time if
  8963. (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) */
  8964. if (v && stats && (!v.paused && v.playbackRate !== 0 || !v.readyState) && frag.autoLevel && frag.level) {
  8965. var requestDelay = performance.now() - stats.trequest,
  8966. playbackRate = Math.abs(v.playbackRate);
  8967. // monitor fragment load progress after half of expected fragment duration,to stabilize bitrate
  8968. if (requestDelay > 500 * frag.duration / playbackRate) {
  8969. var levels = hls.levels,
  8970. loadRate = Math.max(1, stats.bw ? stats.bw / 8 : stats.loaded * 1000 / requestDelay),
  8971. // byte/s; at least 1 byte/s to avoid division by zero
  8972. // compute expected fragment length using frag duration and level bitrate. also ensure that expected len is gte than already loaded size
  8973. level = levels[frag.level],
  8974. levelBitrate = level.realBitrate ? Math.max(level.realBitrate, level.bitrate) : level.bitrate,
  8975. expectedLen = stats.total ? stats.total : Math.max(stats.loaded, Math.round(frag.duration * levelBitrate / 8)),
  8976. pos = v.currentTime,
  8977. fragLoadedDelay = (expectedLen - stats.loaded) / loadRate,
  8978. bufferStarvationDelay = (buffer_helper.bufferInfo(v, pos, hls.config.maxBufferHole).end - pos) / playbackRate;
  8979. // consider emergency switch down only if we have less than 2 frag buffered AND
  8980. // time to finish loading current fragment is bigger than buffer starvation delay
  8981. // ie if we risk buffer starvation if bw does not increase quickly
  8982. if (bufferStarvationDelay < 2 * frag.duration / playbackRate && fragLoadedDelay > bufferStarvationDelay) {
  8983. var fragLevelNextLoadedDelay = void 0,
  8984. nextLoadLevel = void 0;
  8985. // lets iterate through lower level and try to find the biggest one that could avoid rebuffering
  8986. // we start from current level - 1 and we step down , until we find a matching level
  8987. for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
  8988. // compute time to load next fragment at lower level
  8989. // 0.8 : consider only 80% of current bw to be conservative
  8990. // 8 = bits per byte (bps/Bps)
  8991. var levelNextBitrate = levels[nextLoadLevel].realBitrate ? Math.max(levels[nextLoadLevel].realBitrate, levels[nextLoadLevel].bitrate) : levels[nextLoadLevel].bitrate;
  8992. fragLevelNextLoadedDelay = frag.duration * levelNextBitrate / (8 * 0.8 * loadRate);
  8993. if (fragLevelNextLoadedDelay < bufferStarvationDelay) {
  8994. // we found a lower level that be rebuffering free with current estimated bw !
  8995. break;
  8996. }
  8997. }
  8998. // only emergency switch down if it takes less time to load new fragment at lowest level instead
  8999. // of finishing loading current one ...
  9000. if (fragLevelNextLoadedDelay < fragLoadedDelay) {
  9001. logger["b" /* 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));
  9002. // force next load level in auto mode
  9003. hls.nextLoadLevel = nextLoadLevel;
  9004. // update bw estimate for this fragment before cancelling load (this will help reducing the bw)
  9005. this._bwEstimator.sample(requestDelay, stats.loaded);
  9006. //abort fragment loading
  9007. loader.abort();
  9008. // stop abandon rules timer
  9009. this.clearTimer();
  9010. hls.trigger(events["a" /* default */].FRAG_LOAD_EMERGENCY_ABORTED, { frag: frag, stats: stats });
  9011. }
  9012. }
  9013. }
  9014. }
  9015. };
  9016. AbrController.prototype.onFragLoaded = function onFragLoaded(data) {
  9017. var frag = data.frag;
  9018. if (frag.type === 'main' && !isNaN(frag.sn)) {
  9019. // stop monitoring bw once frag loaded
  9020. this.clearTimer();
  9021. // store level id after successful fragment load
  9022. this.lastLoadedFragLevel = frag.level;
  9023. // reset forced auto level value so that next level will be selected
  9024. this._nextAutoLevel = -1;
  9025. // compute level average bitrate
  9026. if (this.hls.config.abrMaxWithRealBitrate) {
  9027. var level = this.hls.levels[frag.level];
  9028. var loadedBytes = (level.loaded ? level.loaded.bytes : 0) + data.stats.loaded;
  9029. var loadedDuration = (level.loaded ? level.loaded.duration : 0) + data.frag.duration;
  9030. level.loaded = { bytes: loadedBytes, duration: loadedDuration };
  9031. level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
  9032. }
  9033. // if fragment has been loaded to perform a bitrate test,
  9034. if (data.frag.bitrateTest) {
  9035. var stats = data.stats;
  9036. stats.tparsed = stats.tbuffered = stats.tload;
  9037. this.onFragBuffered(data);
  9038. }
  9039. }
  9040. };
  9041. AbrController.prototype.onFragBuffered = function onFragBuffered(data) {
  9042. var stats = data.stats,
  9043. frag = data.frag;
  9044. // only update stats on first frag buffering
  9045. // if same frag is loaded multiple times, it might be in browser cache, and loaded quickly
  9046. // and leading to wrong bw estimation
  9047. // on bitrate test, also only update stats once (if tload = tbuffered == on FRAG_LOADED)
  9048. if (stats.aborted !== true && frag.loadCounter === 1 && frag.type === 'main' && !isNaN(frag.sn) && (!frag.bitrateTest || stats.tload === stats.tbuffered)) {
  9049. // use tparsed-trequest instead of tbuffered-trequest to compute fragLoadingProcessing; rationale is that buffer appending only happens once media is attached
  9050. // 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
  9051. // as a consequence it could happen really late in the process. meaning that appending duration might appears huge ... leading to underestimated throughput estimation
  9052. var fragLoadingProcessingMs = stats.tparsed - stats.trequest;
  9053. logger["b" /* 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)));
  9054. this._bwEstimator.sample(fragLoadingProcessingMs, stats.loaded);
  9055. stats.bwEstimate = this._bwEstimator.getEstimate();
  9056. // if fragment has been loaded to perform a bitrate test, (hls.startLevel = -1), store bitrate test delay duration
  9057. if (frag.bitrateTest) {
  9058. this.bitrateTestDelay = fragLoadingProcessingMs / 1000;
  9059. } else {
  9060. this.bitrateTestDelay = 0;
  9061. }
  9062. }
  9063. };
  9064. AbrController.prototype.onError = function onError(data) {
  9065. // stop timer in case of frag loading error
  9066. switch (data.details) {
  9067. case errors["a" /* ErrorDetails */].FRAG_LOAD_ERROR:
  9068. case errors["a" /* ErrorDetails */].FRAG_LOAD_TIMEOUT:
  9069. this.clearTimer();
  9070. break;
  9071. default:
  9072. break;
  9073. }
  9074. };
  9075. AbrController.prototype.clearTimer = function clearTimer() {
  9076. clearInterval(this.timer);
  9077. this.timer = null;
  9078. };
  9079. // return next auto level
  9080. AbrController.prototype._findBestLevel = function _findBestLevel(currentLevel, currentFragDuration, currentBw, minAutoLevel, maxAutoLevel, maxFetchDuration, bwFactor, bwUpFactor, levels) {
  9081. for (var i = maxAutoLevel; i >= minAutoLevel; i--) {
  9082. var levelInfo = levels[i],
  9083. levelDetails = levelInfo.details,
  9084. avgDuration = levelDetails ? levelDetails.totalduration / levelDetails.fragments.length : currentFragDuration,
  9085. live = levelDetails ? levelDetails.live : false,
  9086. adjustedbw = void 0;
  9087. // follow algorithm captured from stagefright :
  9088. // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
  9089. // Pick the highest bandwidth stream below or equal to estimated bandwidth.
  9090. // consider only 80% of the available bandwidth, but if we are switching up,
  9091. // be even more conservative (70%) to avoid overestimating and immediately
  9092. // switching back.
  9093. if (i <= currentLevel) {
  9094. adjustedbw = bwFactor * currentBw;
  9095. } else {
  9096. adjustedbw = bwUpFactor * currentBw;
  9097. }
  9098. var bitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate,
  9099. fetchDuration = bitrate * avgDuration / adjustedbw;
  9100. logger["b" /* logger */].trace('level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: ' + i + '/' + Math.round(adjustedbw) + '/' + bitrate + '/' + avgDuration + '/' + maxFetchDuration + '/' + fetchDuration);
  9101. // if adjusted bw is greater than level bitrate AND
  9102. if (adjustedbw > bitrate && (
  9103. // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
  9104. // 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 ...
  9105. // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that _findBestLevel will return -1
  9106. !fetchDuration || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration)) {
  9107. // as we are looping from highest to lowest, this will return the best achievable quality level
  9108. return i;
  9109. }
  9110. }
  9111. // not enough time budget even with quality level 0 ... rebuffering might happen
  9112. return -1;
  9113. };
  9114. abr_controller__createClass(AbrController, [{
  9115. key: 'nextAutoLevel',
  9116. get: function get() {
  9117. var forcedAutoLevel = this._nextAutoLevel;
  9118. var bwEstimator = this._bwEstimator;
  9119. // in case next auto level has been forced, and bw not available or not reliable, return forced value
  9120. if (forcedAutoLevel !== -1 && (!bwEstimator || !bwEstimator.canEstimate())) {
  9121. return forcedAutoLevel;
  9122. }
  9123. // compute next level using ABR logic
  9124. var nextABRAutoLevel = this._nextABRAutoLevel;
  9125. // if forced auto level has been defined, use it to cap ABR computed quality level
  9126. if (forcedAutoLevel !== -1) {
  9127. nextABRAutoLevel = Math.min(forcedAutoLevel, nextABRAutoLevel);
  9128. }
  9129. return nextABRAutoLevel;
  9130. },
  9131. set: function set(nextLevel) {
  9132. this._nextAutoLevel = nextLevel;
  9133. }
  9134. }, {
  9135. key: '_nextABRAutoLevel',
  9136. get: function get() {
  9137. var hls = this.hls,
  9138. maxAutoLevel = hls.maxAutoLevel,
  9139. levels = hls.levels,
  9140. config = hls.config,
  9141. minAutoLevel = hls.minAutoLevel;
  9142. var v = hls.media,
  9143. currentLevel = this.lastLoadedFragLevel,
  9144. currentFragDuration = this.fragCurrent ? this.fragCurrent.duration : 0,
  9145. pos = v ? v.currentTime : 0,
  9146. // playbackRate is the absolute value of the playback rate; if v.playbackRate is 0, we use 1 to load as
  9147. // if we're playing back at the normal rate.
  9148. playbackRate = v && v.playbackRate !== 0 ? Math.abs(v.playbackRate) : 1.0,
  9149. avgbw = this._bwEstimator ? this._bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate,
  9150. // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.
  9151. bufferStarvationDelay = (buffer_helper.bufferInfo(v, pos, config.maxBufferHole).end - pos) / playbackRate;
  9152. // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all
  9153. var bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, config.abrBandWidthFactor, config.abrBandWidthUpFactor, levels);
  9154. if (bestLevel >= 0) {
  9155. return bestLevel;
  9156. } else {
  9157. logger["b" /* logger */].trace('rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering');
  9158. // not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering
  9159. // if no matching level found, logic will return 0
  9160. var maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay,
  9161. bwFactor = config.abrBandWidthFactor,
  9162. bwUpFactor = config.abrBandWidthUpFactor;
  9163. if (bufferStarvationDelay === 0) {
  9164. // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test
  9165. var bitrateTestDelay = this.bitrateTestDelay;
  9166. if (bitrateTestDelay) {
  9167. // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value
  9168. // max video loading delay used in automatic start level selection :
  9169. // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +
  9170. // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )
  9171. // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration
  9172. var maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
  9173. maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
  9174. logger["b" /* logger */].trace('bitrate test took ' + Math.round(1000 * bitrateTestDelay) + 'ms, set first fragment max fetchDuration to ' + Math.round(1000 * maxStarvationDelay) + ' ms');
  9175. // don't use conservative factor on bitrate test
  9176. bwFactor = bwUpFactor = 1;
  9177. }
  9178. }
  9179. bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay + maxStarvationDelay, bwFactor, bwUpFactor, levels);
  9180. return Math.max(bestLevel, 0);
  9181. }
  9182. }
  9183. }]);
  9184. return AbrController;
  9185. }(event_handler);
  9186. /* harmony default export */ var abr_controller = (abr_controller_AbrController);
  9187. // CONCATENATED MODULE: ./src/controller/buffer-controller.js
  9188. function buffer_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9189. function buffer_controller__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; }
  9190. function buffer_controller__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; }
  9191. /*
  9192. * Buffer Controller
  9193. */
  9194. var buffer_controller_MediaSource = getMediaSource();
  9195. var buffer_controller_BufferController = function (_EventHandler) {
  9196. buffer_controller__inherits(BufferController, _EventHandler);
  9197. function BufferController(hls) {
  9198. buffer_controller__classCallCheck(this, BufferController);
  9199. // the value that we have set mediasource.duration to
  9200. // (the actual duration may be tweaked slighly by the browser)
  9201. var _this = buffer_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MEDIA_ATTACHING, events["a" /* default */].MEDIA_DETACHING, events["a" /* default */].MANIFEST_PARSED, events["a" /* default */].BUFFER_RESET, events["a" /* default */].BUFFER_APPENDING, events["a" /* default */].BUFFER_CODECS, events["a" /* default */].BUFFER_EOS, events["a" /* default */].BUFFER_FLUSHING, events["a" /* default */].LEVEL_PTS_UPDATED, events["a" /* default */].LEVEL_UPDATED));
  9202. _this._msDuration = null;
  9203. // the value that we want to set mediaSource.duration to
  9204. _this._levelDuration = null;
  9205. // current stream state: true - for live broadcast, false - for VoD content
  9206. _this._live = null;
  9207. // cache the self generated object url to detect hijack of video tag
  9208. _this._objectUrl = null;
  9209. // Source Buffer listeners
  9210. _this.onsbue = _this.onSBUpdateEnd.bind(_this);
  9211. _this.onsbe = _this.onSBUpdateError.bind(_this);
  9212. _this.pendingTracks = {};
  9213. _this.tracks = {};
  9214. return _this;
  9215. }
  9216. BufferController.prototype.destroy = function destroy() {
  9217. event_handler.prototype.destroy.call(this);
  9218. };
  9219. BufferController.prototype.onLevelPtsUpdated = function onLevelPtsUpdated(data) {
  9220. var type = data.type;
  9221. var audioTrack = this.tracks.audio;
  9222. // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)
  9223. // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`
  9224. // 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
  9225. // `SourceBuffer.abort()` and adjusting `SourceBuffer.timestampOffset` if `SourceBuffer.updating` is false or awaiting `updateend`
  9226. // event if SB is in updating state.
  9227. // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486
  9228. if (type === 'audio' && audioTrack && audioTrack.container === 'audio/mpeg') {
  9229. // Chrome audio mp3 track
  9230. var audioBuffer = this.sourceBuffer.audio;
  9231. var delta = Math.abs(audioBuffer.timestampOffset - data.start);
  9232. // adjust timestamp offset if time delta is greater than 100ms
  9233. if (delta > 0.1) {
  9234. var updating = audioBuffer.updating;
  9235. try {
  9236. audioBuffer.abort();
  9237. } catch (err) {
  9238. updating = true;
  9239. logger["b" /* logger */].warn('can not abort audio buffer: ' + err);
  9240. }
  9241. if (!updating) {
  9242. logger["b" /* logger */].warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + data.start);
  9243. audioBuffer.timestampOffset = data.start;
  9244. } else {
  9245. this.audioTimestampOffset = data.start;
  9246. }
  9247. }
  9248. }
  9249. };
  9250. BufferController.prototype.onManifestParsed = function onManifestParsed(data) {
  9251. var audioExpected = data.audio,
  9252. videoExpected = data.video || data.levels.length && data.audio,
  9253. sourceBufferNb = 0;
  9254. // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller
  9255. // sourcebuffers will be created all at once when the expected nb of tracks will be reached
  9256. // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller
  9257. // it will contain the expected nb of source buffers, no need to compute it
  9258. if (data.altAudio && (audioExpected || videoExpected)) {
  9259. sourceBufferNb = (audioExpected ? 1 : 0) + (videoExpected ? 1 : 0);
  9260. logger["b" /* logger */].log(sourceBufferNb + ' sourceBuffer(s) expected');
  9261. }
  9262. this.sourceBufferNb = sourceBufferNb;
  9263. };
  9264. BufferController.prototype.onMediaAttaching = function onMediaAttaching(data) {
  9265. var media = this.media = data.media;
  9266. if (media) {
  9267. // setup the media source
  9268. var ms = this.mediaSource = new buffer_controller_MediaSource();
  9269. //Media Source listeners
  9270. this.onmso = this.onMediaSourceOpen.bind(this);
  9271. this.onmse = this.onMediaSourceEnded.bind(this);
  9272. this.onmsc = this.onMediaSourceClose.bind(this);
  9273. ms.addEventListener('sourceopen', this.onmso);
  9274. ms.addEventListener('sourceended', this.onmse);
  9275. ms.addEventListener('sourceclose', this.onmsc);
  9276. // link video and media Source
  9277. media.src = URL.createObjectURL(ms);
  9278. // cache the locally generated object url
  9279. this._objectUrl = media.src;
  9280. }
  9281. };
  9282. BufferController.prototype.onMediaDetaching = function onMediaDetaching() {
  9283. logger["b" /* logger */].log('media source detaching');
  9284. var ms = this.mediaSource;
  9285. if (ms) {
  9286. if (ms.readyState === 'open') {
  9287. try {
  9288. // endOfStream could trigger exception if any sourcebuffer is in updating state
  9289. // we don't really care about checking sourcebuffer state here,
  9290. // as we are anyway detaching the MediaSource
  9291. // let's just avoid this exception to propagate
  9292. ms.endOfStream();
  9293. } catch (err) {
  9294. logger["b" /* logger */].warn('onMediaDetaching:' + err.message + ' while calling endOfStream');
  9295. }
  9296. }
  9297. ms.removeEventListener('sourceopen', this.onmso);
  9298. ms.removeEventListener('sourceended', this.onmse);
  9299. ms.removeEventListener('sourceclose', this.onmsc);
  9300. // Detach properly the MediaSource from the HTMLMediaElement as
  9301. // suggested in https://github.com/w3c/media-source/issues/53.
  9302. if (this.media) {
  9303. URL.revokeObjectURL(this._objectUrl);
  9304. // clean up video tag src only if it's our own url. some external libraries might
  9305. // hijack the video tag and change its 'src' without destroying the Hls instance first
  9306. if (this.media.src === this._objectUrl) {
  9307. this.media.removeAttribute('src');
  9308. this.media.load();
  9309. } else {
  9310. logger["b" /* logger */].warn('media.src was changed by a third party - skip cleanup');
  9311. }
  9312. }
  9313. this.mediaSource = null;
  9314. this.media = null;
  9315. this._objectUrl = null;
  9316. this.pendingTracks = {};
  9317. this.tracks = {};
  9318. this.sourceBuffer = {};
  9319. this.flushRange = [];
  9320. this.segments = [];
  9321. this.appended = 0;
  9322. }
  9323. this.onmso = this.onmse = this.onmsc = null;
  9324. this.hls.trigger(events["a" /* default */].MEDIA_DETACHED);
  9325. };
  9326. BufferController.prototype.onMediaSourceOpen = function onMediaSourceOpen() {
  9327. logger["b" /* logger */].log('media source opened');
  9328. this.hls.trigger(events["a" /* default */].MEDIA_ATTACHED, { media: this.media });
  9329. var mediaSource = this.mediaSource;
  9330. if (mediaSource) {
  9331. // once received, don't listen anymore to sourceopen event
  9332. mediaSource.removeEventListener('sourceopen', this.onmso);
  9333. }
  9334. this.checkPendingTracks();
  9335. };
  9336. BufferController.prototype.checkPendingTracks = function checkPendingTracks() {
  9337. // if any buffer codecs pending, check if we have enough to create sourceBuffers
  9338. var pendingTracks = this.pendingTracks,
  9339. pendingTracksNb = Object.keys(pendingTracks).length;
  9340. // if any pending tracks and (if nb of pending tracks gt or equal than expected nb or if unknown expected nb)
  9341. if (pendingTracksNb && (this.sourceBufferNb <= pendingTracksNb || this.sourceBufferNb === 0)) {
  9342. // ok, let's create them now !
  9343. this.createSourceBuffers(pendingTracks);
  9344. this.pendingTracks = {};
  9345. // append any pending segments now !
  9346. this.doAppending();
  9347. }
  9348. };
  9349. BufferController.prototype.onMediaSourceClose = function onMediaSourceClose() {
  9350. logger["b" /* logger */].log('media source closed');
  9351. };
  9352. BufferController.prototype.onMediaSourceEnded = function onMediaSourceEnded() {
  9353. logger["b" /* logger */].log('media source ended');
  9354. };
  9355. BufferController.prototype.onSBUpdateEnd = function onSBUpdateEnd() {
  9356. // update timestampOffset
  9357. if (this.audioTimestampOffset) {
  9358. var audioBuffer = this.sourceBuffer.audio;
  9359. logger["b" /* logger */].warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + this.audioTimestampOffset);
  9360. audioBuffer.timestampOffset = this.audioTimestampOffset;
  9361. delete this.audioTimestampOffset;
  9362. }
  9363. if (this._needsFlush) {
  9364. this.doFlush();
  9365. }
  9366. if (this._needsEos) {
  9367. this.checkEos();
  9368. }
  9369. this.appending = false;
  9370. var parent = this.parent;
  9371. // count nb of pending segments waiting for appending on this sourcebuffer
  9372. var pending = this.segments.reduce(function (counter, segment) {
  9373. return segment.parent === parent ? counter + 1 : counter;
  9374. }, 0);
  9375. this.hls.trigger(events["a" /* default */].BUFFER_APPENDED, { parent: parent, pending: pending });
  9376. // don't append in flushing mode
  9377. if (!this._needsFlush) {
  9378. this.doAppending();
  9379. }
  9380. this.updateMediaElementDuration();
  9381. };
  9382. BufferController.prototype.onSBUpdateError = function onSBUpdateError(event) {
  9383. logger["b" /* logger */].error('sourceBuffer error:', event);
  9384. // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
  9385. // this error might not always be fatal (it is fatal if decode error is set, in that case
  9386. // it will be followed by a mediaElement error ...)
  9387. this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_APPENDING_ERROR, fatal: false });
  9388. // we don't need to do more than that, as accordin to the spec, updateend will be fired just after
  9389. };
  9390. BufferController.prototype.onBufferReset = function onBufferReset() {
  9391. var sourceBuffer = this.sourceBuffer;
  9392. for (var type in sourceBuffer) {
  9393. var sb = sourceBuffer[type];
  9394. try {
  9395. this.mediaSource.removeSourceBuffer(sb);
  9396. sb.removeEventListener('updateend', this.onsbue);
  9397. sb.removeEventListener('error', this.onsbe);
  9398. } catch (err) {}
  9399. }
  9400. this.sourceBuffer = {};
  9401. this.flushRange = [];
  9402. this.segments = [];
  9403. this.appended = 0;
  9404. };
  9405. BufferController.prototype.onBufferCodecs = function onBufferCodecs(tracks) {
  9406. // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks
  9407. // if sourcebuffers already created, do nothing ...
  9408. if (Object.keys(this.sourceBuffer).length === 0) {
  9409. for (var trackName in tracks) {
  9410. this.pendingTracks[trackName] = tracks[trackName];
  9411. }
  9412. var mediaSource = this.mediaSource;
  9413. if (mediaSource && mediaSource.readyState === 'open') {
  9414. // try to create sourcebuffers if mediasource opened
  9415. this.checkPendingTracks();
  9416. }
  9417. }
  9418. };
  9419. BufferController.prototype.createSourceBuffers = function createSourceBuffers(tracks) {
  9420. var sourceBuffer = this.sourceBuffer,
  9421. mediaSource = this.mediaSource;
  9422. for (var trackName in tracks) {
  9423. if (!sourceBuffer[trackName]) {
  9424. var track = tracks[trackName];
  9425. // use levelCodec as first priority
  9426. var codec = track.levelCodec || track.codec;
  9427. var mimeType = track.container + ';codecs=' + codec;
  9428. logger["b" /* logger */].log('creating sourceBuffer(' + mimeType + ')');
  9429. try {
  9430. var sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);
  9431. sb.addEventListener('updateend', this.onsbue);
  9432. sb.addEventListener('error', this.onsbe);
  9433. this.tracks[trackName] = { codec: codec, container: track.container };
  9434. track.buffer = sb;
  9435. } catch (err) {
  9436. logger["b" /* logger */].error('error while trying to add sourceBuffer:' + err.message);
  9437. this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_ADD_CODEC_ERROR, fatal: false, err: err, mimeType: mimeType });
  9438. }
  9439. }
  9440. }
  9441. this.hls.trigger(events["a" /* default */].BUFFER_CREATED, { tracks: tracks });
  9442. };
  9443. BufferController.prototype.onBufferAppending = function onBufferAppending(data) {
  9444. if (!this._needsFlush) {
  9445. if (!this.segments) {
  9446. this.segments = [data];
  9447. } else {
  9448. this.segments.push(data);
  9449. }
  9450. this.doAppending();
  9451. }
  9452. };
  9453. BufferController.prototype.onBufferAppendFail = function onBufferAppendFail(data) {
  9454. logger["b" /* logger */].error('sourceBuffer error:', data.event);
  9455. // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
  9456. // this error might not always be fatal (it is fatal if decode error is set, in that case
  9457. // it will be followed by a mediaElement error ...)
  9458. this.hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].BUFFER_APPENDING_ERROR, fatal: false });
  9459. };
  9460. // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()
  9461. BufferController.prototype.onBufferEos = function onBufferEos(data) {
  9462. var sb = this.sourceBuffer;
  9463. var dataType = data.type;
  9464. for (var type in sb) {
  9465. if (!dataType || type === dataType) {
  9466. if (!sb[type].ended) {
  9467. sb[type].ended = true;
  9468. logger["b" /* logger */].log(type + ' sourceBuffer now EOS');
  9469. }
  9470. }
  9471. }
  9472. this.checkEos();
  9473. };
  9474. // if all source buffers are marked as ended, signal endOfStream() to MediaSource.
  9475. BufferController.prototype.checkEos = function checkEos() {
  9476. var sb = this.sourceBuffer,
  9477. mediaSource = this.mediaSource;
  9478. if (!mediaSource || mediaSource.readyState !== 'open') {
  9479. this._needsEos = false;
  9480. return;
  9481. }
  9482. for (var type in sb) {
  9483. var sbobj = sb[type];
  9484. if (!sbobj.ended) {
  9485. return;
  9486. }
  9487. if (sbobj.updating) {
  9488. this._needsEos = true;
  9489. return;
  9490. }
  9491. }
  9492. logger["b" /* logger */].log('all media data available, signal endOfStream() to MediaSource and stop loading fragment');
  9493. //Notify the media element that it now has all of the media data
  9494. try {
  9495. mediaSource.endOfStream();
  9496. } catch (e) {
  9497. logger["b" /* logger */].warn('exception while calling mediaSource.endOfStream()');
  9498. }
  9499. this._needsEos = false;
  9500. };
  9501. BufferController.prototype.onBufferFlushing = function onBufferFlushing(data) {
  9502. this.flushRange.push({ start: data.startOffset, end: data.endOffset, type: data.type });
  9503. // attempt flush immediately
  9504. this.flushBufferCounter = 0;
  9505. this.doFlush();
  9506. };
  9507. BufferController.prototype.onLevelUpdated = function onLevelUpdated(_ref) {
  9508. var details = _ref.details;
  9509. if (details.fragments.length > 0) {
  9510. this._levelDuration = details.totalduration + details.fragments[0].start;
  9511. this._live = details.live;
  9512. this.updateMediaElementDuration();
  9513. }
  9514. };
  9515. /**
  9516. * Update Media Source duration to current level duration or override to Infinity if configuration parameter
  9517. * 'liveDurationInfinity` is set to `true`
  9518. * More details: https://github.com/video-dev/hls.js/issues/355
  9519. */
  9520. BufferController.prototype.updateMediaElementDuration = function updateMediaElementDuration() {
  9521. var config = this.hls.config;
  9522. var duration = void 0;
  9523. if (this._levelDuration === null || !this.media || !this.mediaSource || !this.sourceBuffer || this.media.readyState === 0 || this.mediaSource.readyState !== 'open') {
  9524. return;
  9525. }
  9526. for (var type in this.sourceBuffer) {
  9527. if (this.sourceBuffer[type].updating === true) {
  9528. // can't set duration whilst a buffer is updating
  9529. return;
  9530. }
  9531. }
  9532. duration = this.media.duration;
  9533. // initialise to the value that the media source is reporting
  9534. if (this._msDuration === null) {
  9535. this._msDuration = this.mediaSource.duration;
  9536. }
  9537. if (this._live === true && config.liveDurationInfinity === true) {
  9538. // Override duration to Infinity
  9539. logger["b" /* logger */].log('Media Source duration is set to Infinity');
  9540. this._msDuration = this.mediaSource.duration = Infinity;
  9541. } else if (this._levelDuration > this._msDuration && this._levelDuration > duration || duration === Infinity || isNaN(duration)) {
  9542. // levelDuration was the last value we set.
  9543. // not using mediaSource.duration as the browser may tweak this value
  9544. // only update Media Source duration if its value increase, this is to avoid
  9545. // flushing already buffered portion when switching between quality level
  9546. logger["b" /* logger */].log('Updating Media Source duration to ' + this._levelDuration.toFixed(3));
  9547. this._msDuration = this.mediaSource.duration = this._levelDuration;
  9548. }
  9549. };
  9550. BufferController.prototype.doFlush = function doFlush() {
  9551. // loop through all buffer ranges to flush
  9552. while (this.flushRange.length) {
  9553. var range = this.flushRange[0];
  9554. // flushBuffer will abort any buffer append in progress and flush Audio/Video Buffer
  9555. if (this.flushBuffer(range.start, range.end, range.type)) {
  9556. // range flushed, remove from flush array
  9557. this.flushRange.shift();
  9558. this.flushBufferCounter = 0;
  9559. } else {
  9560. this._needsFlush = true;
  9561. // avoid looping, wait for SB update end to retrigger a flush
  9562. return;
  9563. }
  9564. }
  9565. if (this.flushRange.length === 0) {
  9566. // everything flushed
  9567. this._needsFlush = false;
  9568. // let's recompute this.appended, which is used to avoid flush looping
  9569. var appended = 0;
  9570. var sourceBuffer = this.sourceBuffer;
  9571. try {
  9572. for (var type in sourceBuffer) {
  9573. appended += sourceBuffer[type].buffered.length;
  9574. }
  9575. } catch (error) {
  9576. // error could be thrown while accessing buffered, in case sourcebuffer has already been removed from MediaSource
  9577. // this is harmess at this stage, catch this to avoid reporting an internal exception
  9578. logger["b" /* logger */].error('error while accessing sourceBuffer.buffered');
  9579. }
  9580. this.appended = appended;
  9581. this.hls.trigger(events["a" /* default */].BUFFER_FLUSHED);
  9582. }
  9583. };
  9584. BufferController.prototype.doAppending = function doAppending() {
  9585. var hls = this.hls,
  9586. sourceBuffer = this.sourceBuffer,
  9587. segments = this.segments;
  9588. if (Object.keys(sourceBuffer).length) {
  9589. if (this.media.error) {
  9590. this.segments = [];
  9591. logger["b" /* logger */].error('trying to append although a media error occured, flush segment and abort');
  9592. return;
  9593. }
  9594. if (this.appending) {
  9595. //logger.log(`sb appending in progress`);
  9596. return;
  9597. }
  9598. if (segments && segments.length) {
  9599. var segment = segments.shift();
  9600. try {
  9601. var type = segment.type,
  9602. sb = sourceBuffer[type];
  9603. if (sb) {
  9604. if (!sb.updating) {
  9605. // reset sourceBuffer ended flag before appending segment
  9606. sb.ended = false;
  9607. //logger.log(`appending ${segment.content} ${type} SB, size:${segment.data.length}, ${segment.parent}`);
  9608. this.parent = segment.parent;
  9609. sb.appendBuffer(segment.data);
  9610. this.appendError = 0;
  9611. this.appended++;
  9612. this.appending = true;
  9613. } else {
  9614. segments.unshift(segment);
  9615. }
  9616. } else {
  9617. // in case we don't have any source buffer matching with this segment type,
  9618. // it means that Mediasource fails to create sourcebuffer
  9619. // discard this segment, and trigger update end
  9620. this.onSBUpdateEnd();
  9621. }
  9622. } catch (err) {
  9623. // in case any error occured while appending, put back segment in segments table
  9624. logger["b" /* logger */].error('error while trying to append buffer:' + err.message);
  9625. segments.unshift(segment);
  9626. var event = { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, parent: segment.parent };
  9627. if (err.code !== 22) {
  9628. if (this.appendError) {
  9629. this.appendError++;
  9630. } else {
  9631. this.appendError = 1;
  9632. }
  9633. event.details = errors["a" /* ErrorDetails */].BUFFER_APPEND_ERROR;
  9634. /* with UHD content, we could get loop of quota exceeded error until
  9635. browser is able to evict some data from sourcebuffer. retrying help recovering this
  9636. */
  9637. if (this.appendError > hls.config.appendErrorMaxRetry) {
  9638. logger["b" /* logger */].log('fail ' + hls.config.appendErrorMaxRetry + ' times to append segment in sourceBuffer');
  9639. segments = [];
  9640. event.fatal = true;
  9641. hls.trigger(events["a" /* default */].ERROR, event);
  9642. return;
  9643. } else {
  9644. event.fatal = false;
  9645. hls.trigger(events["a" /* default */].ERROR, event);
  9646. }
  9647. } else {
  9648. // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
  9649. // let's stop appending any segments, and report BUFFER_FULL_ERROR error
  9650. this.segments = [];
  9651. event.details = errors["a" /* ErrorDetails */].BUFFER_FULL_ERROR;
  9652. event.fatal = false;
  9653. hls.trigger(events["a" /* default */].ERROR, event);
  9654. return;
  9655. }
  9656. }
  9657. }
  9658. }
  9659. };
  9660. /*
  9661. flush specified buffered range,
  9662. return true once range has been flushed.
  9663. as sourceBuffer.remove() is asynchronous, flushBuffer will be retriggered on sourceBuffer update end
  9664. */
  9665. BufferController.prototype.flushBuffer = function flushBuffer(startOffset, endOffset, typeIn) {
  9666. var sb,
  9667. i,
  9668. bufStart,
  9669. bufEnd,
  9670. flushStart,
  9671. flushEnd,
  9672. sourceBuffer = this.sourceBuffer;
  9673. if (Object.keys(sourceBuffer).length) {
  9674. logger["b" /* logger */].log('flushBuffer,pos/start/end: ' + this.media.currentTime.toFixed(3) + '/' + startOffset + '/' + endOffset);
  9675. // safeguard to avoid infinite looping : don't try to flush more than the nb of appended segments
  9676. if (this.flushBufferCounter < this.appended) {
  9677. for (var type in sourceBuffer) {
  9678. // check if sourcebuffer type is defined (typeIn): if yes, let's only flush this one
  9679. // if no, let's flush all sourcebuffers
  9680. if (typeIn && type !== typeIn) {
  9681. continue;
  9682. }
  9683. sb = sourceBuffer[type];
  9684. // we are going to flush buffer, mark source buffer as 'not ended'
  9685. sb.ended = false;
  9686. if (!sb.updating) {
  9687. try {
  9688. for (i = 0; i < sb.buffered.length; i++) {
  9689. bufStart = sb.buffered.start(i);
  9690. bufEnd = sb.buffered.end(i);
  9691. // workaround firefox not able to properly flush multiple buffered range.
  9692. if (navigator.userAgent.toLowerCase().indexOf('firefox') !== -1 && endOffset === Number.POSITIVE_INFINITY) {
  9693. flushStart = startOffset;
  9694. flushEnd = endOffset;
  9695. } else {
  9696. flushStart = Math.max(bufStart, startOffset);
  9697. flushEnd = Math.min(bufEnd, endOffset);
  9698. }
  9699. /* sometimes sourcebuffer.remove() does not flush
  9700. the exact expected time range.
  9701. to avoid rounding issues/infinite loop,
  9702. only flush buffer range of length greater than 500ms.
  9703. */
  9704. if (Math.min(flushEnd, bufEnd) - flushStart > 0.5) {
  9705. this.flushBufferCounter++;
  9706. logger["b" /* logger */].log('flush ' + type + ' [' + flushStart + ',' + flushEnd + '], of [' + bufStart + ',' + bufEnd + '], pos:' + this.media.currentTime);
  9707. sb.remove(flushStart, flushEnd);
  9708. return false;
  9709. }
  9710. }
  9711. } catch (e) {
  9712. logger["b" /* logger */].warn('exception while accessing sourcebuffer, it might have been removed from MediaSource');
  9713. }
  9714. } else {
  9715. //logger.log('abort ' + type + ' append in progress');
  9716. // this will abort any appending in progress
  9717. //sb.abort();
  9718. logger["b" /* logger */].warn('cannot flush, sb updating in progress');
  9719. return false;
  9720. }
  9721. }
  9722. } else {
  9723. logger["b" /* logger */].warn('abort flushing too many retries');
  9724. }
  9725. logger["b" /* logger */].log('buffer flushed');
  9726. }
  9727. // everything flushed !
  9728. return true;
  9729. };
  9730. return BufferController;
  9731. }(event_handler);
  9732. /* harmony default export */ var buffer_controller = (buffer_controller_BufferController);
  9733. // CONCATENATED MODULE: ./src/controller/cap-level-controller.js
  9734. var cap_level_controller__createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  9735. function cap_level_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9736. function cap_level_controller__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; }
  9737. function cap_level_controller__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; }
  9738. /*
  9739. * cap stream level to media size dimension controller
  9740. */
  9741. var cap_level_controller_CapLevelController = function (_EventHandler) {
  9742. cap_level_controller__inherits(CapLevelController, _EventHandler);
  9743. function CapLevelController(hls) {
  9744. cap_level_controller__classCallCheck(this, CapLevelController);
  9745. return cap_level_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].FPS_DROP_LEVEL_CAPPING, events["a" /* default */].MEDIA_ATTACHING, events["a" /* default */].MANIFEST_PARSED));
  9746. }
  9747. CapLevelController.prototype.destroy = function destroy() {
  9748. if (this.hls.config.capLevelToPlayerSize) {
  9749. this.media = this.restrictedLevels = null;
  9750. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  9751. if (this.timer) {
  9752. this.timer = clearInterval(this.timer);
  9753. }
  9754. }
  9755. };
  9756. CapLevelController.prototype.onFpsDropLevelCapping = function onFpsDropLevelCapping(data) {
  9757. // Don't add a restricted level more than once
  9758. if (CapLevelController.isLevelAllowed(data.droppedLevel, this.restrictedLevels)) {
  9759. this.restrictedLevels.push(data.droppedLevel);
  9760. }
  9761. };
  9762. CapLevelController.prototype.onMediaAttaching = function onMediaAttaching(data) {
  9763. this.media = data.media instanceof HTMLVideoElement ? data.media : null;
  9764. };
  9765. CapLevelController.prototype.onManifestParsed = function onManifestParsed(data) {
  9766. var hls = this.hls;
  9767. this.restrictedLevels = [];
  9768. if (hls.config.capLevelToPlayerSize) {
  9769. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  9770. this.levels = data.levels;
  9771. hls.firstLevel = this.getMaxLevel(data.firstLevel);
  9772. clearInterval(this.timer);
  9773. this.timer = setInterval(this.detectPlayerSize.bind(this), 1000);
  9774. this.detectPlayerSize();
  9775. }
  9776. };
  9777. CapLevelController.prototype.detectPlayerSize = function detectPlayerSize() {
  9778. if (this.media) {
  9779. var levelsLength = this.levels ? this.levels.length : 0;
  9780. if (levelsLength) {
  9781. var hls = this.hls;
  9782. hls.autoLevelCapping = this.getMaxLevel(levelsLength - 1);
  9783. if (hls.autoLevelCapping > this.autoLevelCapping) {
  9784. // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch
  9785. // usually happen when the user go to the fullscreen mode.
  9786. hls.streamController.nextLevelSwitch();
  9787. }
  9788. this.autoLevelCapping = hls.autoLevelCapping;
  9789. }
  9790. }
  9791. };
  9792. /*
  9793. * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
  9794. */
  9795. CapLevelController.prototype.getMaxLevel = function getMaxLevel(capLevelIndex) {
  9796. var _this2 = this;
  9797. if (!this.levels) {
  9798. return -1;
  9799. }
  9800. var validLevels = this.levels.filter(function (level, index) {
  9801. return CapLevelController.isLevelAllowed(index, _this2.restrictedLevels) && index <= capLevelIndex;
  9802. });
  9803. return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
  9804. };
  9805. CapLevelController.isLevelAllowed = function isLevelAllowed(level) {
  9806. var restrictedLevels = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  9807. return restrictedLevels.indexOf(level) === -1;
  9808. };
  9809. CapLevelController.getMaxLevelByMediaSize = function getMaxLevelByMediaSize(levels, width, height) {
  9810. if (!levels || levels && !levels.length) {
  9811. return -1;
  9812. }
  9813. // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next
  9814. // to determine whether we've chosen the greatest bandwidth for the media's dimensions
  9815. var atGreatestBandiwdth = function atGreatestBandiwdth(curLevel, nextLevel) {
  9816. if (!nextLevel) {
  9817. return true;
  9818. }
  9819. return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
  9820. };
  9821. // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to
  9822. // the max level
  9823. var maxLevelIndex = levels.length - 1;
  9824. for (var i = 0; i < levels.length; i += 1) {
  9825. var level = levels[i];
  9826. if ((level.width >= width || level.height >= height) && atGreatestBandiwdth(level, levels[i + 1])) {
  9827. maxLevelIndex = i;
  9828. break;
  9829. }
  9830. }
  9831. return maxLevelIndex;
  9832. };
  9833. cap_level_controller__createClass(CapLevelController, [{
  9834. key: 'mediaWidth',
  9835. get: function get() {
  9836. var width = void 0;
  9837. var media = this.media;
  9838. if (media) {
  9839. width = media.width || media.clientWidth || media.offsetWidth;
  9840. width *= CapLevelController.contentScaleFactor;
  9841. }
  9842. return width;
  9843. }
  9844. }, {
  9845. key: 'mediaHeight',
  9846. get: function get() {
  9847. var height = void 0;
  9848. var media = this.media;
  9849. if (media) {
  9850. height = media.height || media.clientHeight || media.offsetHeight;
  9851. height *= CapLevelController.contentScaleFactor;
  9852. }
  9853. return height;
  9854. }
  9855. }], [{
  9856. key: 'contentScaleFactor',
  9857. get: function get() {
  9858. var pixelRatio = 1;
  9859. try {
  9860. pixelRatio = window.devicePixelRatio;
  9861. } catch (e) {}
  9862. return pixelRatio;
  9863. }
  9864. }]);
  9865. return CapLevelController;
  9866. }(event_handler);
  9867. /* harmony default export */ var cap_level_controller = (cap_level_controller_CapLevelController);
  9868. // CONCATENATED MODULE: ./src/controller/fps-controller.js
  9869. function fps_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9870. function fps_controller__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; }
  9871. function fps_controller__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; }
  9872. /*
  9873. * FPS Controller
  9874. */
  9875. var fps_controller_FPSController = function (_EventHandler) {
  9876. fps_controller__inherits(FPSController, _EventHandler);
  9877. function FPSController(hls) {
  9878. fps_controller__classCallCheck(this, FPSController);
  9879. return fps_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MEDIA_ATTACHING));
  9880. }
  9881. FPSController.prototype.destroy = function destroy() {
  9882. if (this.timer) {
  9883. clearInterval(this.timer);
  9884. }
  9885. this.isVideoPlaybackQualityAvailable = false;
  9886. };
  9887. FPSController.prototype.onMediaAttaching = function onMediaAttaching(data) {
  9888. var config = this.hls.config;
  9889. if (config.capLevelOnFPSDrop) {
  9890. var video = this.video = data.media instanceof HTMLVideoElement ? data.media : null;
  9891. if (typeof video.getVideoPlaybackQuality === 'function') {
  9892. this.isVideoPlaybackQualityAvailable = true;
  9893. }
  9894. clearInterval(this.timer);
  9895. this.timer = setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
  9896. }
  9897. };
  9898. FPSController.prototype.checkFPS = function checkFPS(video, decodedFrames, droppedFrames) {
  9899. var currentTime = performance.now();
  9900. if (decodedFrames) {
  9901. if (this.lastTime) {
  9902. var currentPeriod = currentTime - this.lastTime,
  9903. currentDropped = droppedFrames - this.lastDroppedFrames,
  9904. currentDecoded = decodedFrames - this.lastDecodedFrames,
  9905. droppedFPS = 1000 * currentDropped / currentPeriod,
  9906. hls = this.hls;
  9907. hls.trigger(events["a" /* default */].FPS_DROP, { currentDropped: currentDropped, currentDecoded: currentDecoded, totalDroppedFrames: droppedFrames });
  9908. if (droppedFPS > 0) {
  9909. //logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));
  9910. if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
  9911. var currentLevel = hls.currentLevel;
  9912. logger["b" /* logger */].warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);
  9913. if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
  9914. currentLevel = currentLevel - 1;
  9915. hls.trigger(events["a" /* default */].FPS_DROP_LEVEL_CAPPING, { level: currentLevel, droppedLevel: hls.currentLevel });
  9916. hls.autoLevelCapping = currentLevel;
  9917. hls.streamController.nextLevelSwitch();
  9918. }
  9919. }
  9920. }
  9921. }
  9922. this.lastTime = currentTime;
  9923. this.lastDroppedFrames = droppedFrames;
  9924. this.lastDecodedFrames = decodedFrames;
  9925. }
  9926. };
  9927. FPSController.prototype.checkFPSInterval = function checkFPSInterval() {
  9928. var video = this.video;
  9929. if (video) {
  9930. if (this.isVideoPlaybackQualityAvailable) {
  9931. var videoPlaybackQuality = video.getVideoPlaybackQuality();
  9932. this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
  9933. } else {
  9934. this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
  9935. }
  9936. }
  9937. };
  9938. return FPSController;
  9939. }(event_handler);
  9940. /* harmony default export */ var fps_controller = (fps_controller_FPSController);
  9941. // CONCATENATED MODULE: ./src/utils/xhr-loader.js
  9942. function xhr_loader__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9943. /**
  9944. * XHR based logger
  9945. */
  9946. var xhr_loader_XhrLoader = function () {
  9947. function XhrLoader(config) {
  9948. xhr_loader__classCallCheck(this, XhrLoader);
  9949. if (config && config.xhrSetup) {
  9950. this.xhrSetup = config.xhrSetup;
  9951. }
  9952. }
  9953. XhrLoader.prototype.destroy = function destroy() {
  9954. this.abort();
  9955. this.loader = null;
  9956. };
  9957. XhrLoader.prototype.abort = function abort() {
  9958. var loader = this.loader;
  9959. if (loader && loader.readyState !== 4) {
  9960. this.stats.aborted = true;
  9961. loader.abort();
  9962. }
  9963. window.clearTimeout(this.requestTimeout);
  9964. this.requestTimeout = null;
  9965. window.clearTimeout(this.retryTimeout);
  9966. this.retryTimeout = null;
  9967. };
  9968. XhrLoader.prototype.load = function load(context, config, callbacks) {
  9969. this.context = context;
  9970. this.config = config;
  9971. this.callbacks = callbacks;
  9972. this.stats = { trequest: performance.now(), retry: 0 };
  9973. this.retryDelay = config.retryDelay;
  9974. this.loadInternal();
  9975. };
  9976. XhrLoader.prototype.loadInternal = function loadInternal() {
  9977. var xhr,
  9978. context = this.context;
  9979. xhr = this.loader = new XMLHttpRequest();
  9980. var stats = this.stats;
  9981. stats.tfirst = 0;
  9982. stats.loaded = 0;
  9983. var xhrSetup = this.xhrSetup;
  9984. try {
  9985. if (xhrSetup) {
  9986. try {
  9987. xhrSetup(xhr, context.url);
  9988. } catch (e) {
  9989. // fix xhrSetup: (xhr, url) => {xhr.setRequestHeader("Content-Language", "test");}
  9990. // not working, as xhr.setRequestHeader expects xhr.readyState === OPEN
  9991. xhr.open('GET', context.url, true);
  9992. xhrSetup(xhr, context.url);
  9993. }
  9994. }
  9995. if (!xhr.readyState) {
  9996. xhr.open('GET', context.url, true);
  9997. }
  9998. } catch (e) {
  9999. // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
  10000. this.callbacks.onError({ code: xhr.status, text: e.message }, context, xhr);
  10001. return;
  10002. }
  10003. if (context.rangeEnd) {
  10004. xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));
  10005. }
  10006. xhr.onreadystatechange = this.readystatechange.bind(this);
  10007. xhr.onprogress = this.loadprogress.bind(this);
  10008. xhr.responseType = context.responseType;
  10009. // setup timeout before we perform request
  10010. this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), this.config.timeout);
  10011. xhr.send();
  10012. };
  10013. XhrLoader.prototype.readystatechange = function readystatechange(event) {
  10014. var xhr = event.currentTarget,
  10015. readyState = xhr.readyState,
  10016. stats = this.stats,
  10017. context = this.context,
  10018. config = this.config;
  10019. // don't proceed if xhr has been aborted
  10020. if (stats.aborted) {
  10021. return;
  10022. }
  10023. // >= HEADERS_RECEIVED
  10024. if (readyState >= 2) {
  10025. // clear xhr timeout and rearm it if readyState less than 4
  10026. window.clearTimeout(this.requestTimeout);
  10027. if (stats.tfirst === 0) {
  10028. stats.tfirst = Math.max(performance.now(), stats.trequest);
  10029. }
  10030. if (readyState === 4) {
  10031. var status = xhr.status;
  10032. // http status between 200 to 299 are all successful
  10033. if (status >= 200 && status < 300) {
  10034. stats.tload = Math.max(stats.tfirst, performance.now());
  10035. var data = void 0,
  10036. len = void 0;
  10037. if (context.responseType === 'arraybuffer') {
  10038. data = xhr.response;
  10039. len = data.byteLength;
  10040. } else {
  10041. data = xhr.responseText;
  10042. len = data.length;
  10043. }
  10044. stats.loaded = stats.total = len;
  10045. var response = { url: xhr.responseURL, data: data };
  10046. this.callbacks.onSuccess(response, stats, context, xhr);
  10047. } else {
  10048. // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error
  10049. if (stats.retry >= config.maxRetry || status >= 400 && status < 499) {
  10050. logger["b" /* logger */].error(status + ' while loading ' + context.url);
  10051. this.callbacks.onError({ code: status, text: xhr.statusText }, context, xhr);
  10052. } else {
  10053. // retry
  10054. logger["b" /* logger */].warn(status + ' while loading ' + context.url + ', retrying in ' + this.retryDelay + '...');
  10055. // aborts and resets internal state
  10056. this.destroy();
  10057. // schedule retry
  10058. this.retryTimeout = window.setTimeout(this.loadInternal.bind(this), this.retryDelay);
  10059. // set exponential backoff
  10060. this.retryDelay = Math.min(2 * this.retryDelay, config.maxRetryDelay);
  10061. stats.retry++;
  10062. }
  10063. }
  10064. } else {
  10065. // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet
  10066. this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), config.timeout);
  10067. }
  10068. }
  10069. };
  10070. XhrLoader.prototype.loadtimeout = function loadtimeout() {
  10071. logger["b" /* logger */].warn('timeout while loading ' + this.context.url);
  10072. this.callbacks.onTimeout(this.stats, this.context, null);
  10073. };
  10074. XhrLoader.prototype.loadprogress = function loadprogress(event) {
  10075. var xhr = event.currentTarget,
  10076. stats = this.stats;
  10077. stats.loaded = event.loaded;
  10078. if (event.lengthComputable) {
  10079. stats.total = event.total;
  10080. }
  10081. var onProgress = this.callbacks.onProgress;
  10082. if (onProgress) {
  10083. // third arg is to provide on progress data
  10084. onProgress(stats, this.context, null, xhr);
  10085. }
  10086. };
  10087. return XhrLoader;
  10088. }();
  10089. /* harmony default export */ var xhr_loader = (xhr_loader_XhrLoader);
  10090. // CONCATENATED MODULE: ./src/controller/audio-track-controller.js
  10091. var audio_track_controller__createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  10092. function audio_track_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  10093. function audio_track_controller__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; }
  10094. function audio_track_controller__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; }
  10095. /*
  10096. * audio track controller
  10097. */
  10098. var audio_track_controller_AudioTrackController = function (_EventHandler) {
  10099. audio_track_controller__inherits(AudioTrackController, _EventHandler);
  10100. function AudioTrackController(hls) {
  10101. audio_track_controller__classCallCheck(this, AudioTrackController);
  10102. var _this = audio_track_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MANIFEST_LOADING, events["a" /* default */].MANIFEST_PARSED, events["a" /* default */].AUDIO_TRACK_LOADED, events["a" /* default */].ERROR));
  10103. _this.ticks = 0;
  10104. _this.ontick = _this.tick.bind(_this);
  10105. return _this;
  10106. }
  10107. AudioTrackController.prototype.destroy = function destroy() {
  10108. this.cleanTimer();
  10109. event_handler.prototype.destroy.call(this);
  10110. };
  10111. AudioTrackController.prototype.cleanTimer = function cleanTimer() {
  10112. if (this.timer) {
  10113. clearTimeout(this.timer);
  10114. this.timer = null;
  10115. }
  10116. };
  10117. AudioTrackController.prototype.tick = function tick() {
  10118. this.ticks++;
  10119. if (this.ticks === 1) {
  10120. this.doTick();
  10121. if (this.ticks > 1) {
  10122. setTimeout(this.tick, 1);
  10123. }
  10124. this.ticks = 0;
  10125. }
  10126. };
  10127. AudioTrackController.prototype.doTick = function doTick() {
  10128. this.updateTrack(this.trackId);
  10129. };
  10130. AudioTrackController.prototype.onError = function onError(data) {
  10131. if (data.fatal && data.type === errors["b" /* ErrorTypes */].NETWORK_ERROR) {
  10132. this.cleanTimer();
  10133. }
  10134. };
  10135. AudioTrackController.prototype.onManifestLoading = function onManifestLoading() {
  10136. // reset audio tracks on manifest loading
  10137. this.tracks = [];
  10138. this.trackId = -1;
  10139. };
  10140. AudioTrackController.prototype.onManifestParsed = function onManifestParsed(data) {
  10141. var _this2 = this;
  10142. var tracks = data.audioTracks || [];
  10143. var defaultFound = false;
  10144. this.tracks = tracks;
  10145. this.hls.trigger(events["a" /* default */].AUDIO_TRACKS_UPDATED, { audioTracks: tracks });
  10146. // loop through available audio tracks and autoselect default if needed
  10147. var id = 0;
  10148. tracks.forEach(function (track) {
  10149. if (track.default && !defaultFound) {
  10150. _this2.audioTrack = id;
  10151. defaultFound = true;
  10152. return;
  10153. }
  10154. id++;
  10155. });
  10156. if (defaultFound === false && tracks.length) {
  10157. logger["b" /* logger */].log('no default audio track defined, use first audio track as default');
  10158. this.audioTrack = 0;
  10159. }
  10160. };
  10161. AudioTrackController.prototype.onAudioTrackLoaded = function onAudioTrackLoaded(data) {
  10162. if (data.id < this.tracks.length) {
  10163. logger["b" /* logger */].log('audioTrack ' + data.id + ' loaded');
  10164. this.tracks[data.id].details = data.details;
  10165. // check if current playlist is a live playlist
  10166. if (data.details.live && !this.timer) {
  10167. // if live playlist we will have to reload it periodically
  10168. // set reload period to playlist target duration
  10169. this.timer = setInterval(this.ontick, 1000 * data.details.targetduration);
  10170. }
  10171. if (!data.details.live && this.timer) {
  10172. // playlist is not live and timer is armed : stopping it
  10173. this.cleanTimer();
  10174. }
  10175. }
  10176. };
  10177. /** get alternate audio tracks list from playlist **/
  10178. AudioTrackController.prototype.setAudioTrackInternal = function setAudioTrackInternal(newId) {
  10179. // check if level idx is valid
  10180. if (newId >= 0 && newId < this.tracks.length) {
  10181. // stopping live reloading timer if any
  10182. this.cleanTimer();
  10183. this.trackId = newId;
  10184. logger["b" /* logger */].log('switching to audioTrack ' + newId);
  10185. var audioTrack = this.tracks[newId],
  10186. hls = this.hls,
  10187. type = audioTrack.type,
  10188. url = audioTrack.url,
  10189. eventObj = { id: newId, type: type, url: url };
  10190. // keep AUDIO_TRACK_SWITCH for legacy reason
  10191. hls.trigger(events["a" /* default */].AUDIO_TRACK_SWITCH, eventObj);
  10192. hls.trigger(events["a" /* default */].AUDIO_TRACK_SWITCHING, eventObj);
  10193. // check if we need to load playlist for this audio Track
  10194. var details = audioTrack.details;
  10195. if (url && (details === undefined || details.live === true)) {
  10196. // track not retrieved yet, or live playlist we need to (re)load it
  10197. logger["b" /* logger */].log('(re)loading playlist for audioTrack ' + newId);
  10198. hls.trigger(events["a" /* default */].AUDIO_TRACK_LOADING, { url: url, id: newId });
  10199. }
  10200. }
  10201. };
  10202. AudioTrackController.prototype.updateTrack = function updateTrack(newId) {
  10203. // check if level idx is valid
  10204. if (newId >= 0 && newId < this.tracks.length) {
  10205. // stopping live reloading timer if any
  10206. this.cleanTimer();
  10207. this.trackId = newId;
  10208. logger["b" /* logger */].log('updating audioTrack ' + newId);
  10209. var audioTrack = this.tracks[newId],
  10210. url = audioTrack.url;
  10211. // check if we need to load playlist for this audio Track
  10212. var details = audioTrack.details;
  10213. if (url && (details === undefined || details.live === true)) {
  10214. // track not retrieved yet, or live playlist we need to (re)load it
  10215. logger["b" /* logger */].log('(re)loading playlist for audioTrack ' + newId);
  10216. this.hls.trigger(events["a" /* default */].AUDIO_TRACK_LOADING, { url: url, id: newId });
  10217. }
  10218. }
  10219. };
  10220. audio_track_controller__createClass(AudioTrackController, [{
  10221. key: 'audioTracks',
  10222. get: function get() {
  10223. return this.tracks;
  10224. }
  10225. /** get index of the selected audio track (index in audio track lists) **/
  10226. }, {
  10227. key: 'audioTrack',
  10228. get: function get() {
  10229. return this.trackId;
  10230. }
  10231. /** select an audio track, based on its index in audio track lists**/
  10232. ,
  10233. set: function set(audioTrackId) {
  10234. if (this.trackId !== audioTrackId || this.tracks[audioTrackId].details === undefined) {
  10235. this.setAudioTrackInternal(audioTrackId);
  10236. }
  10237. }
  10238. }]);
  10239. return AudioTrackController;
  10240. }(event_handler);
  10241. /* harmony default export */ var audio_track_controller = (audio_track_controller_AudioTrackController);
  10242. // CONCATENATED MODULE: ./src/controller/audio-stream-controller.js
  10243. var audio_stream_controller__createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  10244. function audio_stream_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  10245. function audio_stream_controller__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; }
  10246. function audio_stream_controller__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; }
  10247. /*
  10248. * Audio Stream Controller
  10249. */
  10250. var audio_stream_controller_State = {
  10251. STOPPED: 'STOPPED',
  10252. STARTING: 'STARTING',
  10253. IDLE: 'IDLE',
  10254. PAUSED: 'PAUSED',
  10255. KEY_LOADING: 'KEY_LOADING',
  10256. FRAG_LOADING: 'FRAG_LOADING',
  10257. FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
  10258. WAITING_TRACK: 'WAITING_TRACK',
  10259. PARSING: 'PARSING',
  10260. PARSED: 'PARSED',
  10261. BUFFER_FLUSHING: 'BUFFER_FLUSHING',
  10262. ENDED: 'ENDED',
  10263. ERROR: 'ERROR',
  10264. WAITING_INIT_PTS: 'WAITING_INIT_PTS'
  10265. };
  10266. var audio_stream_controller_AudioStreamController = function (_TaskLoop) {
  10267. audio_stream_controller__inherits(AudioStreamController, _TaskLoop);
  10268. function AudioStreamController(hls) {
  10269. audio_stream_controller__classCallCheck(this, AudioStreamController);
  10270. var _this = audio_stream_controller__possibleConstructorReturn(this, _TaskLoop.call(this, hls, events["a" /* default */].MEDIA_ATTACHED, events["a" /* default */].MEDIA_DETACHING, events["a" /* default */].AUDIO_TRACKS_UPDATED, events["a" /* default */].AUDIO_TRACK_SWITCHING, events["a" /* default */].AUDIO_TRACK_LOADED, events["a" /* default */].KEY_LOADED, events["a" /* default */].FRAG_LOADED, events["a" /* default */].FRAG_PARSING_INIT_SEGMENT, events["a" /* default */].FRAG_PARSING_DATA, events["a" /* default */].FRAG_PARSED, events["a" /* default */].ERROR, events["a" /* default */].BUFFER_RESET, events["a" /* default */].BUFFER_CREATED, events["a" /* default */].BUFFER_APPENDED, events["a" /* default */].BUFFER_FLUSHED, events["a" /* default */].INIT_PTS_FOUND));
  10271. _this.config = hls.config;
  10272. _this.audioCodecSwap = false;
  10273. _this._state = audio_stream_controller_State.STOPPED;
  10274. _this.initPTS = [];
  10275. _this.waitingFragment = null;
  10276. _this.videoTrackCC = null;
  10277. return _this;
  10278. }
  10279. AudioStreamController.prototype.onHandlerDestroying = function onHandlerDestroying() {
  10280. this.stopLoad();
  10281. };
  10282. AudioStreamController.prototype.onHandlerDestroyed = function onHandlerDestroyed() {
  10283. this.state = audio_stream_controller_State.STOPPED;
  10284. };
  10285. //Signal that video PTS was found
  10286. AudioStreamController.prototype.onInitPtsFound = function onInitPtsFound(data) {
  10287. var demuxerId = data.id,
  10288. cc = data.frag.cc,
  10289. initPTS = data.initPTS;
  10290. if (demuxerId === 'main') {
  10291. //Always update the new INIT PTS
  10292. //Can change due level switch
  10293. this.initPTS[cc] = initPTS;
  10294. this.videoTrackCC = cc;
  10295. logger["b" /* logger */].log('InitPTS for cc: ' + cc + ' found from video track: ' + initPTS);
  10296. //If we are waiting we need to demux/remux the waiting frag
  10297. //With the new initPTS
  10298. if (this.state === audio_stream_controller_State.WAITING_INIT_PTS) {
  10299. this.tick();
  10300. }
  10301. }
  10302. };
  10303. AudioStreamController.prototype.startLoad = function startLoad(startPosition) {
  10304. if (this.tracks) {
  10305. var lastCurrentTime = this.lastCurrentTime;
  10306. this.stopLoad();
  10307. this.setInterval(100);
  10308. this.fragLoadError = 0;
  10309. if (lastCurrentTime > 0 && startPosition === -1) {
  10310. logger["b" /* logger */].log('audio:override startPosition with lastCurrentTime @' + lastCurrentTime.toFixed(3));
  10311. this.state = audio_stream_controller_State.IDLE;
  10312. } else {
  10313. this.lastCurrentTime = this.startPosition ? this.startPosition : startPosition;
  10314. this.state = audio_stream_controller_State.STARTING;
  10315. }
  10316. this.nextLoadPosition = this.startPosition = this.lastCurrentTime;
  10317. this.tick();
  10318. } else {
  10319. this.startPosition = startPosition;
  10320. this.state = audio_stream_controller_State.STOPPED;
  10321. }
  10322. };
  10323. AudioStreamController.prototype.stopLoad = function stopLoad() {
  10324. var frag = this.fragCurrent;
  10325. if (frag) {
  10326. if (frag.loader) {
  10327. frag.loader.abort();
  10328. }
  10329. this.fragCurrent = null;
  10330. }
  10331. this.fragPrevious = null;
  10332. if (this.demuxer) {
  10333. this.demuxer.destroy();
  10334. this.demuxer = null;
  10335. }
  10336. this.state = audio_stream_controller_State.STOPPED;
  10337. };
  10338. AudioStreamController.prototype.doTick = function doTick() {
  10339. var pos,
  10340. track,
  10341. trackDetails,
  10342. hls = this.hls,
  10343. config = hls.config;
  10344. //logger.log('audioStream:' + this.state);
  10345. switch (this.state) {
  10346. case audio_stream_controller_State.ERROR:
  10347. //don't do anything in error state to avoid breaking further ...
  10348. case audio_stream_controller_State.PAUSED:
  10349. //don't do anything in paused state either ...
  10350. case audio_stream_controller_State.BUFFER_FLUSHING:
  10351. break;
  10352. case audio_stream_controller_State.STARTING:
  10353. this.state = audio_stream_controller_State.WAITING_TRACK;
  10354. this.loadedmetadata = false;
  10355. break;
  10356. case audio_stream_controller_State.IDLE:
  10357. var tracks = this.tracks;
  10358. // audio tracks not received => exit loop
  10359. if (!tracks) {
  10360. break;
  10361. }
  10362. // if video not attached AND
  10363. // start fragment already requested OR start frag prefetch disable
  10364. // exit loop
  10365. // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop
  10366. if (!this.media && (this.startFragRequested || !config.startFragPrefetch)) {
  10367. break;
  10368. }
  10369. // determine next candidate fragment to be loaded, based on current position and
  10370. // end of buffer position
  10371. // if we have not yet loaded any fragment, start loading from start position
  10372. if (this.loadedmetadata) {
  10373. pos = this.media.currentTime;
  10374. } else {
  10375. pos = this.nextLoadPosition;
  10376. if (pos === undefined) {
  10377. break;
  10378. }
  10379. }
  10380. var media = this.mediaBuffer ? this.mediaBuffer : this.media,
  10381. videoBuffer = this.videoBuffer ? this.videoBuffer : this.media,
  10382. bufferInfo = buffer_helper.bufferInfo(media, pos, config.maxBufferHole),
  10383. mainBufferInfo = buffer_helper.bufferInfo(videoBuffer, pos, config.maxBufferHole),
  10384. bufferLen = bufferInfo.len,
  10385. bufferEnd = bufferInfo.end,
  10386. fragPrevious = this.fragPrevious,
  10387. // ensure we buffer at least config.maxBufferLength (default 30s)
  10388. // once we reach that threshold, don't buffer more than video (mainBufferInfo.len)
  10389. maxBufLen = Math.max(config.maxBufferLength, mainBufferInfo.len),
  10390. audioSwitch = this.audioSwitch,
  10391. trackId = this.trackId;
  10392. // if buffer length is less than maxBufLen try to load a new fragment
  10393. if ((bufferLen < maxBufLen || audioSwitch) && trackId < tracks.length) {
  10394. trackDetails = tracks[trackId].details;
  10395. // if track info not retrieved yet, switch state and wait for track retrieval
  10396. if (typeof trackDetails === 'undefined') {
  10397. this.state = audio_stream_controller_State.WAITING_TRACK;
  10398. break;
  10399. }
  10400. // check if we need to finalize media stream
  10401. // we just got done loading the final fragment and there is no other buffered range after ...
  10402. // rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between
  10403. // so we should not switch to ENDED in that case, to be able to buffer them
  10404. if (!audioSwitch && !trackDetails.live && fragPrevious && fragPrevious.sn === trackDetails.endSN && !bufferInfo.nextStart) {
  10405. // if we are not seeking or if we are seeking but everything (almost) til the end is buffered, let's signal eos
  10406. // we don't compare exactly media.duration === bufferInfo.end as there could be some subtle media duration difference when switching
  10407. // between different renditions. using half frag duration should help cope with these cases.
  10408. if (!this.media.seeking || this.media.duration - bufferEnd < fragPrevious.duration / 2) {
  10409. // Finalize the media stream
  10410. this.hls.trigger(events["a" /* default */].BUFFER_EOS, { type: 'audio' });
  10411. this.state = audio_stream_controller_State.ENDED;
  10412. break;
  10413. }
  10414. }
  10415. // find fragment index, contiguous with end of buffer position
  10416. var fragments = trackDetails.fragments,
  10417. fragLen = fragments.length,
  10418. start = fragments[0].start,
  10419. end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,
  10420. frag = void 0;
  10421. // When switching audio track, reload audio as close as possible to currentTime
  10422. if (audioSwitch) {
  10423. if (trackDetails.live && !trackDetails.PTSKnown) {
  10424. logger["b" /* logger */].log('switching audiotrack, live stream, unknown PTS,load first fragment');
  10425. bufferEnd = 0;
  10426. } else {
  10427. bufferEnd = pos;
  10428. // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime
  10429. if (trackDetails.PTSKnown && pos < start) {
  10430. // if everything is buffered from pos to start or if audio buffer upfront, let's seek to start
  10431. if (bufferInfo.end > start || bufferInfo.nextStart) {
  10432. logger["b" /* logger */].log('alt audio track ahead of main track, seek to start of alt audio track');
  10433. this.media.currentTime = start + 0.05;
  10434. } else {
  10435. return;
  10436. }
  10437. }
  10438. }
  10439. }
  10440. if (trackDetails.initSegment && !trackDetails.initSegment.data) {
  10441. frag = trackDetails.initSegment;
  10442. }
  10443. // if bufferEnd before start of playlist, load first fragment
  10444. else if (bufferEnd <= start) {
  10445. frag = fragments[0];
  10446. if (this.videoTrackCC !== null && frag.cc !== this.videoTrackCC) {
  10447. // Ensure we find a fragment which matches the continuity of the video track
  10448. frag = findFragWithCC(fragments, this.videoTrackCC);
  10449. }
  10450. if (trackDetails.live && frag.loadIdx && frag.loadIdx === this.fragLoadIdx) {
  10451. // we just loaded this first fragment, and we are still lagging behind the start of the live playlist
  10452. // let's force seek to start
  10453. var nextBuffered = bufferInfo.nextStart ? bufferInfo.nextStart : start;
  10454. logger["b" /* logger */].log('no alt audio available @currentTime:' + this.media.currentTime + ', seeking @' + (nextBuffered + 0.05));
  10455. this.media.currentTime = nextBuffered + 0.05;
  10456. return;
  10457. }
  10458. } else {
  10459. var foundFrag = void 0;
  10460. var maxFragLookUpTolerance = config.maxFragLookUpTolerance;
  10461. var fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : undefined;
  10462. var fragmentWithinToleranceTest = function fragmentWithinToleranceTest(candidate) {
  10463. // offset should be within fragment boundary - config.maxFragLookUpTolerance
  10464. // this is to cope with situations like
  10465. // bufferEnd = 9.991
  10466. // frag[Ø] : [0,10]
  10467. // frag[1] : [10,20]
  10468. // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
  10469. // frag start frag start+duration
  10470. // |-----------------------------|
  10471. // <---> <--->
  10472. // ...--------><-----------------------------><---------....
  10473. // previous frag matching fragment next frag
  10474. // return -1 return 0 return 1
  10475. //logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
  10476. // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
  10477. var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration);
  10478. if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
  10479. return 1;
  10480. } // if maxFragLookUpTolerance will have negative value then don't return -1 for first element
  10481. else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
  10482. return -1;
  10483. }
  10484. return 0;
  10485. };
  10486. if (bufferEnd < end) {
  10487. if (bufferEnd > end - maxFragLookUpTolerance) {
  10488. maxFragLookUpTolerance = 0;
  10489. }
  10490. // Prefer the next fragment if it's within tolerance
  10491. if (fragNext && !fragmentWithinToleranceTest(fragNext)) {
  10492. foundFrag = fragNext;
  10493. } else {
  10494. foundFrag = binary_search.search(fragments, fragmentWithinToleranceTest);
  10495. }
  10496. } else {
  10497. // reach end of playlist
  10498. foundFrag = fragments[fragLen - 1];
  10499. }
  10500. if (foundFrag) {
  10501. frag = foundFrag;
  10502. start = foundFrag.start;
  10503. //logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);
  10504. if (fragPrevious && frag.level === fragPrevious.level && frag.sn === fragPrevious.sn) {
  10505. if (frag.sn < trackDetails.endSN) {
  10506. frag = fragments[frag.sn + 1 - trackDetails.startSN];
  10507. logger["b" /* logger */].log('SN just loaded, load next one: ' + frag.sn);
  10508. } else {
  10509. frag = null;
  10510. }
  10511. }
  10512. }
  10513. }
  10514. if (frag) {
  10515. //logger.log(' loading frag ' + i +',pos/bufEnd:' + pos.toFixed(3) + '/' + bufferEnd.toFixed(3));
  10516. if (frag.decryptdata && frag.decryptdata.uri != null && frag.decryptdata.key == null) {
  10517. logger["b" /* logger */].log('Loading key for ' + frag.sn + ' of [' + trackDetails.startSN + ' ,' + trackDetails.endSN + '],track ' + trackId);
  10518. this.state = audio_stream_controller_State.KEY_LOADING;
  10519. hls.trigger(events["a" /* default */].KEY_LOADING, { frag: frag });
  10520. } else {
  10521. logger["b" /* logger */].log('Loading ' + frag.sn + ', cc: ' + frag.cc + ' of [' + trackDetails.startSN + ' ,' + trackDetails.endSN + '],track ' + trackId + ', currentTime:' + pos + ',bufferEnd:' + bufferEnd.toFixed(3));
  10522. // ensure that we are not reloading the same fragments in loop ...
  10523. if (this.fragLoadIdx !== undefined) {
  10524. this.fragLoadIdx++;
  10525. } else {
  10526. this.fragLoadIdx = 0;
  10527. }
  10528. if (frag.loadCounter) {
  10529. frag.loadCounter++;
  10530. var maxThreshold = config.fragLoadingLoopThreshold;
  10531. // if this frag has already been loaded 3 times, and if it has been reloaded recently
  10532. if (frag.loadCounter > maxThreshold && Math.abs(this.fragLoadIdx - frag.loadIdx) < maxThreshold) {
  10533. hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: errors["a" /* ErrorDetails */].FRAG_LOOP_LOADING_ERROR, fatal: false, frag: frag });
  10534. return;
  10535. }
  10536. } else {
  10537. frag.loadCounter = 1;
  10538. }
  10539. frag.loadIdx = this.fragLoadIdx;
  10540. this.fragCurrent = frag;
  10541. this.startFragRequested = true;
  10542. if (!isNaN(frag.sn)) {
  10543. this.nextLoadPosition = frag.start + frag.duration;
  10544. }
  10545. hls.trigger(events["a" /* default */].FRAG_LOADING, { frag: frag });
  10546. this.state = audio_stream_controller_State.FRAG_LOADING;
  10547. }
  10548. }
  10549. }
  10550. break;
  10551. case audio_stream_controller_State.WAITING_TRACK:
  10552. track = this.tracks[this.trackId];
  10553. // check if playlist is already loaded
  10554. if (track && track.details) {
  10555. this.state = audio_stream_controller_State.IDLE;
  10556. }
  10557. break;
  10558. case audio_stream_controller_State.FRAG_LOADING_WAITING_RETRY:
  10559. var now = performance.now();
  10560. var retryDate = this.retryDate;
  10561. media = this.media;
  10562. var isSeeking = media && media.seeking;
  10563. // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  10564. if (!retryDate || now >= retryDate || isSeeking) {
  10565. logger["b" /* logger */].log('audioStreamController: retryDate reached, switch back to IDLE state');
  10566. this.state = audio_stream_controller_State.IDLE;
  10567. }
  10568. break;
  10569. case audio_stream_controller_State.WAITING_INIT_PTS:
  10570. var videoTrackCC = this.videoTrackCC;
  10571. if (this.initPTS[videoTrackCC] === undefined) {
  10572. break;
  10573. }
  10574. // Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS
  10575. var waitingFrag = this.waitingFragment;
  10576. if (waitingFrag) {
  10577. var waitingFragCC = waitingFrag.frag.cc;
  10578. if (videoTrackCC !== waitingFragCC) {
  10579. track = this.tracks[this.trackId];
  10580. if (track.details && track.details.live) {
  10581. logger["b" /* logger */].warn('Waiting fragment CC (' + waitingFragCC + ') does not match video track CC (' + videoTrackCC + ')');
  10582. this.waitingFragment = null;
  10583. this.state = audio_stream_controller_State.IDLE;
  10584. }
  10585. } else {
  10586. this.state = audio_stream_controller_State.FRAG_LOADING;
  10587. this.onFragLoaded(this.waitingFragment);
  10588. this.waitingFragment = null;
  10589. }
  10590. } else {
  10591. this.state = audio_stream_controller_State.IDLE;
  10592. }
  10593. break;
  10594. case audio_stream_controller_State.STOPPED:
  10595. case audio_stream_controller_State.FRAG_LOADING:
  10596. case audio_stream_controller_State.PARSING:
  10597. case audio_stream_controller_State.PARSED:
  10598. case audio_stream_controller_State.ENDED:
  10599. break;
  10600. default:
  10601. break;
  10602. }
  10603. };
  10604. AudioStreamController.prototype.onMediaAttached = function onMediaAttached(data) {
  10605. var media = this.media = this.mediaBuffer = data.media;
  10606. this.onvseeking = this.onMediaSeeking.bind(this);
  10607. this.onvended = this.onMediaEnded.bind(this);
  10608. media.addEventListener('seeking', this.onvseeking);
  10609. media.addEventListener('ended', this.onvended);
  10610. var config = this.config;
  10611. if (this.tracks && config.autoStartLoad) {
  10612. this.startLoad(config.startPosition);
  10613. }
  10614. };
  10615. AudioStreamController.prototype.onMediaDetaching = function onMediaDetaching() {
  10616. var media = this.media;
  10617. if (media && media.ended) {
  10618. logger["b" /* logger */].log('MSE detaching and video ended, reset startPosition');
  10619. this.startPosition = this.lastCurrentTime = 0;
  10620. }
  10621. // reset fragment loading counter on MSE detaching to avoid reporting FRAG_LOOP_LOADING_ERROR after error recovery
  10622. var tracks = this.tracks;
  10623. if (tracks) {
  10624. // reset fragment load counter
  10625. tracks.forEach(function (track) {
  10626. if (track.details) {
  10627. track.details.fragments.forEach(function (fragment) {
  10628. fragment.loadCounter = undefined;
  10629. });
  10630. }
  10631. });
  10632. }
  10633. // remove video listeners
  10634. if (media) {
  10635. media.removeEventListener('seeking', this.onvseeking);
  10636. media.removeEventListener('ended', this.onvended);
  10637. this.onvseeking = this.onvseeked = this.onvended = null;
  10638. }
  10639. this.media = this.mediaBuffer = this.videoBuffer = null;
  10640. this.loadedmetadata = false;
  10641. this.stopLoad();
  10642. };
  10643. AudioStreamController.prototype.onMediaSeeking = function onMediaSeeking() {
  10644. if (this.state === audio_stream_controller_State.ENDED) {
  10645. // switch to IDLE state to check for potential new fragment
  10646. this.state = audio_stream_controller_State.IDLE;
  10647. }
  10648. if (this.media) {
  10649. this.lastCurrentTime = this.media.currentTime;
  10650. }
  10651. // avoid reporting fragment loop loading error in case user is seeking several times on same position
  10652. if (this.fragLoadIdx !== undefined) {
  10653. this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;
  10654. }
  10655. // tick to speed up processing
  10656. this.tick();
  10657. };
  10658. AudioStreamController.prototype.onMediaEnded = function onMediaEnded() {
  10659. // reset startPosition and lastCurrentTime to restart playback @ stream beginning
  10660. this.startPosition = this.lastCurrentTime = 0;
  10661. };
  10662. AudioStreamController.prototype.onAudioTracksUpdated = function onAudioTracksUpdated(data) {
  10663. logger["b" /* logger */].log('audio tracks updated');
  10664. this.tracks = data.audioTracks;
  10665. };
  10666. AudioStreamController.prototype.onAudioTrackSwitching = function onAudioTrackSwitching(data) {
  10667. // if any URL found on new audio track, it is an alternate audio track
  10668. var altAudio = !!data.url;
  10669. this.trackId = data.id;
  10670. this.fragCurrent = null;
  10671. this.state = audio_stream_controller_State.PAUSED;
  10672. this.waitingFragment = null;
  10673. // destroy useless demuxer when switching audio to main
  10674. if (!altAudio) {
  10675. if (this.demuxer) {
  10676. this.demuxer.destroy();
  10677. this.demuxer = null;
  10678. }
  10679. } else {
  10680. // switching to audio track, start timer if not already started
  10681. this.setInterval(100);
  10682. }
  10683. //should we switch tracks ?
  10684. if (altAudio) {
  10685. this.audioSwitch = true;
  10686. //main audio track are handled by stream-controller, just do something if switching to alt audio track
  10687. this.state = audio_stream_controller_State.IDLE;
  10688. // increase fragment load Index to avoid frag loop loading error after buffer flush
  10689. if (this.fragLoadIdx !== undefined) {
  10690. this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;
  10691. }
  10692. }
  10693. this.tick();
  10694. };
  10695. AudioStreamController.prototype.onAudioTrackLoaded = function onAudioTrackLoaded(data) {
  10696. var newDetails = data.details,
  10697. trackId = data.id,
  10698. track = this.tracks[trackId],
  10699. duration = newDetails.totalduration,
  10700. sliding = 0;
  10701. logger["b" /* logger */].log('track ' + trackId + ' loaded [' + newDetails.startSN + ',' + newDetails.endSN + '],duration:' + duration);
  10702. if (newDetails.live) {
  10703. var curDetails = track.details;
  10704. if (curDetails && newDetails.fragments.length > 0) {
  10705. // we already have details for that level, merge them
  10706. mergeDetails(curDetails, newDetails);
  10707. sliding = newDetails.fragments[0].start;
  10708. // TODO
  10709. //this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);
  10710. if (newDetails.PTSKnown) {
  10711. logger["b" /* logger */].log('live audio playlist sliding:' + sliding.toFixed(3));
  10712. } else {
  10713. logger["b" /* logger */].log('live audio playlist - outdated PTS, unknown sliding');
  10714. }
  10715. } else {
  10716. newDetails.PTSKnown = false;
  10717. logger["b" /* logger */].log('live audio playlist - first load, unknown sliding');
  10718. }
  10719. } else {
  10720. newDetails.PTSKnown = false;
  10721. }
  10722. track.details = newDetails;
  10723. // compute start position
  10724. if (!this.startFragRequested) {
  10725. // compute start position if set to -1. use it straight away if value is defined
  10726. if (this.startPosition === -1) {
  10727. // first, check if start time offset has been set in playlist, if yes, use this value
  10728. var startTimeOffset = newDetails.startTimeOffset;
  10729. if (!isNaN(startTimeOffset)) {
  10730. logger["b" /* logger */].log('start time offset found in playlist, adjust startPosition to ' + startTimeOffset);
  10731. this.startPosition = startTimeOffset;
  10732. } else {
  10733. this.startPosition = 0;
  10734. }
  10735. }
  10736. this.nextLoadPosition = this.startPosition;
  10737. }
  10738. // only switch batck to IDLE state if we were waiting for track to start downloading a new fragment
  10739. if (this.state === audio_stream_controller_State.WAITING_TRACK) {
  10740. this.state = audio_stream_controller_State.IDLE;
  10741. }
  10742. //trigger handler right now
  10743. this.tick();
  10744. };
  10745. AudioStreamController.prototype.onKeyLoaded = function onKeyLoaded() {
  10746. if (this.state === audio_stream_controller_State.KEY_LOADING) {
  10747. this.state = audio_stream_controller_State.IDLE;
  10748. this.tick();
  10749. }
  10750. };
  10751. AudioStreamController.prototype.onFragLoaded = function onFragLoaded(data) {
  10752. var fragCurrent = this.fragCurrent,
  10753. fragLoaded = data.frag;
  10754. if (this.state === audio_stream_controller_State.FRAG_LOADING && fragCurrent && fragLoaded.type === 'audio' && fragLoaded.level === fragCurrent.level && fragLoaded.sn === fragCurrent.sn) {
  10755. var track = this.tracks[this.trackId],
  10756. details = track.details,
  10757. duration = details.totalduration,
  10758. trackId = fragCurrent.level,
  10759. sn = fragCurrent.sn,
  10760. cc = fragCurrent.cc,
  10761. audioCodec = this.config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2',
  10762. stats = this.stats = data.stats;
  10763. if (sn === 'initSegment') {
  10764. this.state = audio_stream_controller_State.IDLE;
  10765. stats.tparsed = stats.tbuffered = performance.now();
  10766. details.initSegment.data = data.payload;
  10767. this.hls.trigger(events["a" /* default */].FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'audio' });
  10768. this.tick();
  10769. } else {
  10770. this.state = audio_stream_controller_State.PARSING;
  10771. // transmux the MPEG-TS data to ISO-BMFF segments
  10772. this.appended = false;
  10773. if (!this.demuxer) {
  10774. this.demuxer = new demux_demuxer(this.hls, 'audio');
  10775. }
  10776. //Check if we have video initPTS
  10777. // If not we need to wait for it
  10778. var initPTS = this.initPTS[cc];
  10779. var initSegmentData = details.initSegment ? details.initSegment.data : [];
  10780. if (details.initSegment || initPTS !== undefined) {
  10781. this.pendingBuffering = true;
  10782. logger["b" /* logger */].log('Demuxing ' + sn + ' of [' + details.startSN + ' ,' + details.endSN + '],track ' + trackId);
  10783. // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
  10784. var accurateTimeOffset = false; //details.PTSKnown || !details.live;
  10785. this.demuxer.push(data.payload, initSegmentData, audioCodec, null, fragCurrent, duration, accurateTimeOffset, initPTS);
  10786. } else {
  10787. logger["b" /* 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);
  10788. this.waitingFragment = data;
  10789. this.state = audio_stream_controller_State.WAITING_INIT_PTS;
  10790. }
  10791. }
  10792. }
  10793. this.fragLoadError = 0;
  10794. };
  10795. AudioStreamController.prototype.onFragParsingInitSegment = function onFragParsingInitSegment(data) {
  10796. var fragCurrent = this.fragCurrent;
  10797. var fragNew = data.frag;
  10798. if (fragCurrent && data.id === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === audio_stream_controller_State.PARSING) {
  10799. var tracks = data.tracks,
  10800. track = void 0;
  10801. // delete any video track found on audio demuxer
  10802. if (tracks.video) {
  10803. delete tracks.video;
  10804. }
  10805. // include levelCodec in audio and video tracks
  10806. track = tracks.audio;
  10807. if (track) {
  10808. track.levelCodec = track.codec;
  10809. track.id = data.id;
  10810. this.hls.trigger(events["a" /* default */].BUFFER_CODECS, tracks);
  10811. logger["b" /* logger */].log('audio track:audio,container:' + track.container + ',codecs[level/parsed]=[' + track.levelCodec + '/' + track.codec + ']');
  10812. var initSegment = track.initSegment;
  10813. if (initSegment) {
  10814. var appendObj = { type: 'audio', data: initSegment, parent: 'audio', content: 'initSegment' };
  10815. if (this.audioSwitch) {
  10816. this.pendingData = [appendObj];
  10817. } else {
  10818. this.appended = true;
  10819. // arm pending Buffering flag before appending a segment
  10820. this.pendingBuffering = true;
  10821. this.hls.trigger(events["a" /* default */].BUFFER_APPENDING, appendObj);
  10822. }
  10823. }
  10824. //trigger handler right now
  10825. this.tick();
  10826. }
  10827. }
  10828. };
  10829. AudioStreamController.prototype.onFragParsingData = function onFragParsingData(data) {
  10830. var _this2 = this;
  10831. var fragCurrent = this.fragCurrent;
  10832. var fragNew = data.frag;
  10833. if (fragCurrent && data.id === 'audio' && data.type === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === audio_stream_controller_State.PARSING) {
  10834. var trackId = this.trackId,
  10835. track = this.tracks[trackId],
  10836. hls = this.hls;
  10837. if (isNaN(data.endPTS)) {
  10838. data.endPTS = data.startPTS + fragCurrent.duration;
  10839. data.endDTS = data.startDTS + fragCurrent.duration;
  10840. }
  10841. logger["b" /* 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);
  10842. updateFragPTSDTS(track.details, fragCurrent, data.startPTS, data.endPTS);
  10843. var audioSwitch = this.audioSwitch,
  10844. media = this.media,
  10845. appendOnBufferFlush = false;
  10846. //Only flush audio from old audio tracks when PTS is known on new audio track
  10847. if (audioSwitch && media) {
  10848. if (media.readyState) {
  10849. var currentTime = media.currentTime;
  10850. logger["b" /* logger */].log('switching audio track : currentTime:' + currentTime);
  10851. if (currentTime >= data.startPTS) {
  10852. logger["b" /* logger */].log('switching audio track : flushing all audio');
  10853. this.state = audio_stream_controller_State.BUFFER_FLUSHING;
  10854. hls.trigger(events["a" /* default */].BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });
  10855. appendOnBufferFlush = true;
  10856. //Lets announce that the initial audio track switch flush occur
  10857. this.audioSwitch = false;
  10858. hls.trigger(events["a" /* default */].AUDIO_TRACK_SWITCHED, { id: trackId });
  10859. }
  10860. } else {
  10861. //Lets announce that the initial audio track switch flush occur
  10862. this.audioSwitch = false;
  10863. hls.trigger(events["a" /* default */].AUDIO_TRACK_SWITCHED, { id: trackId });
  10864. }
  10865. }
  10866. var pendingData = this.pendingData;
  10867. if (!pendingData) {
  10868. console.warn('Apparently attempt to enqueue media payload without codec initialization data upfront');
  10869. hls.trigger(events["a" /* default */].ERROR, { type: errors["b" /* ErrorTypes */].MEDIA_ERROR, details: null, fatal: true });
  10870. return;
  10871. }
  10872. if (!this.audioSwitch) {
  10873. [data.data1, data.data2].forEach(function (buffer) {
  10874. if (buffer && buffer.length) {
  10875. pendingData.push({ type: data.type, data: buffer, parent: 'audio', content: 'data' });
  10876. }
  10877. });
  10878. if (!appendOnBufferFlush && pendingData.length) {
  10879. pendingData.forEach(function (appendObj) {
  10880. // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)
  10881. // in that case it is useless to append following segments
  10882. if (_this2.state === audio_stream_controller_State.PARSING) {
  10883. // arm pending Buffering flag before appending a segment
  10884. _this2.pendingBuffering = true;
  10885. _this2.hls.trigger(events["a" /* default */].BUFFER_APPENDING, appendObj);
  10886. }
  10887. });
  10888. this.pendingData = [];
  10889. this.appended = true;
  10890. }
  10891. }
  10892. //trigger handler right now
  10893. this.tick();
  10894. }
  10895. };
  10896. AudioStreamController.prototype.onFragParsed = function onFragParsed(data) {
  10897. var fragCurrent = this.fragCurrent;
  10898. var fragNew = data.frag;
  10899. if (fragCurrent && data.id === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === audio_stream_controller_State.PARSING) {
  10900. this.stats.tparsed = performance.now();
  10901. this.state = audio_stream_controller_State.PARSED;
  10902. this._checkAppendedParsed();
  10903. }
  10904. };
  10905. AudioStreamController.prototype.onBufferReset = function onBufferReset() {
  10906. // reset reference to sourcebuffers
  10907. this.mediaBuffer = this.videoBuffer = null;
  10908. this.loadedmetadata = false;
  10909. };
  10910. AudioStreamController.prototype.onBufferCreated = function onBufferCreated(data) {
  10911. var audioTrack = data.tracks.audio;
  10912. if (audioTrack) {
  10913. this.mediaBuffer = audioTrack.buffer;
  10914. this.loadedmetadata = true;
  10915. }
  10916. if (data.tracks.video) {
  10917. this.videoBuffer = data.tracks.video.buffer;
  10918. }
  10919. };
  10920. AudioStreamController.prototype.onBufferAppended = function onBufferAppended(data) {
  10921. if (data.parent === 'audio') {
  10922. var state = this.state;
  10923. if (state === audio_stream_controller_State.PARSING || state === audio_stream_controller_State.PARSED) {
  10924. // check if all buffers have been appended
  10925. this.pendingBuffering = data.pending > 0;
  10926. this._checkAppendedParsed();
  10927. }
  10928. }
  10929. };
  10930. AudioStreamController.prototype._checkAppendedParsed = function _checkAppendedParsed() {
  10931. //trigger handler right now
  10932. if (this.state === audio_stream_controller_State.PARSED && (!this.appended || !this.pendingBuffering)) {
  10933. var frag = this.fragCurrent,
  10934. stats = this.stats,
  10935. hls = this.hls;
  10936. if (frag) {
  10937. this.fragPrevious = frag;
  10938. stats.tbuffered = performance.now();
  10939. hls.trigger(events["a" /* default */].FRAG_BUFFERED, { stats: stats, frag: frag, id: 'audio' });
  10940. var media = this.mediaBuffer ? this.mediaBuffer : this.media;
  10941. logger["b" /* logger */].log('audio buffered : ' + timeRanges.toString(media.buffered));
  10942. if (this.audioSwitch && this.appended) {
  10943. this.audioSwitch = false;
  10944. hls.trigger(events["a" /* default */].AUDIO_TRACK_SWITCHED, { id: this.trackId });
  10945. }
  10946. this.state = audio_stream_controller_State.IDLE;
  10947. }
  10948. this.tick();
  10949. }
  10950. };
  10951. AudioStreamController.prototype.onError = function onError(data) {
  10952. var frag = data.frag;
  10953. // don't handle frag error not related to audio fragment
  10954. if (frag && frag.type !== 'audio') {
  10955. return;
  10956. }
  10957. switch (data.details) {
  10958. case errors["a" /* ErrorDetails */].FRAG_LOAD_ERROR:
  10959. case errors["a" /* ErrorDetails */].FRAG_LOAD_TIMEOUT:
  10960. if (!data.fatal) {
  10961. var loadError = this.fragLoadError;
  10962. if (loadError) {
  10963. loadError++;
  10964. } else {
  10965. loadError = 1;
  10966. }
  10967. var config = this.config;
  10968. if (loadError <= config.fragLoadingMaxRetry) {
  10969. this.fragLoadError = loadError;
  10970. // reset load counter to avoid frag loop loading error
  10971. frag.loadCounter = 0;
  10972. // exponential backoff capped to config.fragLoadingMaxRetryTimeout
  10973. var delay = Math.min(Math.pow(2, loadError - 1) * config.fragLoadingRetryDelay, config.fragLoadingMaxRetryTimeout);
  10974. logger["b" /* logger */].warn('audioStreamController: frag loading failed, retry in ' + delay + ' ms');
  10975. this.retryDate = performance.now() + delay;
  10976. // retry loading state
  10977. this.state = audio_stream_controller_State.FRAG_LOADING_WAITING_RETRY;
  10978. } else {
  10979. logger["b" /* logger */].error('audioStreamController: ' + data.details + ' reaches max retry, redispatch as fatal ...');
  10980. // switch error to fatal
  10981. data.fatal = true;
  10982. this.state = audio_stream_controller_State.ERROR;
  10983. }
  10984. }
  10985. break;
  10986. case errors["a" /* ErrorDetails */].FRAG_LOOP_LOADING_ERROR:
  10987. case errors["a" /* ErrorDetails */].AUDIO_TRACK_LOAD_ERROR:
  10988. case errors["a" /* ErrorDetails */].AUDIO_TRACK_LOAD_TIMEOUT:
  10989. case errors["a" /* ErrorDetails */].KEY_LOAD_ERROR:
  10990. case errors["a" /* ErrorDetails */].KEY_LOAD_TIMEOUT:
  10991. // when in ERROR state, don't switch back to IDLE state in case a non-fatal error is received
  10992. if (this.state !== audio_stream_controller_State.ERROR) {
  10993. // if fatal error, stop processing, otherwise move to IDLE to retry loading
  10994. this.state = data.fatal ? audio_stream_controller_State.ERROR : audio_stream_controller_State.IDLE;
  10995. logger["b" /* logger */].warn('audioStreamController: ' + data.details + ' while loading frag,switch to ' + this.state + ' state ...');
  10996. }
  10997. break;
  10998. case errors["a" /* ErrorDetails */].BUFFER_FULL_ERROR:
  10999. // if in appending state
  11000. if (data.parent === 'audio' && (this.state === audio_stream_controller_State.PARSING || this.state === audio_stream_controller_State.PARSED)) {
  11001. var media = this.mediaBuffer,
  11002. currentTime = this.media.currentTime,
  11003. mediaBuffered = media && buffer_helper.isBuffered(media, currentTime) && buffer_helper.isBuffered(media, currentTime + 0.5);
  11004. // reduce max buf len if current position is buffered
  11005. if (mediaBuffered) {
  11006. var _config = this.config;
  11007. if (_config.maxMaxBufferLength >= _config.maxBufferLength) {
  11008. // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
  11009. _config.maxMaxBufferLength /= 2;
  11010. logger["b" /* logger */].warn('audio:reduce max buffer length to ' + _config.maxMaxBufferLength + 's');
  11011. // increase fragment load Index to avoid frag loop loading error after buffer flush
  11012. this.fragLoadIdx += 2 * _config.fragLoadingLoopThreshold;
  11013. }
  11014. this.state = audio_stream_controller_State.IDLE;
  11015. } else {
  11016. // current position is not buffered, but browser is still complaining about buffer full error
  11017. // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
  11018. // in that case flush the whole audio buffer to recover
  11019. logger["b" /* logger */].warn('buffer full error also media.currentTime is not buffered, flush audio buffer');
  11020. this.fragCurrent = null;
  11021. // flush everything
  11022. this.state = audio_stream_controller_State.BUFFER_FLUSHING;
  11023. this.hls.trigger(events["a" /* default */].BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });
  11024. }
  11025. }
  11026. break;
  11027. default:
  11028. break;
  11029. }
  11030. };
  11031. AudioStreamController.prototype.onBufferFlushed = function onBufferFlushed() {
  11032. var _this3 = this;
  11033. var pendingData = this.pendingData;
  11034. if (pendingData && pendingData.length) {
  11035. logger["b" /* logger */].log('appending pending audio data on Buffer Flushed');
  11036. pendingData.forEach(function (appendObj) {
  11037. _this3.hls.trigger(events["a" /* default */].BUFFER_APPENDING, appendObj);
  11038. });
  11039. this.appended = true;
  11040. this.pendingData = [];
  11041. this.state = audio_stream_controller_State.PARSED;
  11042. } else {
  11043. // move to IDLE once flush complete. this should trigger new fragment loading
  11044. this.state = audio_stream_controller_State.IDLE;
  11045. // reset reference to frag
  11046. this.fragPrevious = null;
  11047. this.tick();
  11048. }
  11049. };
  11050. audio_stream_controller__createClass(AudioStreamController, [{
  11051. key: 'state',
  11052. set: function set(nextState) {
  11053. if (this.state !== nextState) {
  11054. var previousState = this.state;
  11055. this._state = nextState;
  11056. logger["b" /* logger */].log('audio stream:' + previousState + '->' + nextState);
  11057. }
  11058. },
  11059. get: function get() {
  11060. return this._state;
  11061. }
  11062. }]);
  11063. return AudioStreamController;
  11064. }(task_loop);
  11065. /* harmony default export */ var audio_stream_controller = (audio_stream_controller_AudioStreamController);
  11066. // CONCATENATED MODULE: ./src/utils/vttcue.js
  11067. /**
  11068. * Copyright 2013 vtt.js Contributors
  11069. *
  11070. * Licensed under the Apache License, Version 2.0 (the "License");
  11071. * you may not use this file except in compliance with the License.
  11072. * You may obtain a copy of the License at
  11073. *
  11074. * http://www.apache.org/licenses/LICENSE-2.0
  11075. *
  11076. * Unless required by applicable law or agreed to in writing, software
  11077. * distributed under the License is distributed on an "AS IS" BASIS,
  11078. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11079. * See the License for the specific language governing permissions and
  11080. * limitations under the License.
  11081. */
  11082. /* harmony default export */ var vttcue = ((function () {
  11083. if (typeof window !== 'undefined' && window.VTTCue) {
  11084. return window.VTTCue;
  11085. }
  11086. var autoKeyword = 'auto';
  11087. var directionSetting = {
  11088. '': true,
  11089. lr: true,
  11090. rl: true
  11091. };
  11092. var alignSetting = {
  11093. start: true,
  11094. middle: true,
  11095. end: true,
  11096. left: true,
  11097. right: true
  11098. };
  11099. function findDirectionSetting(value) {
  11100. if (typeof value !== 'string') {
  11101. return false;
  11102. }
  11103. var dir = directionSetting[value.toLowerCase()];
  11104. return dir ? value.toLowerCase() : false;
  11105. }
  11106. function findAlignSetting(value) {
  11107. if (typeof value !== 'string') {
  11108. return false;
  11109. }
  11110. var align = alignSetting[value.toLowerCase()];
  11111. return align ? value.toLowerCase() : false;
  11112. }
  11113. function extend(obj) {
  11114. var i = 1;
  11115. for (; i < arguments.length; i++) {
  11116. var cobj = arguments[i];
  11117. for (var p in cobj) {
  11118. obj[p] = cobj[p];
  11119. }
  11120. }
  11121. return obj;
  11122. }
  11123. function VTTCue(startTime, endTime, text) {
  11124. var cue = this;
  11125. var isIE8 = function () {
  11126. if (typeof navigator === 'undefined') {
  11127. return;
  11128. }
  11129. return (/MSIE\s8\.0/.test(navigator.userAgent)
  11130. );
  11131. }();
  11132. var baseObj = {};
  11133. if (isIE8) {
  11134. cue = document.createElement('custom');
  11135. } else {
  11136. baseObj.enumerable = true;
  11137. }
  11138. /**
  11139. * Shim implementation specific properties. These properties are not in
  11140. * the spec.
  11141. */
  11142. // Lets us know when the VTTCue's data has changed in such a way that we need
  11143. // to recompute its display state. This lets us compute its display state
  11144. // lazily.
  11145. cue.hasBeenReset = false;
  11146. /**
  11147. * VTTCue and TextTrackCue properties
  11148. * http://dev.w3.org/html5/webvtt/#vttcue-interface
  11149. */
  11150. var _id = '';
  11151. var _pauseOnExit = false;
  11152. var _startTime = startTime;
  11153. var _endTime = endTime;
  11154. var _text = text;
  11155. var _region = null;
  11156. var _vertical = '';
  11157. var _snapToLines = true;
  11158. var _line = 'auto';
  11159. var _lineAlign = 'start';
  11160. var _position = 50;
  11161. var _positionAlign = 'middle';
  11162. var _size = 50;
  11163. var _align = 'middle';
  11164. Object.defineProperty(cue, 'id', extend({}, baseObj, {
  11165. get: function get() {
  11166. return _id;
  11167. },
  11168. set: function set(value) {
  11169. _id = '' + value;
  11170. }
  11171. }));
  11172. Object.defineProperty(cue, 'pauseOnExit', extend({}, baseObj, {
  11173. get: function get() {
  11174. return _pauseOnExit;
  11175. },
  11176. set: function set(value) {
  11177. _pauseOnExit = !!value;
  11178. }
  11179. }));
  11180. Object.defineProperty(cue, 'startTime', extend({}, baseObj, {
  11181. get: function get() {
  11182. return _startTime;
  11183. },
  11184. set: function set(value) {
  11185. if (typeof value !== 'number') {
  11186. throw new TypeError('Start time must be set to a number.');
  11187. }
  11188. _startTime = value;
  11189. this.hasBeenReset = true;
  11190. }
  11191. }));
  11192. Object.defineProperty(cue, 'endTime', extend({}, baseObj, {
  11193. get: function get() {
  11194. return _endTime;
  11195. },
  11196. set: function set(value) {
  11197. if (typeof value !== 'number') {
  11198. throw new TypeError('End time must be set to a number.');
  11199. }
  11200. _endTime = value;
  11201. this.hasBeenReset = true;
  11202. }
  11203. }));
  11204. Object.defineProperty(cue, 'text', extend({}, baseObj, {
  11205. get: function get() {
  11206. return _text;
  11207. },
  11208. set: function set(value) {
  11209. _text = '' + value;
  11210. this.hasBeenReset = true;
  11211. }
  11212. }));
  11213. Object.defineProperty(cue, 'region', extend({}, baseObj, {
  11214. get: function get() {
  11215. return _region;
  11216. },
  11217. set: function set(value) {
  11218. _region = value;
  11219. this.hasBeenReset = true;
  11220. }
  11221. }));
  11222. Object.defineProperty(cue, 'vertical', extend({}, baseObj, {
  11223. get: function get() {
  11224. return _vertical;
  11225. },
  11226. set: function set(value) {
  11227. var setting = findDirectionSetting(value);
  11228. // Have to check for false because the setting an be an empty string.
  11229. if (setting === false) {
  11230. throw new SyntaxError('An invalid or illegal string was specified.');
  11231. }
  11232. _vertical = setting;
  11233. this.hasBeenReset = true;
  11234. }
  11235. }));
  11236. Object.defineProperty(cue, 'snapToLines', extend({}, baseObj, {
  11237. get: function get() {
  11238. return _snapToLines;
  11239. },
  11240. set: function set(value) {
  11241. _snapToLines = !!value;
  11242. this.hasBeenReset = true;
  11243. }
  11244. }));
  11245. Object.defineProperty(cue, 'line', extend({}, baseObj, {
  11246. get: function get() {
  11247. return _line;
  11248. },
  11249. set: function set(value) {
  11250. if (typeof value !== 'number' && value !== autoKeyword) {
  11251. throw new SyntaxError('An invalid number or illegal string was specified.');
  11252. }
  11253. _line = value;
  11254. this.hasBeenReset = true;
  11255. }
  11256. }));
  11257. Object.defineProperty(cue, 'lineAlign', extend({}, baseObj, {
  11258. get: function get() {
  11259. return _lineAlign;
  11260. },
  11261. set: function set(value) {
  11262. var setting = findAlignSetting(value);
  11263. if (!setting) {
  11264. throw new SyntaxError('An invalid or illegal string was specified.');
  11265. }
  11266. _lineAlign = setting;
  11267. this.hasBeenReset = true;
  11268. }
  11269. }));
  11270. Object.defineProperty(cue, 'position', extend({}, baseObj, {
  11271. get: function get() {
  11272. return _position;
  11273. },
  11274. set: function set(value) {
  11275. if (value < 0 || value > 100) {
  11276. throw new Error('Position must be between 0 and 100.');
  11277. }
  11278. _position = value;
  11279. this.hasBeenReset = true;
  11280. }
  11281. }));
  11282. Object.defineProperty(cue, 'positionAlign', extend({}, baseObj, {
  11283. get: function get() {
  11284. return _positionAlign;
  11285. },
  11286. set: function set(value) {
  11287. var setting = findAlignSetting(value);
  11288. if (!setting) {
  11289. throw new SyntaxError('An invalid or illegal string was specified.');
  11290. }
  11291. _positionAlign = setting;
  11292. this.hasBeenReset = true;
  11293. }
  11294. }));
  11295. Object.defineProperty(cue, 'size', extend({}, baseObj, {
  11296. get: function get() {
  11297. return _size;
  11298. },
  11299. set: function set(value) {
  11300. if (value < 0 || value > 100) {
  11301. throw new Error('Size must be between 0 and 100.');
  11302. }
  11303. _size = value;
  11304. this.hasBeenReset = true;
  11305. }
  11306. }));
  11307. Object.defineProperty(cue, 'align', extend({}, baseObj, {
  11308. get: function get() {
  11309. return _align;
  11310. },
  11311. set: function set(value) {
  11312. var setting = findAlignSetting(value);
  11313. if (!setting) {
  11314. throw new SyntaxError('An invalid or illegal string was specified.');
  11315. }
  11316. _align = setting;
  11317. this.hasBeenReset = true;
  11318. }
  11319. }));
  11320. /**
  11321. * Other <track> spec defined properties
  11322. */
  11323. // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state
  11324. cue.displayState = undefined;
  11325. if (isIE8) {
  11326. return cue;
  11327. }
  11328. }
  11329. /**
  11330. * VTTCue methods
  11331. */
  11332. VTTCue.prototype.getCueAsHTML = function () {
  11333. // Assume WebVTT.convertCueToDOMTree is on the global.
  11334. var WebVTT = window.WebVTT;
  11335. return WebVTT.convertCueToDOMTree(window, this.text);
  11336. };
  11337. return VTTCue;
  11338. })());
  11339. // CONCATENATED MODULE: ./src/utils/vttparser.js
  11340. /*
  11341. * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js#L1716
  11342. */
  11343. var StringDecoder = function StringDecoder() {
  11344. return {
  11345. decode: function decode(data) {
  11346. if (!data) {
  11347. return '';
  11348. }
  11349. if (typeof data !== 'string') {
  11350. throw new Error('Error - expected string data.');
  11351. }
  11352. return decodeURIComponent(encodeURIComponent(data));
  11353. }
  11354. };
  11355. };
  11356. function VTTParser() {
  11357. this.window = window;
  11358. this.state = 'INITIAL';
  11359. this.buffer = '';
  11360. this.decoder = new StringDecoder();
  11361. this.regionList = [];
  11362. }
  11363. // Try to parse input as a time stamp.
  11364. function parseTimeStamp(input) {
  11365. function computeSeconds(h, m, s, f) {
  11366. return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000;
  11367. }
  11368. var m = input.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/);
  11369. if (!m) {
  11370. return null;
  11371. }
  11372. if (m[3]) {
  11373. // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds]
  11374. return computeSeconds(m[1], m[2], m[3].replace(':', ''), m[4]);
  11375. } else if (m[1] > 59) {
  11376. // Timestamp takes the form of [hours]:[minutes].[milliseconds]
  11377. // First position is hours as it's over 59.
  11378. return computeSeconds(m[1], m[2], 0, m[4]);
  11379. } else {
  11380. // Timestamp takes the form of [minutes]:[seconds].[milliseconds]
  11381. return computeSeconds(0, m[1], m[2], m[4]);
  11382. }
  11383. }
  11384. // A settings object holds key/value pairs and will ignore anything but the first
  11385. // assignment to a specific key.
  11386. function Settings() {
  11387. this.values = Object.create(null);
  11388. }
  11389. Settings.prototype = {
  11390. // Only accept the first assignment to any key.
  11391. set: function set(k, v) {
  11392. if (!this.get(k) && v !== '') {
  11393. this.values[k] = v;
  11394. }
  11395. },
  11396. // Return the value for a key, or a default value.
  11397. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with
  11398. // a number of possible default values as properties where 'defaultKey' is
  11399. // the key of the property that will be chosen; otherwise it's assumed to be
  11400. // a single value.
  11401. get: function get(k, dflt, defaultKey) {
  11402. if (defaultKey) {
  11403. return this.has(k) ? this.values[k] : dflt[defaultKey];
  11404. }
  11405. return this.has(k) ? this.values[k] : dflt;
  11406. },
  11407. // Check whether we have a value for a key.
  11408. has: function has(k) {
  11409. return k in this.values;
  11410. },
  11411. // Accept a setting if its one of the given alternatives.
  11412. alt: function alt(k, v, a) {
  11413. for (var n = 0; n < a.length; ++n) {
  11414. if (v === a[n]) {
  11415. this.set(k, v);
  11416. break;
  11417. }
  11418. }
  11419. },
  11420. // Accept a setting if its a valid (signed) integer.
  11421. integer: function integer(k, v) {
  11422. if (/^-?\d+$/.test(v)) {
  11423. // integer
  11424. this.set(k, parseInt(v, 10));
  11425. }
  11426. },
  11427. // Accept a setting if its a valid percentage.
  11428. percent: function percent(k, v) {
  11429. var m;
  11430. if (m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/)) {
  11431. v = parseFloat(v);
  11432. if (v >= 0 && v <= 100) {
  11433. this.set(k, v);
  11434. return true;
  11435. }
  11436. }
  11437. return false;
  11438. }
  11439. };
  11440. // Helper function to parse input into groups separated by 'groupDelim', and
  11441. // interprete each group as a key/value pair separated by 'keyValueDelim'.
  11442. function parseOptions(input, callback, keyValueDelim, groupDelim) {
  11443. var groups = groupDelim ? input.split(groupDelim) : [input];
  11444. for (var i in groups) {
  11445. if (typeof groups[i] !== 'string') {
  11446. continue;
  11447. }
  11448. var kv = groups[i].split(keyValueDelim);
  11449. if (kv.length !== 2) {
  11450. continue;
  11451. }
  11452. var k = kv[0];
  11453. var v = kv[1];
  11454. callback(k, v);
  11455. }
  11456. }
  11457. var defaults = new vttcue(0, 0, 0);
  11458. // 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244
  11459. // Safari doesn't yet support this change, but FF and Chrome do.
  11460. var center = defaults.align === 'middle' ? 'middle' : 'center';
  11461. function parseCue(input, cue, regionList) {
  11462. // Remember the original input if we need to throw an error.
  11463. var oInput = input;
  11464. // 4.1 WebVTT timestamp
  11465. function consumeTimeStamp() {
  11466. var ts = parseTimeStamp(input);
  11467. if (ts === null) {
  11468. throw new Error('Malformed timestamp: ' + oInput);
  11469. }
  11470. // Remove time stamp from input.
  11471. input = input.replace(/^[^\sa-zA-Z-]+/, '');
  11472. return ts;
  11473. }
  11474. // 4.4.2 WebVTT cue settings
  11475. function consumeCueSettings(input, cue) {
  11476. var settings = new Settings();
  11477. parseOptions(input, function (k, v) {
  11478. switch (k) {
  11479. case 'region':
  11480. // Find the last region we parsed with the same region id.
  11481. for (var i = regionList.length - 1; i >= 0; i--) {
  11482. if (regionList[i].id === v) {
  11483. settings.set(k, regionList[i].region);
  11484. break;
  11485. }
  11486. }
  11487. break;
  11488. case 'vertical':
  11489. settings.alt(k, v, ['rl', 'lr']);
  11490. break;
  11491. case 'line':
  11492. var vals = v.split(','),
  11493. vals0 = vals[0];
  11494. settings.integer(k, vals0);
  11495. if (settings.percent(k, vals0)) {
  11496. settings.set('snapToLines', false);
  11497. }
  11498. settings.alt(k, vals0, ['auto']);
  11499. if (vals.length === 2) {
  11500. settings.alt('lineAlign', vals[1], ['start', center, 'end']);
  11501. }
  11502. break;
  11503. case 'position':
  11504. vals = v.split(',');
  11505. settings.percent(k, vals[0]);
  11506. if (vals.length === 2) {
  11507. settings.alt('positionAlign', vals[1], ['start', center, 'end', 'line-left', 'line-right', 'auto']);
  11508. }
  11509. break;
  11510. case 'size':
  11511. settings.percent(k, v);
  11512. break;
  11513. case 'align':
  11514. settings.alt(k, v, ['start', center, 'end', 'left', 'right']);
  11515. break;
  11516. }
  11517. }, /:/, /\s/);
  11518. // Apply default values for any missing fields.
  11519. cue.region = settings.get('region', null);
  11520. cue.vertical = settings.get('vertical', '');
  11521. var line = settings.get('line', 'auto');
  11522. if (line === 'auto' && defaults.line === -1) {
  11523. // set numeric line number for Safari
  11524. line = -1;
  11525. }
  11526. cue.line = line;
  11527. cue.lineAlign = settings.get('lineAlign', 'start');
  11528. cue.snapToLines = settings.get('snapToLines', true);
  11529. cue.size = settings.get('size', 100);
  11530. cue.align = settings.get('align', center);
  11531. var position = settings.get('position', 'auto');
  11532. if (position === 'auto' && defaults.position === 50) {
  11533. // set numeric position for Safari
  11534. position = cue.align === 'start' || cue.align === 'left' ? 0 : cue.align === 'end' || cue.align === 'right' ? 100 : 50;
  11535. }
  11536. cue.position = position;
  11537. }
  11538. function skipWhitespace() {
  11539. input = input.replace(/^\s+/, '');
  11540. }
  11541. // 4.1 WebVTT cue timings.
  11542. skipWhitespace();
  11543. cue.startTime = consumeTimeStamp(); // (1) collect cue start time
  11544. skipWhitespace();
  11545. if (input.substr(0, 3) !== '-->') {
  11546. // (3) next characters must match '-->'
  11547. throw new Error('Malformed time stamp (time stamps must be separated by \'-->\'): ' + oInput);
  11548. }
  11549. input = input.substr(3);
  11550. skipWhitespace();
  11551. cue.endTime = consumeTimeStamp(); // (5) collect cue end time
  11552. // 4.1 WebVTT cue settings list.
  11553. skipWhitespace();
  11554. consumeCueSettings(input, cue);
  11555. }
  11556. function fixLineBreaks(input) {
  11557. return input.replace(/<br(?: \/)?>/gi, '\n');
  11558. }
  11559. VTTParser.prototype = {
  11560. parse: function parse(data) {
  11561. var self = this;
  11562. // If there is no data then we won't decode it, but will just try to parse
  11563. // whatever is in buffer already. This may occur in circumstances, for
  11564. // example when flush() is called.
  11565. if (data) {
  11566. // Try to decode the data that we received.
  11567. self.buffer += self.decoder.decode(data, { stream: true });
  11568. }
  11569. function collectNextLine() {
  11570. var buffer = self.buffer;
  11571. var pos = 0;
  11572. buffer = fixLineBreaks(buffer);
  11573. while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') {
  11574. ++pos;
  11575. }
  11576. var line = buffer.substr(0, pos);
  11577. // Advance the buffer early in case we fail below.
  11578. if (buffer[pos] === '\r') {
  11579. ++pos;
  11580. }
  11581. if (buffer[pos] === '\n') {
  11582. ++pos;
  11583. }
  11584. self.buffer = buffer.substr(pos);
  11585. return line;
  11586. }
  11587. // 3.2 WebVTT metadata header syntax
  11588. function parseHeader(input) {
  11589. parseOptions(input, function (k, v) {
  11590. switch (k) {
  11591. case 'Region':
  11592. // 3.3 WebVTT region metadata header syntax
  11593. console.log('parse region', v);
  11594. //parseRegion(v);
  11595. break;
  11596. }
  11597. }, /:/);
  11598. }
  11599. // 5.1 WebVTT file parsing.
  11600. try {
  11601. var line;
  11602. if (self.state === 'INITIAL') {
  11603. // We can't start parsing until we have the first line.
  11604. if (!/\r\n|\n/.test(self.buffer)) {
  11605. return this;
  11606. }
  11607. line = collectNextLine();
  11608. // strip of UTF-8 BOM if any
  11609. // https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8
  11610. var m = line.match(/^()?WEBVTT([ \t].*)?$/);
  11611. if (!m || !m[0]) {
  11612. throw new Error('Malformed WebVTT signature.');
  11613. }
  11614. self.state = 'HEADER';
  11615. }
  11616. var alreadyCollectedLine = false;
  11617. while (self.buffer) {
  11618. // We can't parse a line until we have the full line.
  11619. if (!/\r\n|\n/.test(self.buffer)) {
  11620. return this;
  11621. }
  11622. if (!alreadyCollectedLine) {
  11623. line = collectNextLine();
  11624. } else {
  11625. alreadyCollectedLine = false;
  11626. }
  11627. switch (self.state) {
  11628. case 'HEADER':
  11629. // 13-18 - Allow a header (metadata) under the WEBVTT line.
  11630. if (/:/.test(line)) {
  11631. parseHeader(line);
  11632. } else if (!line) {
  11633. // An empty line terminates the header and starts the body (cues).
  11634. self.state = 'ID';
  11635. }
  11636. continue;
  11637. case 'NOTE':
  11638. // Ignore NOTE blocks.
  11639. if (!line) {
  11640. self.state = 'ID';
  11641. }
  11642. continue;
  11643. case 'ID':
  11644. // Check for the start of NOTE blocks.
  11645. if (/^NOTE($|[ \t])/.test(line)) {
  11646. self.state = 'NOTE';
  11647. break;
  11648. }
  11649. // 19-29 - Allow any number of line terminators, then initialize new cue values.
  11650. if (!line) {
  11651. continue;
  11652. }
  11653. self.cue = new vttcue(0, 0, '');
  11654. self.state = 'CUE';
  11655. // 30-39 - Check if self line contains an optional identifier or timing data.
  11656. if (line.indexOf('-->') === -1) {
  11657. self.cue.id = line;
  11658. continue;
  11659. }
  11660. // Process line as start of a cue.
  11661. /*falls through*/
  11662. case 'CUE':
  11663. // 40 - Collect cue timings and settings.
  11664. try {
  11665. parseCue(line, self.cue, self.regionList);
  11666. } catch (e) {
  11667. // In case of an error ignore rest of the cue.
  11668. self.cue = null;
  11669. self.state = 'BADCUE';
  11670. continue;
  11671. }
  11672. self.state = 'CUETEXT';
  11673. continue;
  11674. case 'CUETEXT':
  11675. var hasSubstring = line.indexOf('-->') !== -1;
  11676. // 34 - If we have an empty line then report the cue.
  11677. // 35 - If we have the special substring '-->' then report the cue,
  11678. // but do not collect the line as we need to process the current
  11679. // one as a new cue.
  11680. if (!line || hasSubstring && (alreadyCollectedLine = true)) {
  11681. // We are done parsing self cue.
  11682. if (self.oncue) {
  11683. self.oncue(self.cue);
  11684. }
  11685. self.cue = null;
  11686. self.state = 'ID';
  11687. continue;
  11688. }
  11689. if (self.cue.text) {
  11690. self.cue.text += '\n';
  11691. }
  11692. self.cue.text += line;
  11693. continue;
  11694. case 'BADCUE':
  11695. // BADCUE
  11696. // 54-62 - Collect and discard the remaining cue.
  11697. if (!line) {
  11698. self.state = 'ID';
  11699. }
  11700. continue;
  11701. }
  11702. }
  11703. } catch (e) {
  11704. // If we are currently parsing a cue, report what we have.
  11705. if (self.state === 'CUETEXT' && self.cue && self.oncue) {
  11706. self.oncue(self.cue);
  11707. }
  11708. self.cue = null;
  11709. // Enter BADWEBVTT state if header was not parsed correctly otherwise
  11710. // another exception occurred so enter BADCUE state.
  11711. self.state = self.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE';
  11712. }
  11713. return this;
  11714. },
  11715. flush: function flush() {
  11716. var self = this;
  11717. try {
  11718. // Finish decoding the stream.
  11719. self.buffer += self.decoder.decode();
  11720. // Synthesize the end of the current cue or region.
  11721. if (self.cue || self.state === 'HEADER') {
  11722. self.buffer += '\n\n';
  11723. self.parse();
  11724. }
  11725. // If we've flushed, parsed, and we're still on the INITIAL state then
  11726. // that means we don't have enough of the stream to parse the first
  11727. // line.
  11728. if (self.state === 'INITIAL') {
  11729. throw new Error('Malformed WebVTT signature.');
  11730. }
  11731. } catch (e) {
  11732. throw e;
  11733. }
  11734. if (self.onflush) {
  11735. self.onflush();
  11736. }
  11737. return this;
  11738. }
  11739. };
  11740. /* harmony default export */ var vttparser = (VTTParser);
  11741. // CONCATENATED MODULE: ./src/utils/cues.js
  11742. function newCue(track, startTime, endTime, captionScreen) {
  11743. var row;
  11744. var cue;
  11745. var indenting;
  11746. var indent;
  11747. var text;
  11748. var VTTCue = window.VTTCue || window.TextTrackCue;
  11749. for (var r = 0; r < captionScreen.rows.length; r++) {
  11750. row = captionScreen.rows[r];
  11751. indenting = true;
  11752. indent = 0;
  11753. text = '';
  11754. if (!row.isEmpty()) {
  11755. for (var c = 0; c < row.chars.length; c++) {
  11756. if (row.chars[c].uchar.match(/\s/) && indenting) {
  11757. indent++;
  11758. } else {
  11759. text += row.chars[c].uchar;
  11760. indenting = false;
  11761. }
  11762. }
  11763. //To be used for cleaning-up orphaned roll-up captions
  11764. row.cueStartTime = startTime;
  11765. // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE
  11766. if (startTime === endTime) {
  11767. endTime += 0.0001;
  11768. }
  11769. cue = new VTTCue(startTime, endTime, fixLineBreaks(text.trim()));
  11770. if (indent >= 16) {
  11771. indent--;
  11772. } else {
  11773. indent++;
  11774. }
  11775. // VTTCue.line get's flakey when using controls, so let's now include line 13&14
  11776. // also, drop line 1 since it's to close to the top
  11777. if (navigator.userAgent.match(/Firefox\//)) {
  11778. cue.line = r + 1;
  11779. } else {
  11780. cue.line = r > 7 ? r - 2 : r + 1;
  11781. }
  11782. cue.align = 'left';
  11783. // Clamp the position between 0 and 100 - if out of these bounds, Firefox throws an exception and captions break
  11784. cue.position = Math.max(0, Math.min(100, 100 * (indent / 32) + (navigator.userAgent.match(/Firefox\//) ? 50 : 0)));
  11785. track.addCue(cue);
  11786. }
  11787. }
  11788. }
  11789. // CONCATENATED MODULE: ./src/utils/cea-608-parser.js
  11790. function cea_608_parser__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  11791. /**
  11792. *
  11793. * This code was ported from the dash.js project at:
  11794. * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js
  11795. * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2
  11796. *
  11797. * The original copyright appears below:
  11798. *
  11799. * The copyright in this software is being made available under the BSD License,
  11800. * included below. This software may be subject to other third party and contributor
  11801. * rights, including patent rights, and no such rights are granted under this license.
  11802. *
  11803. * Copyright (c) 2015-2016, DASH Industry Forum.
  11804. * All rights reserved.
  11805. *
  11806. * Redistribution and use in source and binary forms, with or without modification,
  11807. * are permitted provided that the following conditions are met:
  11808. * 1. Redistributions of source code must retain the above copyright notice, this
  11809. * list of conditions and the following disclaimer.
  11810. * * Redistributions in binary form must reproduce the above copyright notice,
  11811. * this list of conditions and the following disclaimer in the documentation and/or
  11812. * other materials provided with the distribution.
  11813. * 2. Neither the name of Dash Industry Forum nor the names of its
  11814. * contributors may be used to endorse or promote products derived from this software
  11815. * without specific prior written permission.
  11816. *
  11817. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
  11818. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  11819. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  11820. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  11821. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  11822. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  11823. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  11824. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  11825. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  11826. * POSSIBILITY OF SUCH DAMAGE.
  11827. */
  11828. /**
  11829. * Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes
  11830. */
  11831. var specialCea608CharsCodes = {
  11832. 0x2a: 0xe1, // lowercase a, acute accent
  11833. 0x5c: 0xe9, // lowercase e, acute accent
  11834. 0x5e: 0xed, // lowercase i, acute accent
  11835. 0x5f: 0xf3, // lowercase o, acute accent
  11836. 0x60: 0xfa, // lowercase u, acute accent
  11837. 0x7b: 0xe7, // lowercase c with cedilla
  11838. 0x7c: 0xf7, // division symbol
  11839. 0x7d: 0xd1, // uppercase N tilde
  11840. 0x7e: 0xf1, // lowercase n tilde
  11841. 0x7f: 0x2588, // Full block
  11842. // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  11843. // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F
  11844. // THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES
  11845. 0x80: 0xae, // Registered symbol (R)
  11846. 0x81: 0xb0, // degree sign
  11847. 0x82: 0xbd, // 1/2 symbol
  11848. 0x83: 0xbf, // Inverted (open) question mark
  11849. 0x84: 0x2122, // Trademark symbol (TM)
  11850. 0x85: 0xa2, // Cents symbol
  11851. 0x86: 0xa3, // Pounds sterling
  11852. 0x87: 0x266a, // Music 8'th note
  11853. 0x88: 0xe0, // lowercase a, grave accent
  11854. 0x89: 0x20, // transparent space (regular)
  11855. 0x8a: 0xe8, // lowercase e, grave accent
  11856. 0x8b: 0xe2, // lowercase a, circumflex accent
  11857. 0x8c: 0xea, // lowercase e, circumflex accent
  11858. 0x8d: 0xee, // lowercase i, circumflex accent
  11859. 0x8e: 0xf4, // lowercase o, circumflex accent
  11860. 0x8f: 0xfb, // lowercase u, circumflex accent
  11861. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  11862. // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F
  11863. 0x90: 0xc1, // capital letter A with acute
  11864. 0x91: 0xc9, // capital letter E with acute
  11865. 0x92: 0xd3, // capital letter O with acute
  11866. 0x93: 0xda, // capital letter U with acute
  11867. 0x94: 0xdc, // capital letter U with diaresis
  11868. 0x95: 0xfc, // lowercase letter U with diaeresis
  11869. 0x96: 0x2018, // opening single quote
  11870. 0x97: 0xa1, // inverted exclamation mark
  11871. 0x98: 0x2a, // asterisk
  11872. 0x99: 0x2019, // closing single quote
  11873. 0x9a: 0x2501, // box drawings heavy horizontal
  11874. 0x9b: 0xa9, // copyright sign
  11875. 0x9c: 0x2120, // Service mark
  11876. 0x9d: 0x2022, // (round) bullet
  11877. 0x9e: 0x201c, // Left double quotation mark
  11878. 0x9f: 0x201d, // Right double quotation mark
  11879. 0xa0: 0xc0, // uppercase A, grave accent
  11880. 0xa1: 0xc2, // uppercase A, circumflex
  11881. 0xa2: 0xc7, // uppercase C with cedilla
  11882. 0xa3: 0xc8, // uppercase E, grave accent
  11883. 0xa4: 0xca, // uppercase E, circumflex
  11884. 0xa5: 0xcb, // capital letter E with diaresis
  11885. 0xa6: 0xeb, // lowercase letter e with diaresis
  11886. 0xa7: 0xce, // uppercase I, circumflex
  11887. 0xa8: 0xcf, // uppercase I, with diaresis
  11888. 0xa9: 0xef, // lowercase i, with diaresis
  11889. 0xaa: 0xd4, // uppercase O, circumflex
  11890. 0xab: 0xd9, // uppercase U, grave accent
  11891. 0xac: 0xf9, // lowercase u, grave accent
  11892. 0xad: 0xdb, // uppercase U, circumflex
  11893. 0xae: 0xab, // left-pointing double angle quotation mark
  11894. 0xaf: 0xbb, // right-pointing double angle quotation mark
  11895. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  11896. // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F
  11897. 0xb0: 0xc3, // Uppercase A, tilde
  11898. 0xb1: 0xe3, // Lowercase a, tilde
  11899. 0xb2: 0xcd, // Uppercase I, acute accent
  11900. 0xb3: 0xcc, // Uppercase I, grave accent
  11901. 0xb4: 0xec, // Lowercase i, grave accent
  11902. 0xb5: 0xd2, // Uppercase O, grave accent
  11903. 0xb6: 0xf2, // Lowercase o, grave accent
  11904. 0xb7: 0xd5, // Uppercase O, tilde
  11905. 0xb8: 0xf5, // Lowercase o, tilde
  11906. 0xb9: 0x7b, // Open curly brace
  11907. 0xba: 0x7d, // Closing curly brace
  11908. 0xbb: 0x5c, // Backslash
  11909. 0xbc: 0x5e, // Caret
  11910. 0xbd: 0x5f, // Underscore
  11911. 0xbe: 0x7c, // Pipe (vertical line)
  11912. 0xbf: 0x223c, // Tilde operator
  11913. 0xc0: 0xc4, // Uppercase A, umlaut
  11914. 0xc1: 0xe4, // Lowercase A, umlaut
  11915. 0xc2: 0xd6, // Uppercase O, umlaut
  11916. 0xc3: 0xf6, // Lowercase o, umlaut
  11917. 0xc4: 0xdf, // Esszett (sharp S)
  11918. 0xc5: 0xa5, // Yen symbol
  11919. 0xc6: 0xa4, // Generic currency sign
  11920. 0xc7: 0x2503, // Box drawings heavy vertical
  11921. 0xc8: 0xc5, // Uppercase A, ring
  11922. 0xc9: 0xe5, // Lowercase A, ring
  11923. 0xca: 0xd8, // Uppercase O, stroke
  11924. 0xcb: 0xf8, // Lowercase o, strok
  11925. 0xcc: 0x250f, // Box drawings heavy down and right
  11926. 0xcd: 0x2513, // Box drawings heavy down and left
  11927. 0xce: 0x2517, // Box drawings heavy up and right
  11928. 0xcf: 0x251b // Box drawings heavy up and left
  11929. };
  11930. /**
  11931. * Utils
  11932. */
  11933. var getCharForByte = function getCharForByte(byte) {
  11934. var charCode = byte;
  11935. if (specialCea608CharsCodes.hasOwnProperty(byte)) {
  11936. charCode = specialCea608CharsCodes[byte];
  11937. }
  11938. return String.fromCharCode(charCode);
  11939. };
  11940. var NR_ROWS = 15,
  11941. NR_COLS = 100;
  11942. // Tables to look up row from PAC data
  11943. var rowsLowCh1 = { 0x11: 1, 0x12: 3, 0x15: 5, 0x16: 7, 0x17: 9, 0x10: 11, 0x13: 12, 0x14: 14 };
  11944. var rowsHighCh1 = { 0x11: 2, 0x12: 4, 0x15: 6, 0x16: 8, 0x17: 10, 0x13: 13, 0x14: 15 };
  11945. var rowsLowCh2 = { 0x19: 1, 0x1A: 3, 0x1D: 5, 0x1E: 7, 0x1F: 9, 0x18: 11, 0x1B: 12, 0x1C: 14 };
  11946. var rowsHighCh2 = { 0x19: 2, 0x1A: 4, 0x1D: 6, 0x1E: 8, 0x1F: 10, 0x1B: 13, 0x1C: 15 };
  11947. var backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent'];
  11948. /**
  11949. * Simple logger class to be able to write with time-stamps and filter on level.
  11950. */
  11951. var cea_608_parser_logger = {
  11952. verboseFilter: { 'DATA': 3, 'DEBUG': 3, 'INFO': 2, 'WARNING': 2, 'TEXT': 1, 'ERROR': 0 },
  11953. time: null,
  11954. verboseLevel: 0, // Only write errors
  11955. setTime: function setTime(newTime) {
  11956. this.time = newTime;
  11957. },
  11958. log: function log(severity, msg) {
  11959. var minLevel = this.verboseFilter[severity];
  11960. if (this.verboseLevel >= minLevel) {
  11961. console.log(this.time + ' [' + severity + '] ' + msg);
  11962. }
  11963. }
  11964. };
  11965. var numArrayToHexArray = function numArrayToHexArray(numArray) {
  11966. var hexArray = [];
  11967. for (var j = 0; j < numArray.length; j++) {
  11968. hexArray.push(numArray[j].toString(16));
  11969. }
  11970. return hexArray;
  11971. };
  11972. var PenState = function () {
  11973. function PenState(foreground, underline, italics, background, flash) {
  11974. cea_608_parser__classCallCheck(this, PenState);
  11975. this.foreground = foreground || 'white';
  11976. this.underline = underline || false;
  11977. this.italics = italics || false;
  11978. this.background = background || 'black';
  11979. this.flash = flash || false;
  11980. }
  11981. PenState.prototype.reset = function reset() {
  11982. this.foreground = 'white';
  11983. this.underline = false;
  11984. this.italics = false;
  11985. this.background = 'black';
  11986. this.flash = false;
  11987. };
  11988. PenState.prototype.setStyles = function setStyles(styles) {
  11989. var attribs = ['foreground', 'underline', 'italics', 'background', 'flash'];
  11990. for (var i = 0; i < attribs.length; i++) {
  11991. var style = attribs[i];
  11992. if (styles.hasOwnProperty(style)) {
  11993. this[style] = styles[style];
  11994. }
  11995. }
  11996. };
  11997. PenState.prototype.isDefault = function isDefault() {
  11998. return this.foreground === 'white' && !this.underline && !this.italics && this.background === 'black' && !this.flash;
  11999. };
  12000. PenState.prototype.equals = function equals(other) {
  12001. return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash;
  12002. };
  12003. PenState.prototype.copy = function copy(newPenState) {
  12004. this.foreground = newPenState.foreground;
  12005. this.underline = newPenState.underline;
  12006. this.italics = newPenState.italics;
  12007. this.background = newPenState.background;
  12008. this.flash = newPenState.flash;
  12009. };
  12010. PenState.prototype.toString = function toString() {
  12011. return 'color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics + ', background=' + this.background + ', flash=' + this.flash;
  12012. };
  12013. return PenState;
  12014. }();
  12015. /**
  12016. * Unicode character with styling and background.
  12017. * @constructor
  12018. */
  12019. var StyledUnicodeChar = function () {
  12020. function StyledUnicodeChar(uchar, foreground, underline, italics, background, flash) {
  12021. cea_608_parser__classCallCheck(this, StyledUnicodeChar);
  12022. this.uchar = uchar || ' '; // unicode character
  12023. this.penState = new PenState(foreground, underline, italics, background, flash);
  12024. }
  12025. StyledUnicodeChar.prototype.reset = function reset() {
  12026. this.uchar = ' ';
  12027. this.penState.reset();
  12028. };
  12029. StyledUnicodeChar.prototype.setChar = function setChar(uchar, newPenState) {
  12030. this.uchar = uchar;
  12031. this.penState.copy(newPenState);
  12032. };
  12033. StyledUnicodeChar.prototype.setPenState = function setPenState(newPenState) {
  12034. this.penState.copy(newPenState);
  12035. };
  12036. StyledUnicodeChar.prototype.equals = function equals(other) {
  12037. return this.uchar === other.uchar && this.penState.equals(other.penState);
  12038. };
  12039. StyledUnicodeChar.prototype.copy = function copy(newChar) {
  12040. this.uchar = newChar.uchar;
  12041. this.penState.copy(newChar.penState);
  12042. };
  12043. StyledUnicodeChar.prototype.isEmpty = function isEmpty() {
  12044. return this.uchar === ' ' && this.penState.isDefault();
  12045. };
  12046. return StyledUnicodeChar;
  12047. }();
  12048. /**
  12049. * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.
  12050. * @constructor
  12051. */
  12052. var Row = function () {
  12053. function Row() {
  12054. cea_608_parser__classCallCheck(this, Row);
  12055. this.chars = [];
  12056. for (var i = 0; i < NR_COLS; i++) {
  12057. this.chars.push(new StyledUnicodeChar());
  12058. }
  12059. this.pos = 0;
  12060. this.currPenState = new PenState();
  12061. }
  12062. Row.prototype.equals = function equals(other) {
  12063. var equal = true;
  12064. for (var i = 0; i < NR_COLS; i++) {
  12065. if (!this.chars[i].equals(other.chars[i])) {
  12066. equal = false;
  12067. break;
  12068. }
  12069. }
  12070. return equal;
  12071. };
  12072. Row.prototype.copy = function copy(other) {
  12073. for (var i = 0; i < NR_COLS; i++) {
  12074. this.chars[i].copy(other.chars[i]);
  12075. }
  12076. };
  12077. Row.prototype.isEmpty = function isEmpty() {
  12078. var empty = true;
  12079. for (var i = 0; i < NR_COLS; i++) {
  12080. if (!this.chars[i].isEmpty()) {
  12081. empty = false;
  12082. break;
  12083. }
  12084. }
  12085. return empty;
  12086. };
  12087. /**
  12088. * Set the cursor to a valid column.
  12089. */
  12090. Row.prototype.setCursor = function setCursor(absPos) {
  12091. if (this.pos !== absPos) {
  12092. this.pos = absPos;
  12093. }
  12094. if (this.pos < 0) {
  12095. cea_608_parser_logger.log('ERROR', 'Negative cursor position ' + this.pos);
  12096. this.pos = 0;
  12097. } else if (this.pos > NR_COLS) {
  12098. cea_608_parser_logger.log('ERROR', 'Too large cursor position ' + this.pos);
  12099. this.pos = NR_COLS;
  12100. }
  12101. };
  12102. /**
  12103. * Move the cursor relative to current position.
  12104. */
  12105. Row.prototype.moveCursor = function moveCursor(relPos) {
  12106. var newPos = this.pos + relPos;
  12107. if (relPos > 1) {
  12108. for (var i = this.pos + 1; i < newPos + 1; i++) {
  12109. this.chars[i].setPenState(this.currPenState);
  12110. }
  12111. }
  12112. this.setCursor(newPos);
  12113. };
  12114. /**
  12115. * Backspace, move one step back and clear character.
  12116. */
  12117. Row.prototype.backSpace = function backSpace() {
  12118. this.moveCursor(-1);
  12119. this.chars[this.pos].setChar(' ', this.currPenState);
  12120. };
  12121. Row.prototype.insertChar = function insertChar(byte) {
  12122. if (byte >= 0x90) {
  12123. //Extended char
  12124. this.backSpace();
  12125. }
  12126. var char = getCharForByte(byte);
  12127. if (this.pos >= NR_COLS) {
  12128. cea_608_parser_logger.log('ERROR', 'Cannot insert ' + byte.toString(16) + ' (' + char + ') at position ' + this.pos + '. Skipping it!');
  12129. return;
  12130. }
  12131. this.chars[this.pos].setChar(char, this.currPenState);
  12132. this.moveCursor(1);
  12133. };
  12134. Row.prototype.clearFromPos = function clearFromPos(startPos) {
  12135. var i;
  12136. for (i = startPos; i < NR_COLS; i++) {
  12137. this.chars[i].reset();
  12138. }
  12139. };
  12140. Row.prototype.clear = function clear() {
  12141. this.clearFromPos(0);
  12142. this.pos = 0;
  12143. this.currPenState.reset();
  12144. };
  12145. Row.prototype.clearToEndOfRow = function clearToEndOfRow() {
  12146. this.clearFromPos(this.pos);
  12147. };
  12148. Row.prototype.getTextString = function getTextString() {
  12149. var chars = [];
  12150. var empty = true;
  12151. for (var i = 0; i < NR_COLS; i++) {
  12152. var char = this.chars[i].uchar;
  12153. if (char !== ' ') {
  12154. empty = false;
  12155. }
  12156. chars.push(char);
  12157. }
  12158. if (empty) {
  12159. return '';
  12160. } else {
  12161. return chars.join('');
  12162. }
  12163. };
  12164. Row.prototype.setPenStyles = function setPenStyles(styles) {
  12165. this.currPenState.setStyles(styles);
  12166. var currChar = this.chars[this.pos];
  12167. currChar.setPenState(this.currPenState);
  12168. };
  12169. return Row;
  12170. }();
  12171. /**
  12172. * Keep a CEA-608 screen of 32x15 styled characters
  12173. * @constructor
  12174. */
  12175. var CaptionScreen = function () {
  12176. function CaptionScreen() {
  12177. cea_608_parser__classCallCheck(this, CaptionScreen);
  12178. this.rows = [];
  12179. for (var i = 0; i < NR_ROWS; i++) {
  12180. this.rows.push(new Row()); // Note that we use zero-based numbering (0-14)
  12181. }
  12182. this.currRow = NR_ROWS - 1;
  12183. this.nrRollUpRows = null;
  12184. this.reset();
  12185. }
  12186. CaptionScreen.prototype.reset = function reset() {
  12187. for (var i = 0; i < NR_ROWS; i++) {
  12188. this.rows[i].clear();
  12189. }
  12190. this.currRow = NR_ROWS - 1;
  12191. };
  12192. CaptionScreen.prototype.equals = function equals(other) {
  12193. var equal = true;
  12194. for (var i = 0; i < NR_ROWS; i++) {
  12195. if (!this.rows[i].equals(other.rows[i])) {
  12196. equal = false;
  12197. break;
  12198. }
  12199. }
  12200. return equal;
  12201. };
  12202. CaptionScreen.prototype.copy = function copy(other) {
  12203. for (var i = 0; i < NR_ROWS; i++) {
  12204. this.rows[i].copy(other.rows[i]);
  12205. }
  12206. };
  12207. CaptionScreen.prototype.isEmpty = function isEmpty() {
  12208. var empty = true;
  12209. for (var i = 0; i < NR_ROWS; i++) {
  12210. if (!this.rows[i].isEmpty()) {
  12211. empty = false;
  12212. break;
  12213. }
  12214. }
  12215. return empty;
  12216. };
  12217. CaptionScreen.prototype.backSpace = function backSpace() {
  12218. var row = this.rows[this.currRow];
  12219. row.backSpace();
  12220. };
  12221. CaptionScreen.prototype.clearToEndOfRow = function clearToEndOfRow() {
  12222. var row = this.rows[this.currRow];
  12223. row.clearToEndOfRow();
  12224. };
  12225. /**
  12226. * Insert a character (without styling) in the current row.
  12227. */
  12228. CaptionScreen.prototype.insertChar = function insertChar(char) {
  12229. var row = this.rows[this.currRow];
  12230. row.insertChar(char);
  12231. };
  12232. CaptionScreen.prototype.setPen = function setPen(styles) {
  12233. var row = this.rows[this.currRow];
  12234. row.setPenStyles(styles);
  12235. };
  12236. CaptionScreen.prototype.moveCursor = function moveCursor(relPos) {
  12237. var row = this.rows[this.currRow];
  12238. row.moveCursor(relPos);
  12239. };
  12240. CaptionScreen.prototype.setCursor = function setCursor(absPos) {
  12241. cea_608_parser_logger.log('INFO', 'setCursor: ' + absPos);
  12242. var row = this.rows[this.currRow];
  12243. row.setCursor(absPos);
  12244. };
  12245. CaptionScreen.prototype.setPAC = function setPAC(pacData) {
  12246. cea_608_parser_logger.log('INFO', 'pacData = ' + JSON.stringify(pacData));
  12247. var newRow = pacData.row - 1;
  12248. if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {
  12249. newRow = this.nrRollUpRows - 1;
  12250. }
  12251. //Make sure this only affects Roll-up Captions by checking this.nrRollUpRows
  12252. if (this.nrRollUpRows && this.currRow !== newRow) {
  12253. //clear all rows first
  12254. for (var i = 0; i < NR_ROWS; i++) {
  12255. this.rows[i].clear();
  12256. }
  12257. //Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location
  12258. //topRowIndex - the start of rows to copy (inclusive index)
  12259. var topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  12260. //We only copy if the last position was already shown.
  12261. //We use the cueStartTime value to check this.
  12262. var lastOutputScreen = this.lastOutputScreen;
  12263. if (lastOutputScreen) {
  12264. var prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;
  12265. if (prevLineTime && prevLineTime < cea_608_parser_logger.time) {
  12266. for (var _i = 0; _i < this.nrRollUpRows; _i++) {
  12267. this.rows[newRow - this.nrRollUpRows + _i + 1].copy(lastOutputScreen.rows[topRowIndex + _i]);
  12268. }
  12269. }
  12270. }
  12271. }
  12272. this.currRow = newRow;
  12273. var row = this.rows[this.currRow];
  12274. if (pacData.indent !== null) {
  12275. var indent = pacData.indent;
  12276. var prevPos = Math.max(indent - 1, 0);
  12277. row.setCursor(pacData.indent);
  12278. pacData.color = row.chars[prevPos].penState.foreground;
  12279. }
  12280. var styles = { foreground: pacData.color, underline: pacData.underline, italics: pacData.italics, background: 'black', flash: false };
  12281. this.setPen(styles);
  12282. };
  12283. /**
  12284. * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).
  12285. */
  12286. CaptionScreen.prototype.setBkgData = function setBkgData(bkgData) {
  12287. cea_608_parser_logger.log('INFO', 'bkgData = ' + JSON.stringify(bkgData));
  12288. this.backSpace();
  12289. this.setPen(bkgData);
  12290. this.insertChar(0x20); //Space
  12291. };
  12292. CaptionScreen.prototype.setRollUpRows = function setRollUpRows(nrRows) {
  12293. this.nrRollUpRows = nrRows;
  12294. };
  12295. CaptionScreen.prototype.rollUp = function rollUp() {
  12296. if (this.nrRollUpRows === null) {
  12297. cea_608_parser_logger.log('DEBUG', 'roll_up but nrRollUpRows not set yet');
  12298. return; //Not properly setup
  12299. }
  12300. cea_608_parser_logger.log('TEXT', this.getDisplayText());
  12301. var topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  12302. var topRow = this.rows.splice(topRowIndex, 1)[0];
  12303. topRow.clear();
  12304. this.rows.splice(this.currRow, 0, topRow);
  12305. cea_608_parser_logger.log('INFO', 'Rolling up');
  12306. //logger.log('TEXT', this.get_display_text())
  12307. };
  12308. /**
  12309. * Get all non-empty rows with as unicode text.
  12310. */
  12311. CaptionScreen.prototype.getDisplayText = function getDisplayText(asOneRow) {
  12312. asOneRow = asOneRow || false;
  12313. var displayText = [];
  12314. var text = '';
  12315. var rowNr = -1;
  12316. for (var i = 0; i < NR_ROWS; i++) {
  12317. var rowText = this.rows[i].getTextString();
  12318. if (rowText) {
  12319. rowNr = i + 1;
  12320. if (asOneRow) {
  12321. displayText.push('Row ' + rowNr + ': \'' + rowText + '\'');
  12322. } else {
  12323. displayText.push(rowText.trim());
  12324. }
  12325. }
  12326. }
  12327. if (displayText.length > 0) {
  12328. if (asOneRow) {
  12329. text = '[' + displayText.join(' | ') + ']';
  12330. } else {
  12331. text = displayText.join('\n');
  12332. }
  12333. }
  12334. return text;
  12335. };
  12336. CaptionScreen.prototype.getTextAndFormat = function getTextAndFormat() {
  12337. return this.rows;
  12338. };
  12339. return CaptionScreen;
  12340. }();
  12341. //var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];
  12342. var Cea608Channel = function () {
  12343. function Cea608Channel(channelNumber, outputFilter) {
  12344. cea_608_parser__classCallCheck(this, Cea608Channel);
  12345. this.chNr = channelNumber;
  12346. this.outputFilter = outputFilter;
  12347. this.mode = null;
  12348. this.verbose = 0;
  12349. this.displayedMemory = new CaptionScreen();
  12350. this.nonDisplayedMemory = new CaptionScreen();
  12351. this.lastOutputScreen = new CaptionScreen();
  12352. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  12353. this.writeScreen = this.displayedMemory;
  12354. this.mode = null;
  12355. this.cueStartTime = null; // Keeps track of where a cue started.
  12356. }
  12357. Cea608Channel.prototype.reset = function reset() {
  12358. this.mode = null;
  12359. this.displayedMemory.reset();
  12360. this.nonDisplayedMemory.reset();
  12361. this.lastOutputScreen.reset();
  12362. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  12363. this.writeScreen = this.displayedMemory;
  12364. this.mode = null;
  12365. this.cueStartTime = null;
  12366. this.lastCueEndTime = null;
  12367. };
  12368. Cea608Channel.prototype.getHandler = function getHandler() {
  12369. return this.outputFilter;
  12370. };
  12371. Cea608Channel.prototype.setHandler = function setHandler(newHandler) {
  12372. this.outputFilter = newHandler;
  12373. };
  12374. Cea608Channel.prototype.setPAC = function setPAC(pacData) {
  12375. this.writeScreen.setPAC(pacData);
  12376. };
  12377. Cea608Channel.prototype.setBkgData = function setBkgData(bkgData) {
  12378. this.writeScreen.setBkgData(bkgData);
  12379. };
  12380. Cea608Channel.prototype.setMode = function setMode(newMode) {
  12381. if (newMode === this.mode) {
  12382. return;
  12383. }
  12384. this.mode = newMode;
  12385. cea_608_parser_logger.log('INFO', 'MODE=' + newMode);
  12386. if (this.mode === 'MODE_POP-ON') {
  12387. this.writeScreen = this.nonDisplayedMemory;
  12388. } else {
  12389. this.writeScreen = this.displayedMemory;
  12390. this.writeScreen.reset();
  12391. }
  12392. if (this.mode !== 'MODE_ROLL-UP') {
  12393. this.displayedMemory.nrRollUpRows = null;
  12394. this.nonDisplayedMemory.nrRollUpRows = null;
  12395. }
  12396. this.mode = newMode;
  12397. };
  12398. Cea608Channel.prototype.insertChars = function insertChars(chars) {
  12399. for (var i = 0; i < chars.length; i++) {
  12400. this.writeScreen.insertChar(chars[i]);
  12401. }
  12402. var screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP';
  12403. cea_608_parser_logger.log('INFO', screen + ': ' + this.writeScreen.getDisplayText(true));
  12404. if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {
  12405. cea_608_parser_logger.log('TEXT', 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true));
  12406. this.outputDataUpdate();
  12407. }
  12408. };
  12409. Cea608Channel.prototype.ccRCL = function ccRCL() {
  12410. // Resume Caption Loading (switch mode to Pop On)
  12411. cea_608_parser_logger.log('INFO', 'RCL - Resume Caption Loading');
  12412. this.setMode('MODE_POP-ON');
  12413. };
  12414. Cea608Channel.prototype.ccBS = function ccBS() {
  12415. // BackSpace
  12416. cea_608_parser_logger.log('INFO', 'BS - BackSpace');
  12417. if (this.mode === 'MODE_TEXT') {
  12418. return;
  12419. }
  12420. this.writeScreen.backSpace();
  12421. if (this.writeScreen === this.displayedMemory) {
  12422. this.outputDataUpdate();
  12423. }
  12424. };
  12425. Cea608Channel.prototype.ccAOF = function ccAOF() {
  12426. // Reserved (formerly Alarm Off)
  12427. return;
  12428. };
  12429. Cea608Channel.prototype.ccAON = function ccAON() {
  12430. // Reserved (formerly Alarm On)
  12431. return;
  12432. };
  12433. Cea608Channel.prototype.ccDER = function ccDER() {
  12434. // Delete to End of Row
  12435. cea_608_parser_logger.log('INFO', 'DER- Delete to End of Row');
  12436. this.writeScreen.clearToEndOfRow();
  12437. this.outputDataUpdate();
  12438. };
  12439. Cea608Channel.prototype.ccRU = function ccRU(nrRows) {
  12440. //Roll-Up Captions-2,3,or 4 Rows
  12441. cea_608_parser_logger.log('INFO', 'RU(' + nrRows + ') - Roll Up');
  12442. this.writeScreen = this.displayedMemory;
  12443. this.setMode('MODE_ROLL-UP');
  12444. this.writeScreen.setRollUpRows(nrRows);
  12445. };
  12446. Cea608Channel.prototype.ccFON = function ccFON() {
  12447. //Flash On
  12448. cea_608_parser_logger.log('INFO', 'FON - Flash On');
  12449. this.writeScreen.setPen({ flash: true });
  12450. };
  12451. Cea608Channel.prototype.ccRDC = function ccRDC() {
  12452. // Resume Direct Captioning (switch mode to PaintOn)
  12453. cea_608_parser_logger.log('INFO', 'RDC - Resume Direct Captioning');
  12454. this.setMode('MODE_PAINT-ON');
  12455. };
  12456. Cea608Channel.prototype.ccTR = function ccTR() {
  12457. // Text Restart in text mode (not supported, however)
  12458. cea_608_parser_logger.log('INFO', 'TR');
  12459. this.setMode('MODE_TEXT');
  12460. };
  12461. Cea608Channel.prototype.ccRTD = function ccRTD() {
  12462. // Resume Text Display in Text mode (not supported, however)
  12463. cea_608_parser_logger.log('INFO', 'RTD');
  12464. this.setMode('MODE_TEXT');
  12465. };
  12466. Cea608Channel.prototype.ccEDM = function ccEDM() {
  12467. // Erase Displayed Memory
  12468. cea_608_parser_logger.log('INFO', 'EDM - Erase Displayed Memory');
  12469. this.displayedMemory.reset();
  12470. this.outputDataUpdate(true);
  12471. };
  12472. Cea608Channel.prototype.ccCR = function ccCR() {
  12473. // Carriage Return
  12474. cea_608_parser_logger.log('CR - Carriage Return');
  12475. this.writeScreen.rollUp();
  12476. this.outputDataUpdate(true);
  12477. };
  12478. Cea608Channel.prototype.ccENM = function ccENM() {
  12479. //Erase Non-Displayed Memory
  12480. cea_608_parser_logger.log('INFO', 'ENM - Erase Non-displayed Memory');
  12481. this.nonDisplayedMemory.reset();
  12482. };
  12483. Cea608Channel.prototype.ccEOC = function ccEOC() {
  12484. //End of Caption (Flip Memories)
  12485. cea_608_parser_logger.log('INFO', 'EOC - End Of Caption');
  12486. if (this.mode === 'MODE_POP-ON') {
  12487. var tmp = this.displayedMemory;
  12488. this.displayedMemory = this.nonDisplayedMemory;
  12489. this.nonDisplayedMemory = tmp;
  12490. this.writeScreen = this.nonDisplayedMemory;
  12491. cea_608_parser_logger.log('TEXT', 'DISP: ' + this.displayedMemory.getDisplayText());
  12492. }
  12493. this.outputDataUpdate(true);
  12494. };
  12495. Cea608Channel.prototype.ccTO = function ccTO(nrCols) {
  12496. // Tab Offset 1,2, or 3 columns
  12497. cea_608_parser_logger.log('INFO', 'TO(' + nrCols + ') - Tab Offset');
  12498. this.writeScreen.moveCursor(nrCols);
  12499. };
  12500. Cea608Channel.prototype.ccMIDROW = function ccMIDROW(secondByte) {
  12501. // Parse MIDROW command
  12502. var styles = { flash: false };
  12503. styles.underline = secondByte % 2 === 1;
  12504. styles.italics = secondByte >= 0x2e;
  12505. if (!styles.italics) {
  12506. var colorIndex = Math.floor(secondByte / 2) - 0x10;
  12507. var colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta'];
  12508. styles.foreground = colors[colorIndex];
  12509. } else {
  12510. styles.foreground = 'white';
  12511. }
  12512. cea_608_parser_logger.log('INFO', 'MIDROW: ' + JSON.stringify(styles));
  12513. this.writeScreen.setPen(styles);
  12514. };
  12515. Cea608Channel.prototype.outputDataUpdate = function outputDataUpdate() {
  12516. var dispatch = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  12517. var t = cea_608_parser_logger.time;
  12518. if (t === null) {
  12519. return;
  12520. }
  12521. if (this.outputFilter) {
  12522. if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {
  12523. // Start of a new cue
  12524. this.cueStartTime = t;
  12525. } else {
  12526. if (!this.displayedMemory.equals(this.lastOutputScreen)) {
  12527. if (this.outputFilter.newCue) {
  12528. this.outputFilter.newCue(this.cueStartTime, t, this.lastOutputScreen);
  12529. if (dispatch === true && this.outputFilter.dispatchCue) {
  12530. this.outputFilter.dispatchCue();
  12531. }
  12532. }
  12533. this.cueStartTime = this.displayedMemory.isEmpty() ? null : t;
  12534. }
  12535. }
  12536. this.lastOutputScreen.copy(this.displayedMemory);
  12537. }
  12538. };
  12539. Cea608Channel.prototype.cueSplitAtTime = function cueSplitAtTime(t) {
  12540. if (this.outputFilter) {
  12541. if (!this.displayedMemory.isEmpty()) {
  12542. if (this.outputFilter.newCue) {
  12543. this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory);
  12544. }
  12545. this.cueStartTime = t;
  12546. }
  12547. }
  12548. };
  12549. return Cea608Channel;
  12550. }();
  12551. var Cea608Parser = function () {
  12552. function Cea608Parser(field, out1, out2) {
  12553. cea_608_parser__classCallCheck(this, Cea608Parser);
  12554. this.field = field || 1;
  12555. this.outputs = [out1, out2];
  12556. this.channels = [new Cea608Channel(1, out1), new Cea608Channel(2, out2)];
  12557. this.currChNr = -1; // Will be 1 or 2
  12558. this.lastCmdA = null; // First byte of last command
  12559. this.lastCmdB = null; // Second byte of last command
  12560. this.bufferedData = [];
  12561. this.startTime = null;
  12562. this.lastTime = null;
  12563. this.dataCounters = { 'padding': 0, 'char': 0, 'cmd': 0, 'other': 0 };
  12564. }
  12565. Cea608Parser.prototype.getHandler = function getHandler(index) {
  12566. return this.channels[index].getHandler();
  12567. };
  12568. Cea608Parser.prototype.setHandler = function setHandler(index, newHandler) {
  12569. this.channels[index].setHandler(newHandler);
  12570. };
  12571. /**
  12572. * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.
  12573. */
  12574. Cea608Parser.prototype.addData = function addData(t, byteList) {
  12575. var cmdFound,
  12576. a,
  12577. b,
  12578. charsFound = false;
  12579. this.lastTime = t;
  12580. cea_608_parser_logger.setTime(t);
  12581. for (var i = 0; i < byteList.length; i += 2) {
  12582. a = byteList[i] & 0x7f;
  12583. b = byteList[i + 1] & 0x7f;
  12584. if (a === 0 && b === 0) {
  12585. this.dataCounters.padding += 2;
  12586. continue;
  12587. } else {
  12588. cea_608_parser_logger.log('DATA', '[' + numArrayToHexArray([byteList[i], byteList[i + 1]]) + '] -> (' + numArrayToHexArray([a, b]) + ')');
  12589. }
  12590. cmdFound = this.parseCmd(a, b);
  12591. if (!cmdFound) {
  12592. cmdFound = this.parseMidrow(a, b);
  12593. }
  12594. if (!cmdFound) {
  12595. cmdFound = this.parsePAC(a, b);
  12596. }
  12597. if (!cmdFound) {
  12598. cmdFound = this.parseBackgroundAttributes(a, b);
  12599. }
  12600. if (!cmdFound) {
  12601. charsFound = this.parseChars(a, b);
  12602. if (charsFound) {
  12603. if (this.currChNr && this.currChNr >= 0) {
  12604. var channel = this.channels[this.currChNr - 1];
  12605. channel.insertChars(charsFound);
  12606. } else {
  12607. cea_608_parser_logger.log('WARNING', 'No channel found yet. TEXT-MODE?');
  12608. }
  12609. }
  12610. }
  12611. if (cmdFound) {
  12612. this.dataCounters.cmd += 2;
  12613. } else if (charsFound) {
  12614. this.dataCounters.char += 2;
  12615. } else {
  12616. this.dataCounters.other += 2;
  12617. cea_608_parser_logger.log('WARNING', 'Couldn\'t parse cleaned data ' + numArrayToHexArray([a, b]) + ' orig: ' + numArrayToHexArray([byteList[i], byteList[i + 1]]));
  12618. }
  12619. }
  12620. };
  12621. /**
  12622. * Parse Command.
  12623. * @returns {Boolean} Tells if a command was found
  12624. */
  12625. Cea608Parser.prototype.parseCmd = function parseCmd(a, b) {
  12626. var chNr = null;
  12627. var cond1 = (a === 0x14 || a === 0x1C) && 0x20 <= b && b <= 0x2F;
  12628. var cond2 = (a === 0x17 || a === 0x1F) && 0x21 <= b && b <= 0x23;
  12629. if (!(cond1 || cond2)) {
  12630. return false;
  12631. }
  12632. if (a === this.lastCmdA && b === this.lastCmdB) {
  12633. this.lastCmdA = null;
  12634. this.lastCmdB = null; // Repeated commands are dropped (once)
  12635. cea_608_parser_logger.log('DEBUG', 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped');
  12636. return true;
  12637. }
  12638. if (a === 0x14 || a === 0x17) {
  12639. chNr = 1;
  12640. } else {
  12641. chNr = 2; // (a === 0x1C || a=== 0x1f)
  12642. }
  12643. var channel = this.channels[chNr - 1];
  12644. if (a === 0x14 || a === 0x1C) {
  12645. if (b === 0x20) {
  12646. channel.ccRCL();
  12647. } else if (b === 0x21) {
  12648. channel.ccBS();
  12649. } else if (b === 0x22) {
  12650. channel.ccAOF();
  12651. } else if (b === 0x23) {
  12652. channel.ccAON();
  12653. } else if (b === 0x24) {
  12654. channel.ccDER();
  12655. } else if (b === 0x25) {
  12656. channel.ccRU(2);
  12657. } else if (b === 0x26) {
  12658. channel.ccRU(3);
  12659. } else if (b === 0x27) {
  12660. channel.ccRU(4);
  12661. } else if (b === 0x28) {
  12662. channel.ccFON();
  12663. } else if (b === 0x29) {
  12664. channel.ccRDC();
  12665. } else if (b === 0x2A) {
  12666. channel.ccTR();
  12667. } else if (b === 0x2B) {
  12668. channel.ccRTD();
  12669. } else if (b === 0x2C) {
  12670. channel.ccEDM();
  12671. } else if (b === 0x2D) {
  12672. channel.ccCR();
  12673. } else if (b === 0x2E) {
  12674. channel.ccENM();
  12675. } else if (b === 0x2F) {
  12676. channel.ccEOC();
  12677. }
  12678. } else {
  12679. //a == 0x17 || a == 0x1F
  12680. channel.ccTO(b - 0x20);
  12681. }
  12682. this.lastCmdA = a;
  12683. this.lastCmdB = b;
  12684. this.currChNr = chNr;
  12685. return true;
  12686. };
  12687. /**
  12688. * Parse midrow styling command
  12689. * @returns {Boolean}
  12690. */
  12691. Cea608Parser.prototype.parseMidrow = function parseMidrow(a, b) {
  12692. var chNr = null;
  12693. if ((a === 0x11 || a === 0x19) && 0x20 <= b && b <= 0x2f) {
  12694. if (a === 0x11) {
  12695. chNr = 1;
  12696. } else {
  12697. chNr = 2;
  12698. }
  12699. if (chNr !== this.currChNr) {
  12700. cea_608_parser_logger.log('ERROR', 'Mismatch channel in midrow parsing');
  12701. return false;
  12702. }
  12703. var channel = this.channels[chNr - 1];
  12704. channel.ccMIDROW(b);
  12705. cea_608_parser_logger.log('DEBUG', 'MIDROW (' + numArrayToHexArray([a, b]) + ')');
  12706. return true;
  12707. }
  12708. return false;
  12709. };
  12710. /**
  12711. * Parse Preable Access Codes (Table 53).
  12712. * @returns {Boolean} Tells if PAC found
  12713. */
  12714. Cea608Parser.prototype.parsePAC = function parsePAC(a, b) {
  12715. var chNr = null;
  12716. var row = null;
  12717. var case1 = (0x11 <= a && a <= 0x17 || 0x19 <= a && a <= 0x1F) && 0x40 <= b && b <= 0x7F;
  12718. var case2 = (a === 0x10 || a === 0x18) && 0x40 <= b && b <= 0x5F;
  12719. if (!(case1 || case2)) {
  12720. return false;
  12721. }
  12722. if (a === this.lastCmdA && b === this.lastCmdB) {
  12723. this.lastCmdA = null;
  12724. this.lastCmdB = null;
  12725. return true; // Repeated commands are dropped (once)
  12726. }
  12727. chNr = a <= 0x17 ? 1 : 2;
  12728. if (0x40 <= b && b <= 0x5F) {
  12729. row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];
  12730. } else {
  12731. // 0x60 <= b <= 0x7F
  12732. row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a];
  12733. }
  12734. var pacData = this.interpretPAC(row, b);
  12735. var channel = this.channels[chNr - 1];
  12736. channel.setPAC(pacData);
  12737. this.lastCmdA = a;
  12738. this.lastCmdB = b;
  12739. this.currChNr = chNr;
  12740. return true;
  12741. };
  12742. /**
  12743. * Interpret the second byte of the pac, and return the information.
  12744. * @returns {Object} pacData with style parameters.
  12745. */
  12746. Cea608Parser.prototype.interpretPAC = function interpretPAC(row, byte) {
  12747. var pacIndex = byte;
  12748. var pacData = { color: null, italics: false, indent: null, underline: false, row: row };
  12749. if (byte > 0x5F) {
  12750. pacIndex = byte - 0x60;
  12751. } else {
  12752. pacIndex = byte - 0x40;
  12753. }
  12754. pacData.underline = (pacIndex & 1) === 1;
  12755. if (pacIndex <= 0xd) {
  12756. pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex / 2)];
  12757. } else if (pacIndex <= 0xf) {
  12758. pacData.italics = true;
  12759. pacData.color = 'white';
  12760. } else {
  12761. pacData.indent = Math.floor((pacIndex - 0x10) / 2) * 4;
  12762. }
  12763. return pacData; // Note that row has zero offset. The spec uses 1.
  12764. };
  12765. /**
  12766. * Parse characters.
  12767. * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.
  12768. */
  12769. Cea608Parser.prototype.parseChars = function parseChars(a, b) {
  12770. var channelNr = null,
  12771. charCodes = null,
  12772. charCode1 = null;
  12773. if (a >= 0x19) {
  12774. channelNr = 2;
  12775. charCode1 = a - 8;
  12776. } else {
  12777. channelNr = 1;
  12778. charCode1 = a;
  12779. }
  12780. if (0x11 <= charCode1 && charCode1 <= 0x13) {
  12781. // Special character
  12782. var oneCode = b;
  12783. if (charCode1 === 0x11) {
  12784. oneCode = b + 0x50;
  12785. } else if (charCode1 === 0x12) {
  12786. oneCode = b + 0x70;
  12787. } else {
  12788. oneCode = b + 0x90;
  12789. }
  12790. cea_608_parser_logger.log('INFO', 'Special char \'' + getCharForByte(oneCode) + '\' in channel ' + channelNr);
  12791. charCodes = [oneCode];
  12792. } else if (0x20 <= a && a <= 0x7f) {
  12793. charCodes = b === 0 ? [a] : [a, b];
  12794. }
  12795. if (charCodes) {
  12796. var hexCodes = numArrayToHexArray(charCodes);
  12797. cea_608_parser_logger.log('DEBUG', 'Char codes = ' + hexCodes.join(','));
  12798. this.lastCmdA = null;
  12799. this.lastCmdB = null;
  12800. }
  12801. return charCodes;
  12802. };
  12803. /**
  12804. * Parse extended background attributes as well as new foreground color black.
  12805. * @returns{Boolean} Tells if background attributes are found
  12806. */
  12807. Cea608Parser.prototype.parseBackgroundAttributes = function parseBackgroundAttributes(a, b) {
  12808. var bkgData, index, chNr, channel;
  12809. var case1 = (a === 0x10 || a === 0x18) && 0x20 <= b && b <= 0x2f;
  12810. var case2 = (a === 0x17 || a === 0x1f) && 0x2d <= b && b <= 0x2f;
  12811. if (!(case1 || case2)) {
  12812. return false;
  12813. }
  12814. bkgData = {};
  12815. if (a === 0x10 || a === 0x18) {
  12816. index = Math.floor((b - 0x20) / 2);
  12817. bkgData.background = backgroundColors[index];
  12818. if (b % 2 === 1) {
  12819. bkgData.background = bkgData.background + '_semi';
  12820. }
  12821. } else if (b === 0x2d) {
  12822. bkgData.background = 'transparent';
  12823. } else {
  12824. bkgData.foreground = 'black';
  12825. if (b === 0x2f) {
  12826. bkgData.underline = true;
  12827. }
  12828. }
  12829. chNr = a < 0x18 ? 1 : 2;
  12830. channel = this.channels[chNr - 1];
  12831. channel.setBkgData(bkgData);
  12832. this.lastCmdA = null;
  12833. this.lastCmdB = null;
  12834. return true;
  12835. };
  12836. /**
  12837. * Reset state of parser and its channels.
  12838. */
  12839. Cea608Parser.prototype.reset = function reset() {
  12840. for (var i = 0; i < this.channels.length; i++) {
  12841. if (this.channels[i]) {
  12842. this.channels[i].reset();
  12843. }
  12844. }
  12845. this.lastCmdA = null;
  12846. this.lastCmdB = null;
  12847. };
  12848. /**
  12849. * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.
  12850. */
  12851. Cea608Parser.prototype.cueSplitAtTime = function cueSplitAtTime(t) {
  12852. for (var i = 0; i < this.channels.length; i++) {
  12853. if (this.channels[i]) {
  12854. this.channels[i].cueSplitAtTime(t);
  12855. }
  12856. }
  12857. };
  12858. return Cea608Parser;
  12859. }();
  12860. /* harmony default export */ var cea_608_parser = (Cea608Parser);
  12861. // CONCATENATED MODULE: ./src/utils/output-filter.js
  12862. function output_filter__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  12863. var OutputFilter = function () {
  12864. function OutputFilter(timelineController, track) {
  12865. output_filter__classCallCheck(this, OutputFilter);
  12866. this.timelineController = timelineController;
  12867. this.track = track;
  12868. this.startTime = null;
  12869. this.endTime = null;
  12870. this.screen = null;
  12871. }
  12872. OutputFilter.prototype.dispatchCue = function dispatchCue() {
  12873. if (this.startTime === null) {
  12874. return;
  12875. }
  12876. this.timelineController.addCues('textTrack' + this.track, this.startTime, this.endTime, this.screen);
  12877. this.startTime = null;
  12878. };
  12879. OutputFilter.prototype.newCue = function newCue(startTime, endTime, screen) {
  12880. if (this.startTime === null || this.startTime > startTime) {
  12881. this.startTime = startTime;
  12882. }
  12883. this.endTime = endTime;
  12884. this.screen = screen;
  12885. this.timelineController.createCaptionsTrack(this.track);
  12886. };
  12887. return OutputFilter;
  12888. }();
  12889. /* harmony default export */ var output_filter = (OutputFilter);
  12890. // CONCATENATED MODULE: ./src/utils/webvtt-parser.js
  12891. // String.prototype.startsWith is not supported in IE11
  12892. var startsWith = function startsWith(inputString, searchString, position) {
  12893. return inputString.substr(position || 0, searchString.length) === searchString;
  12894. };
  12895. var cueString2millis = function cueString2millis(timeString) {
  12896. var ts = parseInt(timeString.substr(-3));
  12897. var secs = parseInt(timeString.substr(-6, 2));
  12898. var mins = parseInt(timeString.substr(-9, 2));
  12899. var hours = timeString.length > 9 ? parseInt(timeString.substr(0, timeString.indexOf(':'))) : 0;
  12900. if (isNaN(ts) || isNaN(secs) || isNaN(mins) || isNaN(hours)) {
  12901. return -1;
  12902. }
  12903. ts += 1000 * secs;
  12904. ts += 60 * 1000 * mins;
  12905. ts += 60 * 60 * 1000 * hours;
  12906. return ts;
  12907. };
  12908. // From https://github.com/darkskyapp/string-hash
  12909. var hash = function hash(text) {
  12910. var hash = 5381;
  12911. var i = text.length;
  12912. while (i) {
  12913. hash = hash * 33 ^ text.charCodeAt(--i);
  12914. }
  12915. return (hash >>> 0).toString();
  12916. };
  12917. var calculateOffset = function calculateOffset(vttCCs, cc, presentationTime) {
  12918. var currCC = vttCCs[cc];
  12919. var prevCC = vttCCs[currCC.prevCC];
  12920. // This is the first discontinuity or cues have been processed since the last discontinuity
  12921. // Offset = current discontinuity time
  12922. if (!prevCC || !prevCC.new && currCC.new) {
  12923. vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;
  12924. currCC.new = false;
  12925. return;
  12926. }
  12927. // There have been discontinuities since cues were last parsed.
  12928. // Offset = time elapsed
  12929. while (prevCC && prevCC.new) {
  12930. vttCCs.ccOffset += currCC.start - prevCC.start;
  12931. currCC.new = false;
  12932. currCC = prevCC;
  12933. prevCC = vttCCs[currCC.prevCC];
  12934. }
  12935. vttCCs.presentationOffset = presentationTime;
  12936. };
  12937. var WebVTTParser = {
  12938. parse: function parse(vttByteArray, syncPTS, vttCCs, cc, callBack, errorCallBack) {
  12939. // Convert byteArray into string, replacing any somewhat exotic linefeeds with "\n", then split on that character.
  12940. var re = /\r\n|\n\r|\n|\r/g;
  12941. // Uint8Array.prototype.reduce is not implemented in IE11
  12942. var vttLines = Object(id3["b" /* utf8ArrayToStr */])(new Uint8Array(vttByteArray)).trim().replace(re, '\n').split('\n');
  12943. var cueTime = '00:00.000';
  12944. var mpegTs = 0;
  12945. var localTime = 0;
  12946. var presentationTime = 0;
  12947. var cues = [];
  12948. var parsingError = void 0;
  12949. var inHeader = true;
  12950. // let VTTCue = VTTCue || window.TextTrackCue;
  12951. // Create parser object using VTTCue with TextTrackCue fallback on certain browsers.
  12952. var parser = new vttparser();
  12953. parser.oncue = function (cue) {
  12954. // Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline.
  12955. var currCC = vttCCs[cc];
  12956. var cueOffset = vttCCs.ccOffset;
  12957. // Update offsets for new discontinuities
  12958. if (currCC && currCC.new) {
  12959. if (localTime !== undefined) {
  12960. // When local time is provided, offset = discontinuity start time - local time
  12961. cueOffset = vttCCs.ccOffset = currCC.start;
  12962. } else {
  12963. calculateOffset(vttCCs, cc, presentationTime);
  12964. }
  12965. }
  12966. if (presentationTime) {
  12967. // If we have MPEGTS, offset = presentation time + discontinuity offset
  12968. cueOffset = presentationTime + vttCCs.ccOffset - vttCCs.presentationOffset;
  12969. }
  12970. cue.startTime += cueOffset - localTime;
  12971. cue.endTime += cueOffset - localTime;
  12972. // Create a unique hash id for a cue based on start/end times and text.
  12973. // This helps timeline-controller to avoid showing repeated captions.
  12974. cue.id = hash(cue.startTime.toString()) + hash(cue.endTime.toString()) + hash(cue.text);
  12975. // Fix encoding of special characters. TODO: Test with all sorts of weird characters.
  12976. cue.text = decodeURIComponent(encodeURIComponent(cue.text));
  12977. if (cue.endTime > 0) {
  12978. cues.push(cue);
  12979. }
  12980. };
  12981. parser.onparsingerror = function (e) {
  12982. parsingError = e;
  12983. };
  12984. parser.onflush = function () {
  12985. if (parsingError && errorCallBack) {
  12986. errorCallBack(parsingError);
  12987. return;
  12988. }
  12989. callBack(cues);
  12990. };
  12991. // Go through contents line by line.
  12992. vttLines.forEach(function (line) {
  12993. if (inHeader) {
  12994. // Look for X-TIMESTAMP-MAP in header.
  12995. if (startsWith(line, 'X-TIMESTAMP-MAP=')) {
  12996. // Once found, no more are allowed anyway, so stop searching.
  12997. inHeader = false;
  12998. // Extract LOCAL and MPEGTS.
  12999. line.substr(16).split(',').forEach(function (timestamp) {
  13000. if (startsWith(timestamp, 'LOCAL:')) {
  13001. cueTime = timestamp.substr(6);
  13002. } else if (startsWith(timestamp, 'MPEGTS:')) {
  13003. mpegTs = parseInt(timestamp.substr(7));
  13004. }
  13005. });
  13006. try {
  13007. // Calculate subtitle offset in milliseconds.
  13008. // If sync PTS is less than zero, we have a 33-bit wraparound, which is fixed by adding 2^33 = 8589934592.
  13009. syncPTS = syncPTS < 0 ? syncPTS + 8589934592 : syncPTS;
  13010. // Adjust MPEGTS by sync PTS.
  13011. mpegTs -= syncPTS;
  13012. // Convert cue time to seconds
  13013. localTime = cueString2millis(cueTime) / 1000;
  13014. // Convert MPEGTS to seconds from 90kHz.
  13015. presentationTime = mpegTs / 90000;
  13016. if (localTime === -1) {
  13017. parsingError = new Error('Malformed X-TIMESTAMP-MAP: ' + line);
  13018. }
  13019. } catch (e) {
  13020. parsingError = new Error('Malformed X-TIMESTAMP-MAP: ' + line);
  13021. }
  13022. // Return without parsing X-TIMESTAMP-MAP line.
  13023. return;
  13024. } else if (line === '') {
  13025. inHeader = false;
  13026. }
  13027. }
  13028. // Parse line by default.
  13029. parser.parse(line + '\n');
  13030. });
  13031. parser.flush();
  13032. }
  13033. };
  13034. /* harmony default export */ var webvtt_parser = (WebVTTParser);
  13035. // CONCATENATED MODULE: ./src/controller/timeline-controller.js
  13036. function timeline_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  13037. function timeline_controller__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; }
  13038. function timeline_controller__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; }
  13039. /*
  13040. * Timeline Controller
  13041. */
  13042. function clearCurrentCues(track) {
  13043. if (track && track.cues) {
  13044. while (track.cues.length > 0) {
  13045. track.removeCue(track.cues[0]);
  13046. }
  13047. }
  13048. }
  13049. function reuseVttTextTrack(inUseTrack, manifestTrack) {
  13050. return inUseTrack && inUseTrack.label === manifestTrack.name && !(inUseTrack.textTrack1 || inUseTrack.textTrack2);
  13051. }
  13052. function intersection(x1, x2, y1, y2) {
  13053. return Math.min(x2, y2) - Math.max(x1, y1);
  13054. }
  13055. var timeline_controller_TimelineController = function (_EventHandler) {
  13056. timeline_controller__inherits(TimelineController, _EventHandler);
  13057. function TimelineController(hls) {
  13058. timeline_controller__classCallCheck(this, TimelineController);
  13059. var _this = timeline_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MEDIA_ATTACHING, events["a" /* default */].MEDIA_DETACHING, events["a" /* default */].FRAG_PARSING_USERDATA, events["a" /* default */].FRAG_DECRYPTED, events["a" /* default */].MANIFEST_LOADING, events["a" /* default */].MANIFEST_LOADED, events["a" /* default */].FRAG_LOADED, events["a" /* default */].LEVEL_SWITCHING, events["a" /* default */].INIT_PTS_FOUND));
  13060. _this.hls = hls;
  13061. _this.config = hls.config;
  13062. _this.enabled = true;
  13063. _this.Cues = hls.config.cueHandler;
  13064. _this.textTracks = [];
  13065. _this.tracks = [];
  13066. _this.unparsedVttFrags = [];
  13067. _this.initPTS = undefined;
  13068. _this.cueRanges = [];
  13069. if (_this.config.enableCEA708Captions) {
  13070. var channel1 = new output_filter(_this, 1);
  13071. var channel2 = new output_filter(_this, 2);
  13072. _this.cea608Parser = new cea_608_parser(0, channel1, channel2);
  13073. }
  13074. return _this;
  13075. }
  13076. TimelineController.prototype.addCues = function addCues(channel, startTime, endTime, screen) {
  13077. // skip cues which overlap more than 50% with previously parsed time ranges
  13078. var ranges = this.cueRanges;
  13079. var merged = false;
  13080. for (var i = ranges.length; i--;) {
  13081. var cueRange = ranges[i];
  13082. var overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);
  13083. if (overlap >= 0) {
  13084. cueRange[0] = Math.min(cueRange[0], startTime);
  13085. cueRange[1] = Math.max(cueRange[1], endTime);
  13086. merged = true;
  13087. if (overlap / (endTime - startTime) > 0.5) {
  13088. return;
  13089. }
  13090. }
  13091. }
  13092. if (!merged) {
  13093. ranges.push([startTime, endTime]);
  13094. }
  13095. this.Cues.newCue(this[channel], startTime, endTime, screen);
  13096. };
  13097. // Triggered when an initial PTS is found; used for synchronisation of WebVTT.
  13098. TimelineController.prototype.onInitPtsFound = function onInitPtsFound(data) {
  13099. var _this2 = this;
  13100. if (typeof this.initPTS === 'undefined') {
  13101. this.initPTS = data.initPTS;
  13102. }
  13103. // Due to asynchrony, initial PTS may arrive later than the first VTT fragments are loaded.
  13104. // Parse any unparsed fragments upon receiving the initial PTS.
  13105. if (this.unparsedVttFrags.length) {
  13106. this.unparsedVttFrags.forEach(function (frag) {
  13107. _this2.onFragLoaded(frag);
  13108. });
  13109. this.unparsedVttFrags = [];
  13110. }
  13111. };
  13112. TimelineController.prototype.getExistingTrack = function getExistingTrack(channelNumber) {
  13113. var media = this.media;
  13114. if (media) {
  13115. for (var i = 0; i < media.textTracks.length; i++) {
  13116. var textTrack = media.textTracks[i];
  13117. var propName = 'textTrack' + channelNumber;
  13118. if (textTrack[propName] === true) {
  13119. return textTrack;
  13120. }
  13121. }
  13122. }
  13123. return null;
  13124. };
  13125. TimelineController.prototype.sendAddTrackEvent = function sendAddTrackEvent(track, media) {
  13126. var e = null;
  13127. try {
  13128. e = new window.Event('addtrack');
  13129. } catch (err) {
  13130. //for IE11
  13131. e = document.createEvent('Event');
  13132. e.initEvent('addtrack', false, false);
  13133. }
  13134. e.track = track;
  13135. media.dispatchEvent(e);
  13136. };
  13137. TimelineController.prototype.createCaptionsTrack = function createCaptionsTrack(track) {
  13138. var trackVar = 'textTrack' + track;
  13139. if (!this[trackVar]) {
  13140. //Enable reuse of existing text track.
  13141. var existingTrack = this.getExistingTrack(track);
  13142. if (!existingTrack) {
  13143. var textTrack = this.createTextTrack('captions', this.config['captionsTextTrack' + track + 'Label'], this.config.captionsTextTrack1LanguageCode);
  13144. if (textTrack) {
  13145. textTrack[trackVar] = true;
  13146. this[trackVar] = textTrack;
  13147. }
  13148. } else {
  13149. this[trackVar] = existingTrack;
  13150. clearCurrentCues(this[trackVar]);
  13151. this.sendAddTrackEvent(this[trackVar], this.media);
  13152. }
  13153. }
  13154. };
  13155. TimelineController.prototype.createTextTrack = function createTextTrack(kind, label, lang) {
  13156. var media = this.media;
  13157. if (media) {
  13158. return media.addTextTrack(kind, label, lang);
  13159. }
  13160. };
  13161. TimelineController.prototype.destroy = function destroy() {
  13162. event_handler.prototype.destroy.call(this);
  13163. };
  13164. TimelineController.prototype.onMediaAttaching = function onMediaAttaching(data) {
  13165. this.media = data.media;
  13166. this._cleanTracks();
  13167. };
  13168. TimelineController.prototype.onMediaDetaching = function onMediaDetaching() {
  13169. clearCurrentCues(this.textTrack1);
  13170. clearCurrentCues(this.textTrack2);
  13171. };
  13172. TimelineController.prototype.onManifestLoading = function onManifestLoading() {
  13173. this.lastSn = -1; // Detect discontiguity in fragment parsing
  13174. this.prevCC = -1;
  13175. this.vttCCs = { ccOffset: 0, presentationOffset: 0 }; // Detect discontinuity in subtitle manifests
  13176. this._cleanTracks();
  13177. };
  13178. TimelineController.prototype._cleanTracks = function _cleanTracks() {
  13179. // clear outdated subtitles
  13180. var media = this.media;
  13181. if (media) {
  13182. var textTracks = media.textTracks;
  13183. if (textTracks) {
  13184. for (var i = 0; i < textTracks.length; i++) {
  13185. clearCurrentCues(textTracks[i]);
  13186. }
  13187. }
  13188. }
  13189. };
  13190. TimelineController.prototype.onManifestLoaded = function onManifestLoaded(data) {
  13191. var _this3 = this;
  13192. this.textTracks = [];
  13193. this.unparsedVttFrags = this.unparsedVttFrags || [];
  13194. this.initPTS = undefined;
  13195. this.cueRanges = [];
  13196. if (this.config.enableWebVTT) {
  13197. this.tracks = data.subtitles || [];
  13198. var inUseTracks = this.media ? this.media.textTracks : [];
  13199. this.tracks.forEach(function (track, index) {
  13200. var textTrack = void 0;
  13201. if (index < inUseTracks.length) {
  13202. var inUseTrack = inUseTracks[index];
  13203. // Reuse tracks with the same label, but do not reuse 608/708 tracks
  13204. if (reuseVttTextTrack(inUseTrack, track)) {
  13205. textTrack = inUseTrack;
  13206. }
  13207. }
  13208. if (!textTrack) {
  13209. textTrack = _this3.createTextTrack('subtitles', track.name, track.lang);
  13210. }
  13211. textTrack.mode = track.default ? 'showing' : 'hidden';
  13212. _this3.textTracks.push(textTrack);
  13213. });
  13214. }
  13215. };
  13216. TimelineController.prototype.onLevelSwitching = function onLevelSwitching() {
  13217. this.enabled = this.hls.currentLevel.closedCaptions !== 'NONE';
  13218. };
  13219. TimelineController.prototype.onFragLoaded = function onFragLoaded(data) {
  13220. var frag = data.frag,
  13221. payload = data.payload;
  13222. if (frag.type === 'main') {
  13223. var sn = frag.sn;
  13224. // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack
  13225. if (sn !== this.lastSn + 1) {
  13226. var cea608Parser = this.cea608Parser;
  13227. if (cea608Parser) {
  13228. cea608Parser.reset();
  13229. }
  13230. }
  13231. this.lastSn = sn;
  13232. }
  13233. // If fragment is subtitle type, parse as WebVTT.
  13234. else if (frag.type === 'subtitle') {
  13235. if (payload.byteLength) {
  13236. // We need an initial synchronisation PTS. Store fragments as long as none has arrived.
  13237. if (typeof this.initPTS === 'undefined') {
  13238. this.unparsedVttFrags.push(data);
  13239. return;
  13240. }
  13241. var decryptData = frag.decryptdata;
  13242. // If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait.
  13243. if (decryptData == null || decryptData.key == null || decryptData.method !== 'AES-128') {
  13244. this._parseVTTs(frag, payload);
  13245. }
  13246. } else {
  13247. // In case there is no payload, finish unsuccessfully.
  13248. this.hls.trigger(events["a" /* default */].SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });
  13249. }
  13250. }
  13251. };
  13252. TimelineController.prototype._parseVTTs = function _parseVTTs(frag, payload) {
  13253. var vttCCs = this.vttCCs;
  13254. if (!vttCCs[frag.cc]) {
  13255. vttCCs[frag.cc] = { start: frag.start, prevCC: this.prevCC, new: true };
  13256. this.prevCC = frag.cc;
  13257. }
  13258. var textTracks = this.textTracks,
  13259. hls = this.hls;
  13260. // Parse the WebVTT file contents.
  13261. webvtt_parser.parse(payload, this.initPTS, vttCCs, frag.cc, function (cues) {
  13262. var currentTrack = textTracks[frag.trackId];
  13263. // Add cues and trigger event with success true.
  13264. cues.forEach(function (cue) {
  13265. // Sometimes there are cue overlaps on segmented vtts so the same
  13266. // cue can appear more than once in different vtt files.
  13267. // This avoid showing duplicated cues with same timecode and text.
  13268. if (!currentTrack.cues.getCueById(cue.id)) {
  13269. try {
  13270. currentTrack.addCue(cue);
  13271. } catch (err) {
  13272. var textTrackCue = new window.TextTrackCue(cue.startTime, cue.endTime, cue.text);
  13273. textTrackCue.id = cue.id;
  13274. currentTrack.addCue(textTrackCue);
  13275. }
  13276. }
  13277. });
  13278. hls.trigger(events["a" /* default */].SUBTITLE_FRAG_PROCESSED, { success: true, frag: frag });
  13279. }, function (e) {
  13280. // Something went wrong while parsing. Trigger event with success false.
  13281. logger["b" /* logger */].log('Failed to parse VTT cue: ' + e);
  13282. hls.trigger(events["a" /* default */].SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });
  13283. });
  13284. };
  13285. TimelineController.prototype.onFragDecrypted = function onFragDecrypted(data) {
  13286. var decryptedData = data.payload,
  13287. frag = data.frag;
  13288. if (frag.type === 'subtitle') {
  13289. if (typeof this.initPTS === 'undefined') {
  13290. this.unparsedVttFrags.push(data);
  13291. return;
  13292. }
  13293. this._parseVTTs(frag, decryptedData);
  13294. }
  13295. };
  13296. TimelineController.prototype.onFragParsingUserdata = function onFragParsingUserdata(data) {
  13297. // push all of the CEA-708 messages into the interpreter
  13298. // immediately. It will create the proper timestamps based on our PTS value
  13299. if (this.enabled && this.config.enableCEA708Captions) {
  13300. for (var i = 0; i < data.samples.length; i++) {
  13301. var ccdatas = this.extractCea608Data(data.samples[i].bytes);
  13302. this.cea608Parser.addData(data.samples[i].pts, ccdatas);
  13303. }
  13304. }
  13305. };
  13306. TimelineController.prototype.extractCea608Data = function extractCea608Data(byteArray) {
  13307. var count = byteArray[0] & 31;
  13308. var position = 2;
  13309. var tmpByte, ccbyte1, ccbyte2, ccValid, ccType;
  13310. var actualCCBytes = [];
  13311. for (var j = 0; j < count; j++) {
  13312. tmpByte = byteArray[position++];
  13313. ccbyte1 = 0x7F & byteArray[position++];
  13314. ccbyte2 = 0x7F & byteArray[position++];
  13315. ccValid = (4 & tmpByte) !== 0;
  13316. ccType = 3 & tmpByte;
  13317. if (ccbyte1 === 0 && ccbyte2 === 0) {
  13318. continue;
  13319. }
  13320. if (ccValid) {
  13321. if (ccType === 0) // || ccType === 1
  13322. {
  13323. actualCCBytes.push(ccbyte1);
  13324. actualCCBytes.push(ccbyte2);
  13325. }
  13326. }
  13327. }
  13328. return actualCCBytes;
  13329. };
  13330. return TimelineController;
  13331. }(event_handler);
  13332. /* harmony default export */ var timeline_controller = (timeline_controller_TimelineController);
  13333. // CONCATENATED MODULE: ./src/controller/subtitle-track-controller.js
  13334. var subtitle_track_controller__createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  13335. function subtitle_track_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  13336. function subtitle_track_controller__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; }
  13337. function subtitle_track_controller__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; }
  13338. /*
  13339. * subtitle track controller
  13340. */
  13341. function filterSubtitleTracks(textTrackList) {
  13342. var tracks = [];
  13343. for (var i = 0; i < textTrackList.length; i++) {
  13344. if (textTrackList[i].kind === 'subtitles') {
  13345. tracks.push(textTrackList[i]);
  13346. }
  13347. }
  13348. return tracks;
  13349. }
  13350. var subtitle_track_controller_SubtitleTrackController = function (_EventHandler) {
  13351. subtitle_track_controller__inherits(SubtitleTrackController, _EventHandler);
  13352. function SubtitleTrackController(hls) {
  13353. subtitle_track_controller__classCallCheck(this, SubtitleTrackController);
  13354. var _this = subtitle_track_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MEDIA_ATTACHED, events["a" /* default */].MEDIA_DETACHING, events["a" /* default */].MANIFEST_LOADING, events["a" /* default */].MANIFEST_LOADED, events["a" /* default */].SUBTITLE_TRACK_LOADED));
  13355. _this.tracks = [];
  13356. _this.trackId = -1;
  13357. _this.media = undefined;
  13358. _this.subtitleDisplay = false;
  13359. return _this;
  13360. }
  13361. SubtitleTrackController.prototype._onTextTracksChanged = function _onTextTracksChanged() {
  13362. // Media is undefined when switching streams via loadSource()
  13363. if (!this.media) {
  13364. return;
  13365. }
  13366. var trackId = -1;
  13367. var tracks = filterSubtitleTracks(this.media.textTracks);
  13368. for (var id = 0; id < tracks.length; id++) {
  13369. if (tracks[id].mode === 'showing') {
  13370. trackId = id;
  13371. }
  13372. }
  13373. // Setting current subtitleTrack will invoke code.
  13374. this.subtitleTrack = trackId;
  13375. };
  13376. SubtitleTrackController.prototype.destroy = function destroy() {
  13377. event_handler.prototype.destroy.call(this);
  13378. };
  13379. // Listen for subtitle track change, then extract the current track ID.
  13380. SubtitleTrackController.prototype.onMediaAttached = function onMediaAttached(data) {
  13381. var _this2 = this;
  13382. this.media = data.media;
  13383. if (!this.media) {
  13384. return;
  13385. }
  13386. if (this.queuedDefaultTrack !== undefined) {
  13387. this.subtitleTrack = this.queuedDefaultTrack;
  13388. delete this.queuedDefaultTrack;
  13389. }
  13390. this.trackChangeListener = this._onTextTracksChanged.bind(this);
  13391. this.useTextTrackPolling = !(this.media.textTracks && 'onchange' in this.media.textTracks);
  13392. if (this.useTextTrackPolling) {
  13393. this.subtitlePollingInterval = setInterval(function () {
  13394. _this2.trackChangeListener();
  13395. }, 500);
  13396. } else {
  13397. this.media.textTracks.addEventListener('change', this.trackChangeListener);
  13398. }
  13399. };
  13400. SubtitleTrackController.prototype.onMediaDetaching = function onMediaDetaching() {
  13401. if (!this.media) {
  13402. return;
  13403. }
  13404. if (this.useTextTrackPolling) {
  13405. clearInterval(this.subtitlePollingInterval);
  13406. } else {
  13407. this.media.textTracks.removeEventListener('change', this.trackChangeListener);
  13408. }
  13409. this.media = undefined;
  13410. };
  13411. // Reset subtitle tracks on manifest loading
  13412. SubtitleTrackController.prototype.onManifestLoading = function onManifestLoading() {
  13413. this.tracks = [];
  13414. this.trackId = -1;
  13415. };
  13416. // Fired whenever a new manifest is loaded.
  13417. SubtitleTrackController.prototype.onManifestLoaded = function onManifestLoaded(data) {
  13418. var _this3 = this;
  13419. var tracks = data.subtitles || [];
  13420. this.tracks = tracks;
  13421. this.trackId = -1;
  13422. this.hls.trigger(events["a" /* default */].SUBTITLE_TRACKS_UPDATED, { subtitleTracks: tracks });
  13423. // loop through available subtitle tracks and autoselect default if needed
  13424. // TODO: improve selection logic to handle forced, etc
  13425. tracks.forEach(function (track) {
  13426. if (track.default) {
  13427. // setting this.subtitleTrack will trigger internal logic
  13428. // if media has not been attached yet, it will fail
  13429. // we keep a reference to the default track id
  13430. // and we'll set subtitleTrack when onMediaAttached is triggered
  13431. if (_this3.media) {
  13432. _this3.subtitleTrack = track.id;
  13433. } else {
  13434. _this3.queuedDefaultTrack = track.id;
  13435. }
  13436. }
  13437. });
  13438. };
  13439. // Trigger subtitle track playlist reload.
  13440. SubtitleTrackController.prototype.onTick = function onTick() {
  13441. var trackId = this.trackId;
  13442. var subtitleTrack = this.tracks[trackId];
  13443. if (!subtitleTrack) {
  13444. return;
  13445. }
  13446. var details = subtitleTrack.details;
  13447. // check if we need to load playlist for this subtitle Track
  13448. if (details === undefined || details.live === true) {
  13449. // track not retrieved yet, or live playlist we need to (re)load it
  13450. logger["b" /* logger */].log('(re)loading playlist for subtitle track ' + trackId);
  13451. this.hls.trigger(events["a" /* default */].SUBTITLE_TRACK_LOADING, { url: subtitleTrack.url, id: trackId });
  13452. }
  13453. };
  13454. SubtitleTrackController.prototype.onSubtitleTrackLoaded = function onSubtitleTrackLoaded(data) {
  13455. var _this4 = this;
  13456. if (data.id < this.tracks.length) {
  13457. logger["b" /* logger */].log('subtitle track ' + data.id + ' loaded');
  13458. this.tracks[data.id].details = data.details;
  13459. // check if current playlist is a live playlist
  13460. if (data.details.live && !this.timer) {
  13461. // if live playlist we will have to reload it periodically
  13462. // set reload period to playlist target duration
  13463. this.timer = setInterval(function () {
  13464. _this4.onTick();
  13465. }, 1000 * data.details.targetduration, this);
  13466. }
  13467. if (!data.details.live && this.timer) {
  13468. // playlist is not live and timer is armed : stopping it
  13469. clearInterval(this.timer);
  13470. this.timer = null;
  13471. }
  13472. }
  13473. };
  13474. /** get alternate subtitle tracks list from playlist **/
  13475. SubtitleTrackController.prototype.setSubtitleTrackInternal = function setSubtitleTrackInternal(newId) {
  13476. // check if level idx is valid
  13477. if (newId < -1 || newId >= this.tracks.length) {
  13478. return;
  13479. }
  13480. // stopping live reloading timer if any
  13481. if (this.timer) {
  13482. clearInterval(this.timer);
  13483. this.timer = null;
  13484. }
  13485. var textTracks = filterSubtitleTracks(this.media.textTracks);
  13486. // hide currently enabled subtitle track
  13487. if (this.trackId !== -1 && this.subtitleDisplay) {
  13488. textTracks[this.trackId].mode = 'hidden';
  13489. }
  13490. this.trackId = newId;
  13491. logger["b" /* logger */].log('switching to subtitle track ' + newId);
  13492. this.hls.trigger(events["a" /* default */].SUBTITLE_TRACK_SWITCH, { id: newId });
  13493. if (newId === -1) {
  13494. return;
  13495. }
  13496. var subtitleTrack = this.tracks[newId];
  13497. if (this.subtitleDisplay) {
  13498. textTracks[newId].mode = 'showing';
  13499. }
  13500. // check if we need to load playlist for this subtitle Track
  13501. var details = subtitleTrack.details;
  13502. if (details === undefined || details.live === true) {
  13503. // track not retrieved yet, or live playlist we need to (re)load it
  13504. logger["b" /* logger */].log('(re)loading playlist for subtitle track ' + newId);
  13505. this.hls.trigger(events["a" /* default */].SUBTITLE_TRACK_LOADING, { url: subtitleTrack.url, id: newId });
  13506. }
  13507. };
  13508. subtitle_track_controller__createClass(SubtitleTrackController, [{
  13509. key: 'subtitleTracks',
  13510. get: function get() {
  13511. return this.tracks;
  13512. }
  13513. /** get index of the selected subtitle track (index in subtitle track lists) **/
  13514. }, {
  13515. key: 'subtitleTrack',
  13516. get: function get() {
  13517. return this.trackId;
  13518. }
  13519. /** select a subtitle track, based on its index in subtitle track lists**/
  13520. ,
  13521. set: function set(subtitleTrackId) {
  13522. if (this.trackId !== subtitleTrackId) {
  13523. // || this.tracks[subtitleTrackId].details === undefined) {
  13524. this.setSubtitleTrackInternal(subtitleTrackId);
  13525. }
  13526. }
  13527. }]);
  13528. return SubtitleTrackController;
  13529. }(event_handler);
  13530. /* harmony default export */ var subtitle_track_controller = (subtitle_track_controller_SubtitleTrackController);
  13531. // EXTERNAL MODULE: ./src/crypt/decrypter.js + 3 modules
  13532. var decrypter = __webpack_require__(5);
  13533. // CONCATENATED MODULE: ./src/controller/subtitle-stream-controller.js
  13534. function subtitle_stream_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  13535. function subtitle_stream_controller__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; }
  13536. function subtitle_stream_controller__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; }
  13537. /*
  13538. * Subtitle Stream Controller
  13539. */
  13540. var subtitle_stream_controller_State = {
  13541. STOPPED: 'STOPPED',
  13542. IDLE: 'IDLE',
  13543. KEY_LOADING: 'KEY_LOADING',
  13544. FRAG_LOADING: 'FRAG_LOADING'
  13545. };
  13546. var subtitle_stream_controller_SubtitleStreamController = function (_TaskLoop) {
  13547. subtitle_stream_controller__inherits(SubtitleStreamController, _TaskLoop);
  13548. function SubtitleStreamController(hls) {
  13549. subtitle_stream_controller__classCallCheck(this, SubtitleStreamController);
  13550. var _this = subtitle_stream_controller__possibleConstructorReturn(this, _TaskLoop.call(this, hls, events["a" /* default */].MEDIA_ATTACHED, events["a" /* default */].ERROR, events["a" /* default */].KEY_LOADED, events["a" /* default */].FRAG_LOADED, events["a" /* default */].SUBTITLE_TRACKS_UPDATED, events["a" /* default */].SUBTITLE_TRACK_SWITCH, events["a" /* default */].SUBTITLE_TRACK_LOADED, events["a" /* default */].SUBTITLE_FRAG_PROCESSED));
  13551. _this.config = hls.config;
  13552. _this.vttFragSNsProcessed = {};
  13553. _this.vttFragQueues = undefined;
  13554. _this.currentlyProcessing = null;
  13555. _this.state = subtitle_stream_controller_State.STOPPED;
  13556. _this.currentTrackId = -1;
  13557. _this.decrypter = new decrypter["a" /* default */](hls.observer, hls.config);
  13558. return _this;
  13559. }
  13560. SubtitleStreamController.prototype.onHandlerDestroyed = function onHandlerDestroyed() {
  13561. this.state = subtitle_stream_controller_State.STOPPED;
  13562. };
  13563. // Remove all queued items and create a new, empty queue for each track.
  13564. SubtitleStreamController.prototype.clearVttFragQueues = function clearVttFragQueues() {
  13565. var _this2 = this;
  13566. this.vttFragQueues = {};
  13567. this.tracks.forEach(function (track) {
  13568. _this2.vttFragQueues[track.id] = [];
  13569. });
  13570. };
  13571. // If no frag is being processed and queue isn't empty, initiate processing of next frag in line.
  13572. SubtitleStreamController.prototype.nextFrag = function nextFrag() {
  13573. if (this.currentlyProcessing === null && this.currentTrackId > -1 && this.vttFragQueues[this.currentTrackId].length) {
  13574. var frag = this.currentlyProcessing = this.vttFragQueues[this.currentTrackId].shift();
  13575. this.fragCurrent = frag;
  13576. this.hls.trigger(events["a" /* default */].FRAG_LOADING, { frag: frag });
  13577. this.state = subtitle_stream_controller_State.FRAG_LOADING;
  13578. }
  13579. };
  13580. // When fragment has finished processing, add sn to list of completed if successful.
  13581. SubtitleStreamController.prototype.onSubtitleFragProcessed = function onSubtitleFragProcessed(data) {
  13582. if (data.success) {
  13583. this.vttFragSNsProcessed[data.frag.trackId].push(data.frag.sn);
  13584. }
  13585. this.currentlyProcessing = null;
  13586. this.state = subtitle_stream_controller_State.IDLE;
  13587. this.nextFrag();
  13588. };
  13589. SubtitleStreamController.prototype.onMediaAttached = function onMediaAttached() {
  13590. this.state = subtitle_stream_controller_State.IDLE;
  13591. };
  13592. // If something goes wrong, procede to next frag, if we were processing one.
  13593. SubtitleStreamController.prototype.onError = function onError(data) {
  13594. var frag = data.frag;
  13595. // don't handle frag error not related to subtitle fragment
  13596. if (frag && frag.type !== 'subtitle') {
  13597. return;
  13598. }
  13599. if (this.currentlyProcessing) {
  13600. this.currentlyProcessing = null;
  13601. this.nextFrag();
  13602. }
  13603. };
  13604. SubtitleStreamController.prototype.doTick = function doTick() {
  13605. var _this3 = this;
  13606. switch (this.state) {
  13607. case subtitle_stream_controller_State.IDLE:
  13608. var tracks = this.tracks;
  13609. var trackId = this.currentTrackId;
  13610. var processedFragSNs = this.vttFragSNsProcessed[trackId],
  13611. fragQueue = this.vttFragQueues[trackId],
  13612. currentFragSN = !!this.currentlyProcessing ? this.currentlyProcessing.sn : -1;
  13613. var alreadyProcessed = function alreadyProcessed(frag) {
  13614. return processedFragSNs.indexOf(frag.sn) > -1;
  13615. };
  13616. var alreadyInQueue = function alreadyInQueue(frag) {
  13617. return fragQueue.some(function (fragInQueue) {
  13618. return fragInQueue.sn === frag.sn;
  13619. });
  13620. };
  13621. // exit if tracks don't exist
  13622. if (!tracks) {
  13623. break;
  13624. }
  13625. var trackDetails;
  13626. if (trackId < tracks.length) {
  13627. trackDetails = tracks[trackId].details;
  13628. }
  13629. if (typeof trackDetails === 'undefined') {
  13630. break;
  13631. }
  13632. // Add all fragments that haven't been, aren't currently being and aren't waiting to be processed, to queue.
  13633. trackDetails.fragments.forEach(function (frag) {
  13634. if (!(alreadyProcessed(frag) || frag.sn === currentFragSN || alreadyInQueue(frag))) {
  13635. // Load key if subtitles are encrypted
  13636. if (frag.decryptdata && frag.decryptdata.uri != null && frag.decryptdata.key == null) {
  13637. logger["b" /* logger */].log('Loading key for ' + frag.sn);
  13638. _this3.state = subtitle_stream_controller_State.KEY_LOADING;
  13639. _this3.hls.trigger(events["a" /* default */].KEY_LOADING, { frag: frag });
  13640. } else {
  13641. // Frags don't know their subtitle track ID, so let's just add that...
  13642. frag.trackId = trackId;
  13643. fragQueue.push(frag);
  13644. _this3.nextFrag();
  13645. }
  13646. }
  13647. });
  13648. }
  13649. };
  13650. // Got all new subtitle tracks.
  13651. SubtitleStreamController.prototype.onSubtitleTracksUpdated = function onSubtitleTracksUpdated(data) {
  13652. var _this4 = this;
  13653. logger["b" /* logger */].log('subtitle tracks updated');
  13654. this.tracks = data.subtitleTracks;
  13655. this.clearVttFragQueues();
  13656. this.vttFragSNsProcessed = {};
  13657. this.tracks.forEach(function (track) {
  13658. _this4.vttFragSNsProcessed[track.id] = [];
  13659. });
  13660. };
  13661. SubtitleStreamController.prototype.onSubtitleTrackSwitch = function onSubtitleTrackSwitch(data) {
  13662. this.currentTrackId = data.id;
  13663. this.clearVttFragQueues();
  13664. };
  13665. // Got a new set of subtitle fragments.
  13666. SubtitleStreamController.prototype.onSubtitleTrackLoaded = function onSubtitleTrackLoaded() {
  13667. this.tick();
  13668. };
  13669. SubtitleStreamController.prototype.onKeyLoaded = function onKeyLoaded() {
  13670. if (this.state === subtitle_stream_controller_State.KEY_LOADING) {
  13671. this.state = subtitle_stream_controller_State.IDLE;
  13672. this.tick();
  13673. }
  13674. };
  13675. SubtitleStreamController.prototype.onFragLoaded = function onFragLoaded(data) {
  13676. var fragCurrent = this.fragCurrent,
  13677. decryptData = data.frag.decryptdata;
  13678. var fragLoaded = data.frag,
  13679. hls = this.hls;
  13680. if (this.state === subtitle_stream_controller_State.FRAG_LOADING && fragCurrent && data.frag.type === 'subtitle' && fragCurrent.sn === data.frag.sn) {
  13681. // check to see if the payload needs to be decrypted
  13682. if (data.payload.byteLength > 0 && decryptData != null && decryptData.key != null && decryptData.method === 'AES-128') {
  13683. var startTime;
  13684. try {
  13685. startTime = performance.now();
  13686. } catch (error) {
  13687. startTime = Date.now();
  13688. }
  13689. // decrypt the subtitles
  13690. this.decrypter.decrypt(data.payload, decryptData.key.buffer, decryptData.iv.buffer, function (decryptedData) {
  13691. var endTime;
  13692. try {
  13693. endTime = performance.now();
  13694. } catch (error) {
  13695. endTime = Date.now();
  13696. }
  13697. hls.trigger(events["a" /* default */].FRAG_DECRYPTED, { frag: fragLoaded, payload: decryptedData, stats: { tstart: startTime, tdecrypt: endTime } });
  13698. });
  13699. }
  13700. }
  13701. };
  13702. return SubtitleStreamController;
  13703. }(task_loop);
  13704. /* harmony default export */ var subtitle_stream_controller = (subtitle_stream_controller_SubtitleStreamController);
  13705. // CONCATENATED MODULE: ./src/controller/eme-controller.js
  13706. var eme_controller__createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  13707. function eme_controller__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  13708. function eme_controller__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; }
  13709. function eme_controller__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; }
  13710. /**
  13711. * @author Stephan Hesse <disparat@gmail.com> | <tchakabam@gmail.com>
  13712. *
  13713. * DRM support for Hls.js
  13714. */
  13715. var MAX_LICENSE_REQUEST_FAILURES = 3;
  13716. /**
  13717. * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess
  13718. */
  13719. var KeySystems = {
  13720. WIDEVINE: 'com.widevine.alpha',
  13721. PLAYREADY: 'com.microsoft.playready'
  13722. };
  13723. /**
  13724. * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration
  13725. * @param {Array<string>} audioCodecs List of required audio codecs to support
  13726. * @param {Array<string>} videoCodecs List of required video codecs to support
  13727. * @param {object} drmSystemOptions Optional parameters/requirements for the key-system
  13728. * @returns {Array<MediaSystemConfiguration>} An array of supported configurations
  13729. */
  13730. var createWidevineMediaKeySystemConfigurations = function createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs, drmSystemOptions) {
  13731. /* jshint ignore:line */
  13732. var baseConfig = {
  13733. //initDataTypes: ['keyids', 'mp4'],
  13734. //label: "",
  13735. //persistentState: "not-allowed", // or "required" ?
  13736. //distinctiveIdentifier: "not-allowed", // or "required" ?
  13737. //sessionTypes: ['temporary'],
  13738. videoCapabilities: [
  13739. //{ contentType: 'video/mp4; codecs="avc1.42E01E"' }
  13740. ]
  13741. };
  13742. videoCodecs.forEach(function (codec) {
  13743. baseConfig.videoCapabilities.push({
  13744. contentType: 'video/mp4; codecs="' + codec + '"'
  13745. });
  13746. });
  13747. return [baseConfig];
  13748. };
  13749. /**
  13750. * The idea here is to handle key-system (and their respective platforms) specific configuration differences
  13751. * in order to work with the local requestMediaKeySystemAccess method.
  13752. *
  13753. * We can also rule-out platform-related key-system support at this point by throwing an error or returning null.
  13754. *
  13755. * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum
  13756. * @param {Array<string>} audioCodecs List of required audio codecs to support
  13757. * @param {Array<string>} videoCodecs List of required video codecs to support
  13758. * @returns {Array<MediaSystemConfiguration> | null} A non-empty Array of MediaKeySystemConfiguration objects or `null`
  13759. */
  13760. var getSupportedMediaKeySystemConfigurations = function getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs) {
  13761. switch (keySystem) {
  13762. case KeySystems.WIDEVINE:
  13763. return createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs);
  13764. default:
  13765. throw Error('Unknown key-system: ' + keySystem);
  13766. }
  13767. };
  13768. /**
  13769. * Controller to deal with encrypted media extensions (EME)
  13770. * @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API
  13771. *
  13772. * @class
  13773. * @constructor
  13774. */
  13775. var eme_controller_EMEController = function (_EventHandler) {
  13776. eme_controller__inherits(EMEController, _EventHandler);
  13777. /**
  13778. * @constructs
  13779. * @param {Hls} hls Our Hls.js instance
  13780. */
  13781. function EMEController(hls) {
  13782. eme_controller__classCallCheck(this, EMEController);
  13783. var _this = eme_controller__possibleConstructorReturn(this, _EventHandler.call(this, hls, events["a" /* default */].MEDIA_ATTACHED, events["a" /* default */].MANIFEST_PARSED));
  13784. _this._widevineLicenseUrl = hls.config.widevineLicenseUrl;
  13785. _this._licenseXhrSetup = hls.config.licenseXhrSetup;
  13786. _this._emeEnabled = hls.config.emeEnabled;
  13787. _this._requestMediaKeySystemAccess = hls.config.requestMediaKeySystemAccessFunc;
  13788. _this._mediaKeysList = [];
  13789. _this._media = null;
  13790. _this._hasSetMediaKeys = false;
  13791. _this._isMediaEncrypted = false;
  13792. _this._requestLicenseFailureCount = 0;
  13793. return _this;
  13794. }
  13795. /**
  13796. *
  13797. * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum
  13798. * @returns {string} License server URL for key-system (if any configured, otherwise causes error)
  13799. */
  13800. EMEController.prototype.getLicenseServerUrl = function getLicenseServerUrl(keySystem) {
  13801. var url = void 0;
  13802. switch (keySystem) {
  13803. case KeySystems.WIDEVINE:
  13804. url = this._widevineLicenseUrl;
  13805. break;
  13806. default:
  13807. url = null;
  13808. break;
  13809. }
  13810. if (!url) {
  13811. logger["b" /* logger */].error('No license server URL configured for key-system "' + keySystem + '"');
  13812. this.hls.trigger(events["a" /* default */].ERROR, {
  13813. type: errors["b" /* ErrorTypes */].KEY_SYSTEM_ERROR,
  13814. details: errors["a" /* ErrorDetails */].KEY_SYSTEM_LICENSE_REQUEST_FAILED,
  13815. fatal: true
  13816. });
  13817. }
  13818. return url;
  13819. };
  13820. /**
  13821. * Requests access object and adds it to our list upon success
  13822. * @private
  13823. * @param {string} keySystem System ID (see `KeySystems`)
  13824. * @param {Array<string>} audioCodecs List of required audio codecs to support
  13825. * @param {Array<string>} videoCodecs List of required video codecs to support
  13826. */
  13827. EMEController.prototype._attemptKeySystemAccess = function _attemptKeySystemAccess(keySystem, audioCodecs, videoCodecs) {
  13828. var _this2 = this;
  13829. // TODO: add other DRM "options"
  13830. var mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs);
  13831. if (!mediaKeySystemConfigs) {
  13832. logger["b" /* logger */].warn('Can not create config for key-system (maybe because platform is not supported):', keySystem);
  13833. return;
  13834. }
  13835. logger["b" /* logger */].log('Requesting encrypted media key-system access');
  13836. // expecting interface like window.navigator.requestMediaKeySystemAccess
  13837. this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs).then(function (mediaKeySystemAccess) {
  13838. _this2._onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess);
  13839. }).catch(function (err) {
  13840. logger["b" /* logger */].error('Failed to obtain key-system "' + keySystem + '" access:', err);
  13841. });
  13842. };
  13843. /**
  13844. * Handles obtaining access to a key-system
  13845. *
  13846. * @param {string} keySystem
  13847. * @param {MediaKeySystemAccess} mediaKeySystemAccess https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemAccess
  13848. */
  13849. EMEController.prototype._onMediaKeySystemAccessObtained = function _onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess) {
  13850. var _this3 = this;
  13851. logger["b" /* logger */].log('Access for key-system "' + keySystem + '" obtained');
  13852. var mediaKeysListItem = {
  13853. mediaKeys: null,
  13854. mediaKeysSession: null,
  13855. mediaKeysSessionInitialized: false,
  13856. mediaKeySystemAccess: mediaKeySystemAccess,
  13857. mediaKeySystemDomain: keySystem
  13858. };
  13859. this._mediaKeysList.push(mediaKeysListItem);
  13860. mediaKeySystemAccess.createMediaKeys().then(function (mediaKeys) {
  13861. mediaKeysListItem.mediaKeys = mediaKeys;
  13862. logger["b" /* logger */].log('Media-keys created for key-system "' + keySystem + '"');
  13863. _this3._onMediaKeysCreated();
  13864. }).catch(function (err) {
  13865. logger["b" /* logger */].error('Failed to create media-keys:', err);
  13866. });
  13867. };
  13868. /**
  13869. * Handles key-creation (represents access to CDM). We are going to create key-sessions upon this
  13870. * for all existing keys where no session exists yet.
  13871. */
  13872. EMEController.prototype._onMediaKeysCreated = function _onMediaKeysCreated() {
  13873. var _this4 = this;
  13874. // check for all key-list items if a session exists, otherwise, create one
  13875. this._mediaKeysList.forEach(function (mediaKeysListItem) {
  13876. if (!mediaKeysListItem.mediaKeysSession) {
  13877. mediaKeysListItem.mediaKeysSession = mediaKeysListItem.mediaKeys.createSession();
  13878. _this4._onNewMediaKeySession(mediaKeysListItem.mediaKeysSession);
  13879. }
  13880. });
  13881. };
  13882. /**
  13883. *
  13884. * @param {*} keySession
  13885. */
  13886. EMEController.prototype._onNewMediaKeySession = function _onNewMediaKeySession(keySession) {
  13887. var _this5 = this;
  13888. logger["b" /* logger */].log('New key-system session ' + keySession.sessionId);
  13889. keySession.addEventListener('message', function (event) {
  13890. _this5._onKeySessionMessage(keySession, event.message);
  13891. }, false);
  13892. };
  13893. EMEController.prototype._onKeySessionMessage = function _onKeySessionMessage(keySession, message) {
  13894. logger["b" /* logger */].log('Got EME message event, creating license request');
  13895. this._requestLicense(message, function (data) {
  13896. logger["b" /* logger */].log('Received license data, updating key-session');
  13897. keySession.update(data);
  13898. });
  13899. };
  13900. EMEController.prototype._onMediaEncrypted = function _onMediaEncrypted(initDataType, initData) {
  13901. logger["b" /* logger */].log('Media is encrypted using "' + initDataType + '" init data type');
  13902. this._isMediaEncrypted = true;
  13903. this._mediaEncryptionInitDataType = initDataType;
  13904. this._mediaEncryptionInitData = initData;
  13905. this._attemptSetMediaKeys();
  13906. this._generateRequestWithPreferredKeySession();
  13907. };
  13908. EMEController.prototype._attemptSetMediaKeys = function _attemptSetMediaKeys() {
  13909. if (!this._hasSetMediaKeys) {
  13910. // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?
  13911. var keysListItem = this._mediaKeysList[0];
  13912. if (!keysListItem || !keysListItem.mediaKeys) {
  13913. logger["b" /* logger */].error('Fatal: Media is encrypted but no CDM access or no keys have been obtained yet');
  13914. this.hls.trigger(events["a" /* default */].ERROR, {
  13915. type: errors["b" /* ErrorTypes */].KEY_SYSTEM_ERROR,
  13916. details: errors["a" /* ErrorDetails */].KEY_SYSTEM_NO_KEYS,
  13917. fatal: true
  13918. });
  13919. return;
  13920. }
  13921. logger["b" /* logger */].log('Setting keys for encrypted media');
  13922. this._media.setMediaKeys(keysListItem.mediaKeys);
  13923. this._hasSetMediaKeys = true;
  13924. }
  13925. };
  13926. EMEController.prototype._generateRequestWithPreferredKeySession = function _generateRequestWithPreferredKeySession() {
  13927. var _this6 = this;
  13928. // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?
  13929. var keysListItem = this._mediaKeysList[0];
  13930. if (!keysListItem) {
  13931. logger["b" /* logger */].error('Fatal: Media is encrypted but not any key-system access has been obtained yet');
  13932. this.hls.trigger(events["a" /* default */].ERROR, {
  13933. type: errors["b" /* ErrorTypes */].KEY_SYSTEM_ERROR,
  13934. details: errors["a" /* ErrorDetails */].KEY_SYSTEM_NO_ACCESS,
  13935. fatal: true
  13936. });
  13937. return;
  13938. }
  13939. if (keysListItem.mediaKeysSessionInitialized) {
  13940. logger["b" /* logger */].warn('Key-Session already initialized but requested again');
  13941. return;
  13942. }
  13943. var keySession = keysListItem.mediaKeysSession;
  13944. if (!keySession) {
  13945. logger["b" /* logger */].error('Fatal: Media is encrypted but no key-session existing');
  13946. this.hls.trigger(events["a" /* default */].ERROR, {
  13947. type: errors["b" /* ErrorTypes */].KEY_SYSTEM_ERROR,
  13948. details: errors["a" /* ErrorDetails */].KEY_SYSTEM_NO_SESSION,
  13949. fatal: true
  13950. });
  13951. }
  13952. var initDataType = this._mediaEncryptionInitDataType;
  13953. var initData = this._mediaEncryptionInitData;
  13954. logger["b" /* logger */].log('Generating key-session request for "' + initDataType + '" init data type');
  13955. keysListItem.mediaKeysSessionInitialized = true;
  13956. keySession.generateRequest(initDataType, initData).then(function () {
  13957. logger["b" /* logger */].debug('Key-session generation succeeded');
  13958. }).catch(function (err) {
  13959. logger["b" /* logger */].error('Error generating key-session request:', err);
  13960. _this6.hls.trigger(events["a" /* default */].ERROR, {
  13961. type: errors["b" /* ErrorTypes */].KEY_SYSTEM_ERROR,
  13962. details: errors["a" /* ErrorDetails */].KEY_SYSTEM_NO_SESSION,
  13963. fatal: false
  13964. });
  13965. });
  13966. };
  13967. /**
  13968. * @param {string} url License server URL
  13969. * @param {ArrayBuffer} keyMessage Message data issued by key-system
  13970. * @param {function} callback Called when XHR has succeeded
  13971. * @returns {XMLHttpRequest} Unsent (but opened state) XHR object
  13972. */
  13973. EMEController.prototype._createLicenseXhr = function _createLicenseXhr(url, keyMessage, callback) {
  13974. var xhr = new XMLHttpRequest();
  13975. var licenseXhrSetup = this._licenseXhrSetup;
  13976. try {
  13977. if (licenseXhrSetup) {
  13978. try {
  13979. licenseXhrSetup(xhr, url);
  13980. } catch (e) {
  13981. // let's try to open before running setup
  13982. xhr.open('POST', url, true);
  13983. licenseXhrSetup(xhr, url);
  13984. }
  13985. }
  13986. // if licenseXhrSetup did not yet call open, let's do it now
  13987. if (!xhr.readyState) {
  13988. xhr.open('POST', url, true);
  13989. }
  13990. } catch (e) {
  13991. // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
  13992. logger["b" /* logger */].error('Error setting up key-system license XHR', e);
  13993. this.hls.trigger(events["a" /* default */].ERROR, {
  13994. type: errors["b" /* ErrorTypes */].KEY_SYSTEM_ERROR,
  13995. details: errors["a" /* ErrorDetails */].KEY_SYSTEM_LICENSE_REQUEST_FAILED,
  13996. fatal: true
  13997. });
  13998. return;
  13999. }
  14000. xhr.responseType = 'arraybuffer';
  14001. xhr.onreadystatechange = this._onLicenseRequestReadyStageChange.bind(this, xhr, url, keyMessage, callback);
  14002. return xhr;
  14003. };
  14004. /**
  14005. * @param {XMLHttpRequest} xhr
  14006. * @param {string} url License server URL
  14007. * @param {ArrayBuffer} keyMessage Message data issued by key-system
  14008. * @param {function} callback Called when XHR has succeeded
  14009. *
  14010. */
  14011. EMEController.prototype._onLicenseRequestReadyStageChange = function _onLicenseRequestReadyStageChange(xhr, url, keyMessage, callback) {
  14012. switch (xhr.readyState) {
  14013. case 4:
  14014. if (xhr.status === 200) {
  14015. this._requestLicenseFailureCount = 0;
  14016. logger["b" /* logger */].log('License request succeeded');
  14017. callback(xhr.response);
  14018. } else {
  14019. logger["b" /* logger */].error('License Request XHR failed (' + url + '). Status: ' + xhr.status + ' (' + xhr.statusText + ')');
  14020. this._requestLicenseFailureCount++;
  14021. if (this._requestLicenseFailureCount <= MAX_LICENSE_REQUEST_FAILURES) {
  14022. var attemptsLeft = MAX_LICENSE_REQUEST_FAILURES - this._requestLicenseFailureCount + 1;
  14023. logger["b" /* logger */].warn('Retrying license request, ' + attemptsLeft + ' attempts left');
  14024. this._requestLicense(keyMessage, callback);
  14025. return;
  14026. }
  14027. this.hls.trigger(events["a" /* default */].ERROR, {
  14028. type: errors["b" /* ErrorTypes */].KEY_SYSTEM_ERROR,
  14029. details: errors["a" /* ErrorDetails */].KEY_SYSTEM_LICENSE_REQUEST_FAILED,
  14030. fatal: true
  14031. });
  14032. }
  14033. break;
  14034. }
  14035. };
  14036. /**
  14037. * @param {object} keysListItem
  14038. * @param {ArrayBuffer} keyMessage
  14039. * @returns {ArrayBuffer} Challenge data posted to license server
  14040. */
  14041. EMEController.prototype._generateLicenseRequestChallenge = function _generateLicenseRequestChallenge(keysListItem, keyMessage) {
  14042. var challenge = void 0;
  14043. if (keysListItem.mediaKeySystemDomain === KeySystems.PLAYREADY) {
  14044. logger["b" /* logger */].error('PlayReady is not supported (yet)');
  14045. // from https://github.com/MicrosoftEdge/Demos/blob/master/eme/scripts/demo.js
  14046. /*
  14047. if (this.licenseType !== this.LICENSE_TYPE_WIDEVINE) {
  14048. // For PlayReady CDMs, we need to dig the Challenge out of the XML.
  14049. var keyMessageXml = new DOMParser().parseFromString(String.fromCharCode.apply(null, new Uint16Array(keyMessage)), 'application/xml');
  14050. if (keyMessageXml.getElementsByTagName('Challenge')[0]) {
  14051. challenge = atob(keyMessageXml.getElementsByTagName('Challenge')[0].childNodes[0].nodeValue);
  14052. } else {
  14053. throw 'Cannot find <Challenge> in key message';
  14054. }
  14055. var headerNames = keyMessageXml.getElementsByTagName('name');
  14056. var headerValues = keyMessageXml.getElementsByTagName('value');
  14057. if (headerNames.length !== headerValues.length) {
  14058. throw 'Mismatched header <name>/<value> pair in key message';
  14059. }
  14060. for (var i = 0; i < headerNames.length; i++) {
  14061. xhr.setRequestHeader(headerNames[i].childNodes[0].nodeValue, headerValues[i].childNodes[0].nodeValue);
  14062. }
  14063. }
  14064. */
  14065. } else if (keysListItem.mediaKeySystemDomain === KeySystems.WIDEVINE) {
  14066. // For Widevine CDMs, the challenge is the keyMessage.
  14067. challenge = keyMessage;
  14068. } else {
  14069. logger["b" /* logger */].error('Unsupported key-system:', keysListItem.mediaKeySystemDomain);
  14070. }
  14071. return challenge;
  14072. };
  14073. EMEController.prototype._requestLicense = function _requestLicense(keyMessage, callback) {
  14074. logger["b" /* logger */].log('Requesting content license for key-system');
  14075. var keysListItem = this._mediaKeysList[0];
  14076. if (!keysListItem) {
  14077. logger["b" /* logger */].error('Fatal error: Media is encrypted but no key-system access has been obtained yet');
  14078. this.hls.trigger(events["a" /* default */].ERROR, {
  14079. type: errors["b" /* ErrorTypes */].KEY_SYSTEM_ERROR,
  14080. details: errors["a" /* ErrorDetails */].KEY_SYSTEM_NO_ACCESS,
  14081. fatal: true
  14082. });
  14083. return;
  14084. }
  14085. var url = this.getLicenseServerUrl(keysListItem.mediaKeySystemDomain);
  14086. var xhr = this._createLicenseXhr(url, keyMessage, callback);
  14087. logger["b" /* logger */].log('Sending license request to URL: ' + url);
  14088. xhr.send(this._generateLicenseRequestChallenge(keysListItem, keyMessage));
  14089. };
  14090. EMEController.prototype.onMediaAttached = function onMediaAttached(data) {
  14091. var _this7 = this;
  14092. if (!this._emeEnabled) {
  14093. return;
  14094. }
  14095. var media = data.media;
  14096. // keep reference of media
  14097. this._media = media;
  14098. // FIXME: also handle detaching media !
  14099. media.addEventListener('encrypted', function (e) {
  14100. _this7._onMediaEncrypted(e.initDataType, e.initData);
  14101. });
  14102. };
  14103. EMEController.prototype.onManifestParsed = function onManifestParsed(data) {
  14104. if (!this._emeEnabled) {
  14105. return;
  14106. }
  14107. var audioCodecs = data.levels.map(function (level) {
  14108. return level.audioCodec;
  14109. });
  14110. var videoCodecs = data.levels.map(function (level) {
  14111. return level.videoCodec;
  14112. });
  14113. this._attemptKeySystemAccess(KeySystems.WIDEVINE, audioCodecs, videoCodecs);
  14114. };
  14115. eme_controller__createClass(EMEController, [{
  14116. key: 'requestMediaKeySystemAccess',
  14117. get: function get() {
  14118. if (!this._requestMediaKeySystemAccess) {
  14119. throw new Error('No requestMediaKeySystemAccess function configured');
  14120. }
  14121. return this._requestMediaKeySystemAccess;
  14122. }
  14123. }]);
  14124. return EMEController;
  14125. }(event_handler);
  14126. /* harmony default export */ var eme_controller = (eme_controller_EMEController);
  14127. // CONCATENATED MODULE: ./src/helper/mediakeys-helper.js
  14128. var requestMediaKeySystemAccess = function () {
  14129. if (window.navigator && window.navigator.requestMediaKeySystemAccess) {
  14130. return window.navigator.requestMediaKeySystemAccess.bind(window.navigator);
  14131. } else {
  14132. return null;
  14133. }
  14134. }();
  14135. // CONCATENATED MODULE: ./src/config.js
  14136. /**
  14137. * HLS config
  14138. */
  14139. //import FetchLoader from './utils/fetch-loader';
  14140. var hlsDefaultConfig = {
  14141. autoStartLoad: true, // used by stream-controller
  14142. startPosition: -1, // used by stream-controller
  14143. defaultAudioCodec: undefined, // used by stream-controller
  14144. debug: false, // used by logger
  14145. capLevelOnFPSDrop: false, // used by fps-controller
  14146. capLevelToPlayerSize: false, // used by cap-level-controller
  14147. initialLiveManifestSize: 1, // used by stream-controller
  14148. maxBufferLength: 30, // used by stream-controller
  14149. maxBufferSize: 60 * 1000 * 1000, // used by stream-controller
  14150. maxBufferHole: 0.5, // used by stream-controller
  14151. maxSeekHole: 2, // used by stream-controller
  14152. lowBufferWatchdogPeriod: 0.5, // used by stream-controller
  14153. highBufferWatchdogPeriod: 3, // used by stream-controller
  14154. nudgeOffset: 0.1, // used by stream-controller
  14155. nudgeMaxRetry: 3, // used by stream-controller
  14156. maxFragLookUpTolerance: 0.25, // used by stream-controller
  14157. liveSyncDurationCount: 3, // used by stream-controller
  14158. liveMaxLatencyDurationCount: Infinity, // used by stream-controller
  14159. liveSyncDuration: undefined, // used by stream-controller
  14160. liveMaxLatencyDuration: undefined, // used by stream-controller
  14161. liveDurationInfinity: false, // used by buffer-controller
  14162. maxMaxBufferLength: 600, // used by stream-controller
  14163. enableWorker: true, // used by demuxer
  14164. enableSoftwareAES: true, // used by decrypter
  14165. manifestLoadingTimeOut: 10000, // used by playlist-loader
  14166. manifestLoadingMaxRetry: 1, // used by playlist-loader
  14167. manifestLoadingRetryDelay: 1000, // used by playlist-loader
  14168. manifestLoadingMaxRetryTimeout: 64000, // used by playlist-loader
  14169. startLevel: undefined, // used by level-controller
  14170. levelLoadingTimeOut: 10000, // used by playlist-loader
  14171. levelLoadingMaxRetry: 4, // used by playlist-loader
  14172. levelLoadingRetryDelay: 1000, // used by playlist-loader
  14173. levelLoadingMaxRetryTimeout: 64000, // used by playlist-loader
  14174. fragLoadingTimeOut: 20000, // used by fragment-loader
  14175. fragLoadingMaxRetry: 6, // used by fragment-loader
  14176. fragLoadingRetryDelay: 1000, // used by fragment-loader
  14177. fragLoadingMaxRetryTimeout: 64000, // used by fragment-loader
  14178. fragLoadingLoopThreshold: 3, // used by stream-controller
  14179. startFragPrefetch: false, // used by stream-controller
  14180. fpsDroppedMonitoringPeriod: 5000, // used by fps-controller
  14181. fpsDroppedMonitoringThreshold: 0.2, // used by fps-controller
  14182. appendErrorMaxRetry: 3, // used by buffer-controller
  14183. loader: xhr_loader,
  14184. //loader: FetchLoader,
  14185. fLoader: undefined,
  14186. pLoader: undefined,
  14187. xhrSetup: undefined,
  14188. licenseXhrSetup: undefined, // used by eme-controller
  14189. fetchSetup: undefined,
  14190. abrController: abr_controller,
  14191. bufferController: buffer_controller,
  14192. capLevelController: cap_level_controller,
  14193. fpsController: fps_controller,
  14194. stretchShortVideoTrack: false, // used by mp4-remuxer
  14195. maxAudioFramesDrift: 1, // used by mp4-remuxer
  14196. forceKeyFrameOnDiscontinuity: true, // used by ts-demuxer
  14197. abrEwmaFastLive: 3, // used by abr-controller
  14198. abrEwmaSlowLive: 9, // used by abr-controller
  14199. abrEwmaFastVoD: 3, // used by abr-controller
  14200. abrEwmaSlowVoD: 9, // used by abr-controller
  14201. abrEwmaDefaultEstimate: 5e5, // 500 kbps // used by abr-controller
  14202. abrBandWidthFactor: 0.95, // used by abr-controller
  14203. abrBandWidthUpFactor: 0.7, // used by abr-controller
  14204. abrMaxWithRealBitrate: false, // used by abr-controller
  14205. maxStarvationDelay: 4, // used by abr-controller
  14206. maxLoadingDelay: 4, // used by abr-controller
  14207. minAutoBitrate: 0, // used by hls
  14208. emeEnabled: false, // used by eme-controller
  14209. widevineLicenseUrl: undefined, // used by eme-controller
  14210. requestMediaKeySystemAccessFunc: requestMediaKeySystemAccess // used by eme-controller
  14211. };
  14212. if (true) {
  14213. hlsDefaultConfig.subtitleStreamController = subtitle_stream_controller;
  14214. hlsDefaultConfig.subtitleTrackController = subtitle_track_controller;
  14215. hlsDefaultConfig.timelineController = timeline_controller;
  14216. hlsDefaultConfig.cueHandler = cues_namespaceObject;
  14217. hlsDefaultConfig.enableCEA708Captions = true; // used by timeline-controller
  14218. hlsDefaultConfig.enableWebVTT = true; // used by timeline-controller
  14219. hlsDefaultConfig.captionsTextTrack1Label = 'English'; // used by timeline-controller
  14220. hlsDefaultConfig.captionsTextTrack1LanguageCode = 'en'; // used by timeline-controller
  14221. hlsDefaultConfig.captionsTextTrack2Label = 'Spanish'; // used by timeline-controller
  14222. hlsDefaultConfig.captionsTextTrack2LanguageCode = 'es'; // used by timeline-controller
  14223. }
  14224. if (true) {
  14225. hlsDefaultConfig.audioStreamController = audio_stream_controller;
  14226. hlsDefaultConfig.audioTrackController = audio_track_controller;
  14227. }
  14228. if (true) {
  14229. hlsDefaultConfig.emeController = eme_controller;
  14230. }
  14231. // CONCATENATED MODULE: ./src/hls.js
  14232. var hls__createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  14233. function hls__classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  14234. /**
  14235. * HLS interface
  14236. */
  14237. // polyfill for IE11
  14238. __webpack_require__(12);
  14239. var hls_Hls = function () {
  14240. Hls.isSupported = function isSupported() {
  14241. return is_supported_isSupported();
  14242. };
  14243. hls__createClass(Hls, null, [{
  14244. key: 'version',
  14245. get: function get() {
  14246. return "0.8.9";
  14247. }
  14248. }, {
  14249. key: 'Events',
  14250. get: function get() {
  14251. return events["a" /* default */];
  14252. }
  14253. }, {
  14254. key: 'ErrorTypes',
  14255. get: function get() {
  14256. return errors["b" /* ErrorTypes */];
  14257. }
  14258. }, {
  14259. key: 'ErrorDetails',
  14260. get: function get() {
  14261. return errors["a" /* ErrorDetails */];
  14262. }
  14263. }, {
  14264. key: 'DefaultConfig',
  14265. get: function get() {
  14266. if (!Hls.defaultConfig) {
  14267. return hlsDefaultConfig;
  14268. }
  14269. return Hls.defaultConfig;
  14270. },
  14271. set: function set(defaultConfig) {
  14272. Hls.defaultConfig = defaultConfig;
  14273. }
  14274. }]);
  14275. function Hls() {
  14276. var _this = this;
  14277. var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  14278. hls__classCallCheck(this, Hls);
  14279. var defaultConfig = Hls.DefaultConfig;
  14280. if ((config.liveSyncDurationCount || config.liveMaxLatencyDurationCount) && (config.liveSyncDuration || config.liveMaxLatencyDuration)) {
  14281. throw new Error('Illegal hls.js config: don\'t mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration');
  14282. }
  14283. for (var prop in defaultConfig) {
  14284. if (prop in config) {
  14285. continue;
  14286. }
  14287. config[prop] = defaultConfig[prop];
  14288. }
  14289. if (config.liveMaxLatencyDurationCount !== undefined && config.liveMaxLatencyDurationCount <= config.liveSyncDurationCount) {
  14290. throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be gt "liveSyncDurationCount"');
  14291. }
  14292. if (config.liveMaxLatencyDuration !== undefined && (config.liveMaxLatencyDuration <= config.liveSyncDuration || config.liveSyncDuration === undefined)) {
  14293. throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be gt "liveSyncDuration"');
  14294. }
  14295. Object(logger["a" /* enableLogs */])(config.debug);
  14296. this.config = config;
  14297. this._autoLevelCapping = -1;
  14298. // observer setup
  14299. var observer = this.observer = new events_default.a();
  14300. observer.trigger = function trigger(event) {
  14301. for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  14302. data[_key - 1] = arguments[_key];
  14303. }
  14304. observer.emit.apply(observer, [event, event].concat(data));
  14305. };
  14306. observer.off = function off(event) {
  14307. for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  14308. data[_key2 - 1] = arguments[_key2];
  14309. }
  14310. observer.removeListener.apply(observer, [event].concat(data));
  14311. };
  14312. this.on = observer.on.bind(observer);
  14313. this.off = observer.off.bind(observer);
  14314. this.trigger = observer.trigger.bind(observer);
  14315. // core controllers and network loaders
  14316. var abrController = this.abrController = new config.abrController(this);
  14317. var bufferController = new config.bufferController(this);
  14318. var capLevelController = new config.capLevelController(this);
  14319. var fpsController = new config.fpsController(this);
  14320. var playListLoader = new playlist_loader(this);
  14321. var fragmentLoader = new fragment_loader(this);
  14322. var keyLoader = new key_loader(this);
  14323. var id3TrackController = new id3_track_controller(this);
  14324. // network controllers
  14325. var levelController = this.levelController = new level_controller(this);
  14326. var streamController = this.streamController = new stream_controller(this);
  14327. var networkControllers = [levelController, streamController];
  14328. // optional audio stream controller
  14329. var Controller = config.audioStreamController;
  14330. if (Controller) {
  14331. networkControllers.push(new Controller(this));
  14332. }
  14333. this.networkControllers = networkControllers;
  14334. var coreComponents = [playListLoader, fragmentLoader, keyLoader, abrController, bufferController, capLevelController, fpsController, id3TrackController];
  14335. // optional audio track and subtitle controller
  14336. Controller = config.audioTrackController;
  14337. if (Controller) {
  14338. var audioTrackController = new Controller(this);
  14339. this.audioTrackController = audioTrackController;
  14340. coreComponents.push(audioTrackController);
  14341. }
  14342. Controller = config.subtitleTrackController;
  14343. if (Controller) {
  14344. var subtitleTrackController = new Controller(this);
  14345. this.subtitleTrackController = subtitleTrackController;
  14346. coreComponents.push(subtitleTrackController);
  14347. }
  14348. Controller = config.emeController;
  14349. if (Controller) {
  14350. var emeController = new Controller(this);
  14351. this.emeController = emeController;
  14352. coreComponents.push(emeController);
  14353. }
  14354. // optional subtitle controller
  14355. [config.subtitleStreamController, config.timelineController].forEach(function (Controller) {
  14356. if (Controller) {
  14357. coreComponents.push(new Controller(_this));
  14358. }
  14359. });
  14360. this.coreComponents = coreComponents;
  14361. }
  14362. Hls.prototype.destroy = function destroy() {
  14363. logger["b" /* logger */].log('destroy');
  14364. this.trigger(events["a" /* default */].DESTROYING);
  14365. this.detachMedia();
  14366. this.coreComponents.concat(this.networkControllers).forEach(function (component) {
  14367. component.destroy();
  14368. });
  14369. this.url = null;
  14370. this.observer.removeAllListeners();
  14371. this._autoLevelCapping = -1;
  14372. };
  14373. Hls.prototype.attachMedia = function attachMedia(media) {
  14374. logger["b" /* logger */].log('attachMedia');
  14375. this.media = media;
  14376. this.trigger(events["a" /* default */].MEDIA_ATTACHING, { media: media });
  14377. };
  14378. Hls.prototype.detachMedia = function detachMedia() {
  14379. logger["b" /* logger */].log('detachMedia');
  14380. this.trigger(events["a" /* default */].MEDIA_DETACHING);
  14381. this.media = null;
  14382. };
  14383. Hls.prototype.loadSource = function loadSource(url) {
  14384. url = url_toolkit_default.a.buildAbsoluteURL(window.location.href, url, { alwaysNormalize: true });
  14385. logger["b" /* logger */].log('loadSource:' + url);
  14386. this.url = url;
  14387. // when attaching to a source URL, trigger a playlist load
  14388. this.trigger(events["a" /* default */].MANIFEST_LOADING, { url: url });
  14389. };
  14390. Hls.prototype.startLoad = function startLoad() {
  14391. var startPosition = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : -1;
  14392. logger["b" /* logger */].log('startLoad(' + startPosition + ')');
  14393. this.networkControllers.forEach(function (controller) {
  14394. controller.startLoad(startPosition);
  14395. });
  14396. };
  14397. Hls.prototype.stopLoad = function stopLoad() {
  14398. logger["b" /* logger */].log('stopLoad');
  14399. this.networkControllers.forEach(function (controller) {
  14400. controller.stopLoad();
  14401. });
  14402. };
  14403. Hls.prototype.swapAudioCodec = function swapAudioCodec() {
  14404. logger["b" /* logger */].log('swapAudioCodec');
  14405. this.streamController.swapAudioCodec();
  14406. };
  14407. Hls.prototype.recoverMediaError = function recoverMediaError() {
  14408. logger["b" /* logger */].log('recoverMediaError');
  14409. var media = this.media;
  14410. this.detachMedia();
  14411. this.attachMedia(media);
  14412. };
  14413. /** Return all quality levels **/
  14414. hls__createClass(Hls, [{
  14415. key: 'levels',
  14416. get: function get() {
  14417. return this.levelController.levels;
  14418. }
  14419. /** Return current playback quality level **/
  14420. }, {
  14421. key: 'currentLevel',
  14422. get: function get() {
  14423. return this.streamController.currentLevel;
  14424. }
  14425. /* set quality level immediately (-1 for automatic level selection) */
  14426. ,
  14427. set: function set(newLevel) {
  14428. logger["b" /* logger */].log('set currentLevel:' + newLevel);
  14429. this.loadLevel = newLevel;
  14430. this.streamController.immediateLevelSwitch();
  14431. }
  14432. /** Return next playback quality level (quality level of next fragment) **/
  14433. }, {
  14434. key: 'nextLevel',
  14435. get: function get() {
  14436. return this.streamController.nextLevel;
  14437. }
  14438. /* set quality level for next fragment (-1 for automatic level selection) */
  14439. ,
  14440. set: function set(newLevel) {
  14441. logger["b" /* logger */].log('set nextLevel:' + newLevel);
  14442. this.levelController.manualLevel = newLevel;
  14443. this.streamController.nextLevelSwitch();
  14444. }
  14445. /** Return the quality level of current/last loaded fragment **/
  14446. }, {
  14447. key: 'loadLevel',
  14448. get: function get() {
  14449. return this.levelController.level;
  14450. }
  14451. /* set quality level for current/next loaded fragment (-1 for automatic level selection) */
  14452. ,
  14453. set: function set(newLevel) {
  14454. logger["b" /* logger */].log('set loadLevel:' + newLevel);
  14455. this.levelController.manualLevel = newLevel;
  14456. }
  14457. /** Return the quality level of next loaded fragment **/
  14458. }, {
  14459. key: 'nextLoadLevel',
  14460. get: function get() {
  14461. return this.levelController.nextLoadLevel;
  14462. }
  14463. /** set quality level of next loaded fragment **/
  14464. ,
  14465. set: function set(level) {
  14466. this.levelController.nextLoadLevel = level;
  14467. }
  14468. /** Return first level (index of first level referenced in manifest)
  14469. **/
  14470. }, {
  14471. key: 'firstLevel',
  14472. get: function get() {
  14473. return Math.max(this.levelController.firstLevel, this.minAutoLevel);
  14474. }
  14475. /** set first level (index of first level referenced in manifest)
  14476. **/
  14477. ,
  14478. set: function set(newLevel) {
  14479. logger["b" /* logger */].log('set firstLevel:' + newLevel);
  14480. this.levelController.firstLevel = newLevel;
  14481. }
  14482. /** Return start level (level of first fragment that will be played back)
  14483. if not overrided by user, first level appearing in manifest will be used as start level
  14484. if -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)
  14485. **/
  14486. }, {
  14487. key: 'startLevel',
  14488. get: function get() {
  14489. return this.levelController.startLevel;
  14490. }
  14491. /** set start level (level of first fragment that will be played back)
  14492. if not overrided by user, first level appearing in manifest will be used as start level
  14493. if -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)
  14494. **/
  14495. ,
  14496. set: function set(newLevel) {
  14497. logger["b" /* logger */].log('set startLevel:' + newLevel);
  14498. var hls = this;
  14499. // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel
  14500. if (newLevel !== -1) {
  14501. newLevel = Math.max(newLevel, hls.minAutoLevel);
  14502. }
  14503. hls.levelController.startLevel = newLevel;
  14504. }
  14505. /** Return the capping/max level value that could be used by automatic level selection algorithm **/
  14506. }, {
  14507. key: 'autoLevelCapping',
  14508. get: function get() {
  14509. return this._autoLevelCapping;
  14510. }
  14511. /** set the capping/max level value that could be used by automatic level selection algorithm **/
  14512. ,
  14513. set: function set(newLevel) {
  14514. logger["b" /* logger */].log('set autoLevelCapping:' + newLevel);
  14515. this._autoLevelCapping = newLevel;
  14516. }
  14517. /* check if we are in automatic level selection mode */
  14518. }, {
  14519. key: 'autoLevelEnabled',
  14520. get: function get() {
  14521. return this.levelController.manualLevel === -1;
  14522. }
  14523. /* return manual level */
  14524. }, {
  14525. key: 'manualLevel',
  14526. get: function get() {
  14527. return this.levelController.manualLevel;
  14528. }
  14529. /* return min level selectable in auto mode according to config.minAutoBitrate */
  14530. }, {
  14531. key: 'minAutoLevel',
  14532. get: function get() {
  14533. var hls = this,
  14534. levels = hls.levels,
  14535. minAutoBitrate = hls.config.minAutoBitrate,
  14536. len = levels ? levels.length : 0;
  14537. for (var i = 0; i < len; i++) {
  14538. var levelNextBitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate;
  14539. if (levelNextBitrate > minAutoBitrate) {
  14540. return i;
  14541. }
  14542. }
  14543. return 0;
  14544. }
  14545. /* return max level selectable in auto mode according to autoLevelCapping */
  14546. }, {
  14547. key: 'maxAutoLevel',
  14548. get: function get() {
  14549. var hls = this;
  14550. var levels = hls.levels;
  14551. var autoLevelCapping = hls.autoLevelCapping;
  14552. var maxAutoLevel = void 0;
  14553. if (autoLevelCapping === -1 && levels && levels.length) {
  14554. maxAutoLevel = levels.length - 1;
  14555. } else {
  14556. maxAutoLevel = autoLevelCapping;
  14557. }
  14558. return maxAutoLevel;
  14559. }
  14560. // return next auto level
  14561. }, {
  14562. key: 'nextAutoLevel',
  14563. get: function get() {
  14564. var hls = this;
  14565. // ensure next auto level is between min and max auto level
  14566. return Math.min(Math.max(hls.abrController.nextAutoLevel, hls.minAutoLevel), hls.maxAutoLevel);
  14567. }
  14568. // this setter is used to force next auto level
  14569. // 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)
  14570. // forced value is valid for one fragment. upon succesful frag loading at forced level, this value will be resetted to -1 by ABR controller
  14571. ,
  14572. set: function set(nextLevel) {
  14573. var hls = this;
  14574. hls.abrController.nextAutoLevel = Math.max(hls.minAutoLevel, nextLevel);
  14575. }
  14576. /** get alternate audio tracks list from playlist **/
  14577. }, {
  14578. key: 'audioTracks',
  14579. get: function get() {
  14580. var audioTrackController = this.audioTrackController;
  14581. return audioTrackController ? audioTrackController.audioTracks : [];
  14582. }
  14583. /** get index of the selected audio track (index in audio track lists) **/
  14584. }, {
  14585. key: 'audioTrack',
  14586. get: function get() {
  14587. var audioTrackController = this.audioTrackController;
  14588. return audioTrackController ? audioTrackController.audioTrack : -1;
  14589. }
  14590. /** select an audio track, based on its index in audio track lists**/
  14591. ,
  14592. set: function set(audioTrackId) {
  14593. var audioTrackController = this.audioTrackController;
  14594. if (audioTrackController) {
  14595. audioTrackController.audioTrack = audioTrackId;
  14596. }
  14597. }
  14598. }, {
  14599. key: 'liveSyncPosition',
  14600. get: function get() {
  14601. return this.streamController.liveSyncPosition;
  14602. }
  14603. /** get alternate subtitle tracks list from playlist **/
  14604. }, {
  14605. key: 'subtitleTracks',
  14606. get: function get() {
  14607. var subtitleTrackController = this.subtitleTrackController;
  14608. return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
  14609. }
  14610. /** get index of the selected subtitle track (index in subtitle track lists) **/
  14611. }, {
  14612. key: 'subtitleTrack',
  14613. get: function get() {
  14614. var subtitleTrackController = this.subtitleTrackController;
  14615. return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
  14616. }
  14617. /** select an subtitle track, based on its index in subtitle track lists**/
  14618. ,
  14619. set: function set(subtitleTrackId) {
  14620. var subtitleTrackController = this.subtitleTrackController;
  14621. if (subtitleTrackController) {
  14622. subtitleTrackController.subtitleTrack = subtitleTrackId;
  14623. }
  14624. }
  14625. }, {
  14626. key: 'subtitleDisplay',
  14627. get: function get() {
  14628. var subtitleTrackController = this.subtitleTrackController;
  14629. return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
  14630. },
  14631. set: function set(value) {
  14632. var subtitleTrackController = this.subtitleTrackController;
  14633. if (subtitleTrackController) {
  14634. subtitleTrackController.subtitleDisplay = value;
  14635. }
  14636. }
  14637. }]);
  14638. return Hls;
  14639. }();
  14640. /* harmony default export */ var src_hls = __webpack_exports__["default"] = (hls_Hls);
  14641. /***/ }),
  14642. /* 10 */
  14643. /***/ (function(module, exports, __webpack_require__) {
  14644. function webpackBootstrapFunc (modules) {
  14645. /******/ // The module cache
  14646. /******/ var installedModules = {};
  14647. /******/ // The require function
  14648. /******/ function __webpack_require__(moduleId) {
  14649. /******/ // Check if module is in cache
  14650. /******/ if(installedModules[moduleId])
  14651. /******/ return installedModules[moduleId].exports;
  14652. /******/ // Create a new module (and put it into the cache)
  14653. /******/ var module = installedModules[moduleId] = {
  14654. /******/ i: moduleId,
  14655. /******/ l: false,
  14656. /******/ exports: {}
  14657. /******/ };
  14658. /******/ // Execute the module function
  14659. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  14660. /******/ // Flag the module as loaded
  14661. /******/ module.l = true;
  14662. /******/ // Return the exports of the module
  14663. /******/ return module.exports;
  14664. /******/ }
  14665. /******/ // expose the modules object (__webpack_modules__)
  14666. /******/ __webpack_require__.m = modules;
  14667. /******/ // expose the module cache
  14668. /******/ __webpack_require__.c = installedModules;
  14669. /******/ // identity function for calling harmony imports with the correct context
  14670. /******/ __webpack_require__.i = function(value) { return value; };
  14671. /******/ // define getter function for harmony exports
  14672. /******/ __webpack_require__.d = function(exports, name, getter) {
  14673. /******/ if(!__webpack_require__.o(exports, name)) {
  14674. /******/ Object.defineProperty(exports, name, {
  14675. /******/ configurable: false,
  14676. /******/ enumerable: true,
  14677. /******/ get: getter
  14678. /******/ });
  14679. /******/ }
  14680. /******/ };
  14681. /******/ // getDefaultExport function for compatibility with non-harmony modules
  14682. /******/ __webpack_require__.n = function(module) {
  14683. /******/ var getter = module && module.__esModule ?
  14684. /******/ function getDefault() { return module['default']; } :
  14685. /******/ function getModuleExports() { return module; };
  14686. /******/ __webpack_require__.d(getter, 'a', getter);
  14687. /******/ return getter;
  14688. /******/ };
  14689. /******/ // Object.prototype.hasOwnProperty.call
  14690. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  14691. /******/ // __webpack_public_path__
  14692. /******/ __webpack_require__.p = "/";
  14693. /******/ // on error function for async loading
  14694. /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; };
  14695. var f = __webpack_require__(__webpack_require__.s = ENTRY_MODULE)
  14696. return f.default || f // try to call default if defined to also support babel esmodule exports
  14697. }
  14698. var moduleNameReqExp = '[\\.|\\-|\\+|\\w|\/|@]+'
  14699. var dependencyRegExp = '\\((\/\\*.*?\\*\/)?\s?.*?(' + moduleNameReqExp + ').*?\\)' // additional chars when output.pathinfo is true
  14700. // http://stackoverflow.com/a/2593661/130442
  14701. function quoteRegExp (str) {
  14702. return (str + '').replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&')
  14703. }
  14704. function getModuleDependencies (sources, module, queueName) {
  14705. var retval = {}
  14706. retval[queueName] = []
  14707. var fnString = module.toString()
  14708. var wrapperSignature = fnString.match(/^function\s?\(\w+,\s*\w+,\s*(\w+)\)/)
  14709. if (!wrapperSignature) return retval
  14710. var webpackRequireName = wrapperSignature[1]
  14711. // main bundle deps
  14712. var re = new RegExp('(\\\\n|\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g')
  14713. var match
  14714. while ((match = re.exec(fnString))) {
  14715. if (match[3] === 'dll-reference') continue
  14716. retval[queueName].push(match[3])
  14717. }
  14718. // dll deps
  14719. re = new RegExp('\\(' + quoteRegExp(webpackRequireName) + '\\("(dll-reference\\s(' + moduleNameReqExp + '))"\\)\\)' + dependencyRegExp, 'g')
  14720. while ((match = re.exec(fnString))) {
  14721. if (!sources[match[2]]) {
  14722. retval[queueName].push(match[1])
  14723. sources[match[2]] = __webpack_require__(match[1]).m
  14724. }
  14725. retval[match[2]] = retval[match[2]] || []
  14726. retval[match[2]].push(match[4])
  14727. }
  14728. return retval
  14729. }
  14730. function hasValuesInQueues (queues) {
  14731. var keys = Object.keys(queues)
  14732. return keys.reduce(function (hasValues, key) {
  14733. return hasValues || queues[key].length > 0
  14734. }, false)
  14735. }
  14736. function getRequiredModules (sources, moduleId) {
  14737. var modulesQueue = {
  14738. main: [moduleId]
  14739. }
  14740. var requiredModules = {
  14741. main: []
  14742. }
  14743. var seenModules = {
  14744. main: {}
  14745. }
  14746. while (hasValuesInQueues(modulesQueue)) {
  14747. var queues = Object.keys(modulesQueue)
  14748. for (var i = 0; i < queues.length; i++) {
  14749. var queueName = queues[i]
  14750. var queue = modulesQueue[queueName]
  14751. var moduleToCheck = queue.pop()
  14752. seenModules[queueName] = seenModules[queueName] || {}
  14753. if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue
  14754. seenModules[queueName][moduleToCheck] = true
  14755. requiredModules[queueName] = requiredModules[queueName] || []
  14756. requiredModules[queueName].push(moduleToCheck)
  14757. var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName)
  14758. var newModulesKeys = Object.keys(newModules)
  14759. for (var j = 0; j < newModulesKeys.length; j++) {
  14760. modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || []
  14761. modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]])
  14762. }
  14763. }
  14764. }
  14765. return requiredModules
  14766. }
  14767. module.exports = function (moduleId, options) {
  14768. options = options || {}
  14769. var sources = {
  14770. main: __webpack_require__.m
  14771. }
  14772. var requiredModules = options.all ? { main: Object.keys(sources) } : getRequiredModules(sources, moduleId)
  14773. var src = ''
  14774. Object.keys(requiredModules).filter(function (m) { return m !== 'main' }).forEach(function (module) {
  14775. var entryModule = 0
  14776. while (requiredModules[module][entryModule]) {
  14777. entryModule++
  14778. }
  14779. requiredModules[module].push(entryModule)
  14780. sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })'
  14781. src = src + 'var ' + module + ' = (' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(entryModule)) + ')({' + requiredModules[module].map(function (id) { return '' + JSON.stringify(id) + ': ' + sources[module][id].toString() }).join(',') + '});\n'
  14782. })
  14783. src = src + '(' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.main.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources.main[id].toString() }).join(',') + '})(self);'
  14784. var blob = new window.Blob([src], { type: 'text/javascript' })
  14785. if (options.bare) { return blob }
  14786. var URL = window.URL || window.webkitURL || window.mozURL || window.msURL
  14787. var workerUrl = URL.createObjectURL(blob)
  14788. var worker = new window.Worker(workerUrl)
  14789. worker.objectURL = workerUrl
  14790. return worker
  14791. }
  14792. /***/ }),
  14793. /* 11 */
  14794. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  14795. "use strict";
  14796. Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
  14797. /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__demux_demuxer_inline__ = __webpack_require__(8);
  14798. /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__events__ = __webpack_require__(1);
  14799. /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__utils_logger__ = __webpack_require__(0);
  14800. /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_events__ = __webpack_require__(6);
  14801. /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_events___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_3_events__);
  14802. /* demuxer web worker.
  14803. * - listen to worker message, and trigger DemuxerInline upon reception of Fragments.
  14804. * - 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.
  14805. */
  14806. var DemuxerWorker = function DemuxerWorker(self) {
  14807. // observer setup
  14808. var observer = new __WEBPACK_IMPORTED_MODULE_3_events___default.a();
  14809. observer.trigger = function trigger(event) {
  14810. for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  14811. data[_key - 1] = arguments[_key];
  14812. }
  14813. observer.emit.apply(observer, [event, event].concat(data));
  14814. };
  14815. observer.off = function off(event) {
  14816. for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  14817. data[_key2 - 1] = arguments[_key2];
  14818. }
  14819. observer.removeListener.apply(observer, [event].concat(data));
  14820. };
  14821. var forwardMessage = function forwardMessage(ev, data) {
  14822. self.postMessage({ event: ev, data: data });
  14823. };
  14824. self.addEventListener('message', function (ev) {
  14825. var data = ev.data;
  14826. //console.log('demuxer cmd:' + data.cmd);
  14827. switch (data.cmd) {
  14828. case 'init':
  14829. var config = JSON.parse(data.config);
  14830. self.demuxer = new __WEBPACK_IMPORTED_MODULE_0__demux_demuxer_inline__["a" /* default */](observer, data.typeSupported, config, data.vendor);
  14831. try {
  14832. Object(__WEBPACK_IMPORTED_MODULE_2__utils_logger__["a" /* enableLogs */])(config.debug === true);
  14833. } catch (err) {
  14834. console.warn('demuxerWorker: unable to enable logs');
  14835. }
  14836. // signal end of worker init
  14837. forwardMessage('init', null);
  14838. break;
  14839. case 'demux':
  14840. 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);
  14841. break;
  14842. default:
  14843. break;
  14844. }
  14845. });
  14846. // forward events to main thread
  14847. observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].FRAG_DECRYPTED, forwardMessage);
  14848. observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].FRAG_PARSING_INIT_SEGMENT, forwardMessage);
  14849. observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].FRAG_PARSED, forwardMessage);
  14850. observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].ERROR, forwardMessage);
  14851. observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].FRAG_PARSING_METADATA, forwardMessage);
  14852. observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].FRAG_PARSING_USERDATA, forwardMessage);
  14853. observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].INIT_PTS_FOUND, forwardMessage);
  14854. // special case for FRAG_PARSING_DATA: pass data1/data2 as transferable object (no copy)
  14855. observer.on(__WEBPACK_IMPORTED_MODULE_1__events__["a" /* default */].FRAG_PARSING_DATA, function (ev, data) {
  14856. var transferable = [];
  14857. var message = { event: ev, data: data };
  14858. if (data.data1) {
  14859. message.data1 = data.data1.buffer;
  14860. transferable.push(data.data1.buffer);
  14861. delete data.data1;
  14862. }
  14863. if (data.data2) {
  14864. message.data2 = data.data2.buffer;
  14865. transferable.push(data.data2.buffer);
  14866. delete data.data2;
  14867. }
  14868. self.postMessage(message, transferable);
  14869. });
  14870. };
  14871. /* harmony default export */ __webpack_exports__["default"] = (DemuxerWorker);
  14872. /***/ }),
  14873. /* 12 */
  14874. /***/ (function(module, exports) {
  14875. /*! http://mths.be/endswith v0.2.0 by @mathias */
  14876. if (!String.prototype.endsWith) {
  14877. (function() {
  14878. 'use strict'; // needed to support `apply`/`call` with `undefined`/`null`
  14879. var defineProperty = (function() {
  14880. // IE 8 only supports `Object.defineProperty` on DOM elements
  14881. try {
  14882. var object = {};
  14883. var $defineProperty = Object.defineProperty;
  14884. var result = $defineProperty(object, object, object) && $defineProperty;
  14885. } catch(error) {}
  14886. return result;
  14887. }());
  14888. var toString = {}.toString;
  14889. var endsWith = function(search) {
  14890. if (this == null) {
  14891. throw TypeError();
  14892. }
  14893. var string = String(this);
  14894. if (search && toString.call(search) == '[object RegExp]') {
  14895. throw TypeError();
  14896. }
  14897. var stringLength = string.length;
  14898. var searchString = String(search);
  14899. var searchLength = searchString.length;
  14900. var pos = stringLength;
  14901. if (arguments.length > 1) {
  14902. var position = arguments[1];
  14903. if (position !== undefined) {
  14904. // `ToInteger`
  14905. pos = position ? Number(position) : 0;
  14906. if (pos != pos) { // better `isNaN`
  14907. pos = 0;
  14908. }
  14909. }
  14910. }
  14911. var end = Math.min(Math.max(pos, 0), stringLength);
  14912. var start = end - searchLength;
  14913. if (start < 0) {
  14914. return false;
  14915. }
  14916. var index = -1;
  14917. while (++index < searchLength) {
  14918. if (string.charCodeAt(start + index) != searchString.charCodeAt(index)) {
  14919. return false;
  14920. }
  14921. }
  14922. return true;
  14923. };
  14924. if (defineProperty) {
  14925. defineProperty(String.prototype, 'endsWith', {
  14926. 'value': endsWith,
  14927. 'configurable': true,
  14928. 'writable': true
  14929. });
  14930. } else {
  14931. String.prototype.endsWith = endsWith;
  14932. }
  14933. }());
  14934. }
  14935. /***/ })
  14936. /******/ ])["default"];
  14937. });
  14938. //# sourceMappingURL=hls.js.map