hls.js 696 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550
  1. typeof window !== "undefined" &&
  2. (function webpackUniversalModuleDefinition(root, factory) {
  3. if(typeof exports === 'object' && typeof module === 'object')
  4. module.exports = factory();
  5. else if(typeof define === 'function' && define.amd)
  6. define([], factory);
  7. else if(typeof exports === 'object')
  8. exports["Hls"] = factory();
  9. else
  10. root["Hls"] = factory();
  11. })(this, function() {
  12. return /******/ (function(modules) { // webpackBootstrap
  13. /******/ // The module cache
  14. /******/ var installedModules = {};
  15. /******/
  16. /******/ // The require function
  17. /******/ function __webpack_require__(moduleId) {
  18. /******/
  19. /******/ // Check if module is in cache
  20. /******/ if(installedModules[moduleId]) {
  21. /******/ return installedModules[moduleId].exports;
  22. /******/ }
  23. /******/ // Create a new module (and put it into the cache)
  24. /******/ var module = installedModules[moduleId] = {
  25. /******/ i: moduleId,
  26. /******/ l: false,
  27. /******/ exports: {}
  28. /******/ };
  29. /******/
  30. /******/ // Execute the module function
  31. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  32. /******/
  33. /******/ // Flag the module as loaded
  34. /******/ module.l = true;
  35. /******/
  36. /******/ // Return the exports of the module
  37. /******/ return module.exports;
  38. /******/ }
  39. /******/
  40. /******/
  41. /******/ // expose the modules object (__webpack_modules__)
  42. /******/ __webpack_require__.m = modules;
  43. /******/
  44. /******/ // expose the module cache
  45. /******/ __webpack_require__.c = installedModules;
  46. /******/
  47. /******/ // define getter function for harmony exports
  48. /******/ __webpack_require__.d = function(exports, name, getter) {
  49. /******/ if(!__webpack_require__.o(exports, name)) {
  50. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  51. /******/ }
  52. /******/ };
  53. /******/
  54. /******/ // define __esModule on exports
  55. /******/ __webpack_require__.r = function(exports) {
  56. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  57. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  58. /******/ }
  59. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  60. /******/ };
  61. /******/
  62. /******/ // create a fake namespace object
  63. /******/ // mode & 1: value is a module id, require it
  64. /******/ // mode & 2: merge all properties of value into the ns
  65. /******/ // mode & 4: return value when already ns object
  66. /******/ // mode & 8|1: behave like require
  67. /******/ __webpack_require__.t = function(value, mode) {
  68. /******/ if(mode & 1) value = __webpack_require__(value);
  69. /******/ if(mode & 8) return value;
  70. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  71. /******/ var ns = Object.create(null);
  72. /******/ __webpack_require__.r(ns);
  73. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  74. /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  75. /******/ return ns;
  76. /******/ };
  77. /******/
  78. /******/ // getDefaultExport function for compatibility with non-harmony modules
  79. /******/ __webpack_require__.n = function(module) {
  80. /******/ var getter = module && module.__esModule ?
  81. /******/ function getDefault() { return module['default']; } :
  82. /******/ function getModuleExports() { return module; };
  83. /******/ __webpack_require__.d(getter, 'a', getter);
  84. /******/ return getter;
  85. /******/ };
  86. /******/
  87. /******/ // Object.prototype.hasOwnProperty.call
  88. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  89. /******/
  90. /******/ // __webpack_public_path__
  91. /******/ __webpack_require__.p = "/dist/";
  92. /******/
  93. /******/
  94. /******/ // Load entry module and return exports
  95. /******/ return __webpack_require__(__webpack_require__.s = "./src/hls.ts");
  96. /******/ })
  97. /************************************************************************/
  98. /******/ ({
  99. /***/ "./node_modules/eventemitter3/index.js":
  100. /*!*********************************************!*\
  101. !*** ./node_modules/eventemitter3/index.js ***!
  102. \*********************************************/
  103. /*! no static exports found */
  104. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  105. /***/ (function(module, exports, __webpack_require__) {
  106. "use strict";
  107. var has = Object.prototype.hasOwnProperty
  108. , prefix = '~';
  109. /**
  110. * Constructor to create a storage for our `EE` objects.
  111. * An `Events` instance is a plain object whose properties are event names.
  112. *
  113. * @constructor
  114. * @private
  115. */
  116. function Events() {}
  117. //
  118. // We try to not inherit from `Object.prototype`. In some engines creating an
  119. // instance in this way is faster than calling `Object.create(null)` directly.
  120. // If `Object.create(null)` is not supported we prefix the event names with a
  121. // character to make sure that the built-in object properties are not
  122. // overridden or used as an attack vector.
  123. //
  124. if (Object.create) {
  125. Events.prototype = Object.create(null);
  126. //
  127. // This hack is needed because the `__proto__` property is still inherited in
  128. // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  129. //
  130. if (!new Events().__proto__) prefix = false;
  131. }
  132. /**
  133. * Representation of a single event listener.
  134. *
  135. * @param {Function} fn The listener function.
  136. * @param {*} context The context to invoke the listener with.
  137. * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
  138. * @constructor
  139. * @private
  140. */
  141. function EE(fn, context, once) {
  142. this.fn = fn;
  143. this.context = context;
  144. this.once = once || false;
  145. }
  146. /**
  147. * Add a listener for a given event.
  148. *
  149. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  150. * @param {(String|Symbol)} event The event name.
  151. * @param {Function} fn The listener function.
  152. * @param {*} context The context to invoke the listener with.
  153. * @param {Boolean} once Specify if the listener is a one-time listener.
  154. * @returns {EventEmitter}
  155. * @private
  156. */
  157. function addListener(emitter, event, fn, context, once) {
  158. if (typeof fn !== 'function') {
  159. throw new TypeError('The listener must be a function');
  160. }
  161. var listener = new EE(fn, context || emitter, once)
  162. , evt = prefix ? prefix + event : event;
  163. if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
  164. else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
  165. else emitter._events[evt] = [emitter._events[evt], listener];
  166. return emitter;
  167. }
  168. /**
  169. * Clear event by name.
  170. *
  171. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  172. * @param {(String|Symbol)} evt The Event name.
  173. * @private
  174. */
  175. function clearEvent(emitter, evt) {
  176. if (--emitter._eventsCount === 0) emitter._events = new Events();
  177. else delete emitter._events[evt];
  178. }
  179. /**
  180. * Minimal `EventEmitter` interface that is molded against the Node.js
  181. * `EventEmitter` interface.
  182. *
  183. * @constructor
  184. * @public
  185. */
  186. function EventEmitter() {
  187. this._events = new Events();
  188. this._eventsCount = 0;
  189. }
  190. /**
  191. * Return an array listing the events for which the emitter has registered
  192. * listeners.
  193. *
  194. * @returns {Array}
  195. * @public
  196. */
  197. EventEmitter.prototype.eventNames = function eventNames() {
  198. var names = []
  199. , events
  200. , name;
  201. if (this._eventsCount === 0) return names;
  202. for (name in (events = this._events)) {
  203. if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
  204. }
  205. if (Object.getOwnPropertySymbols) {
  206. return names.concat(Object.getOwnPropertySymbols(events));
  207. }
  208. return names;
  209. };
  210. /**
  211. * Return the listeners registered for a given event.
  212. *
  213. * @param {(String|Symbol)} event The event name.
  214. * @returns {Array} The registered listeners.
  215. * @public
  216. */
  217. EventEmitter.prototype.listeners = function listeners(event) {
  218. var evt = prefix ? prefix + event : event
  219. , handlers = this._events[evt];
  220. if (!handlers) return [];
  221. if (handlers.fn) return [handlers.fn];
  222. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  223. ee[i] = handlers[i].fn;
  224. }
  225. return ee;
  226. };
  227. /**
  228. * Return the number of listeners listening to a given event.
  229. *
  230. * @param {(String|Symbol)} event The event name.
  231. * @returns {Number} The number of listeners.
  232. * @public
  233. */
  234. EventEmitter.prototype.listenerCount = function listenerCount(event) {
  235. var evt = prefix ? prefix + event : event
  236. , listeners = this._events[evt];
  237. if (!listeners) return 0;
  238. if (listeners.fn) return 1;
  239. return listeners.length;
  240. };
  241. /**
  242. * Calls each of the listeners registered for a given event.
  243. *
  244. * @param {(String|Symbol)} event The event name.
  245. * @returns {Boolean} `true` if the event had listeners, else `false`.
  246. * @public
  247. */
  248. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  249. var evt = prefix ? prefix + event : event;
  250. if (!this._events[evt]) return false;
  251. var listeners = this._events[evt]
  252. , len = arguments.length
  253. , args
  254. , i;
  255. if (listeners.fn) {
  256. if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  257. switch (len) {
  258. case 1: return listeners.fn.call(listeners.context), true;
  259. case 2: return listeners.fn.call(listeners.context, a1), true;
  260. case 3: return listeners.fn.call(listeners.context, a1, a2), true;
  261. case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
  262. case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  263. case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  264. }
  265. for (i = 1, args = new Array(len -1); i < len; i++) {
  266. args[i - 1] = arguments[i];
  267. }
  268. listeners.fn.apply(listeners.context, args);
  269. } else {
  270. var length = listeners.length
  271. , j;
  272. for (i = 0; i < length; i++) {
  273. if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  274. switch (len) {
  275. case 1: listeners[i].fn.call(listeners[i].context); break;
  276. case 2: listeners[i].fn.call(listeners[i].context, a1); break;
  277. case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
  278. case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
  279. default:
  280. if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
  281. args[j - 1] = arguments[j];
  282. }
  283. listeners[i].fn.apply(listeners[i].context, args);
  284. }
  285. }
  286. }
  287. return true;
  288. };
  289. /**
  290. * Add a listener for a given event.
  291. *
  292. * @param {(String|Symbol)} event The event name.
  293. * @param {Function} fn The listener function.
  294. * @param {*} [context=this] The context to invoke the listener with.
  295. * @returns {EventEmitter} `this`.
  296. * @public
  297. */
  298. EventEmitter.prototype.on = function on(event, fn, context) {
  299. return addListener(this, event, fn, context, false);
  300. };
  301. /**
  302. * Add a one-time listener for a given event.
  303. *
  304. * @param {(String|Symbol)} event The event name.
  305. * @param {Function} fn The listener function.
  306. * @param {*} [context=this] The context to invoke the listener with.
  307. * @returns {EventEmitter} `this`.
  308. * @public
  309. */
  310. EventEmitter.prototype.once = function once(event, fn, context) {
  311. return addListener(this, event, fn, context, true);
  312. };
  313. /**
  314. * Remove the listeners of a given event.
  315. *
  316. * @param {(String|Symbol)} event The event name.
  317. * @param {Function} fn Only remove the listeners that match this function.
  318. * @param {*} context Only remove the listeners that have this context.
  319. * @param {Boolean} once Only remove one-time listeners.
  320. * @returns {EventEmitter} `this`.
  321. * @public
  322. */
  323. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  324. var evt = prefix ? prefix + event : event;
  325. if (!this._events[evt]) return this;
  326. if (!fn) {
  327. clearEvent(this, evt);
  328. return this;
  329. }
  330. var listeners = this._events[evt];
  331. if (listeners.fn) {
  332. if (
  333. listeners.fn === fn &&
  334. (!once || listeners.once) &&
  335. (!context || listeners.context === context)
  336. ) {
  337. clearEvent(this, evt);
  338. }
  339. } else {
  340. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  341. if (
  342. listeners[i].fn !== fn ||
  343. (once && !listeners[i].once) ||
  344. (context && listeners[i].context !== context)
  345. ) {
  346. events.push(listeners[i]);
  347. }
  348. }
  349. //
  350. // Reset the array, or remove it completely if we have no more listeners.
  351. //
  352. if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
  353. else clearEvent(this, evt);
  354. }
  355. return this;
  356. };
  357. /**
  358. * Remove all listeners, or those of the specified event.
  359. *
  360. * @param {(String|Symbol)} [event] The event name.
  361. * @returns {EventEmitter} `this`.
  362. * @public
  363. */
  364. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  365. var evt;
  366. if (event) {
  367. evt = prefix ? prefix + event : event;
  368. if (this._events[evt]) clearEvent(this, evt);
  369. } else {
  370. this._events = new Events();
  371. this._eventsCount = 0;
  372. }
  373. return this;
  374. };
  375. //
  376. // Alias methods names because people roll like that.
  377. //
  378. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  379. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  380. //
  381. // Expose the prefix.
  382. //
  383. EventEmitter.prefixed = prefix;
  384. //
  385. // Allow `EventEmitter` to be imported as module namespace.
  386. //
  387. EventEmitter.EventEmitter = EventEmitter;
  388. //
  389. // Expose the module.
  390. //
  391. if (true) {
  392. module.exports = EventEmitter;
  393. }
  394. /***/ }),
  395. /***/ "./node_modules/url-toolkit/src/url-toolkit.js":
  396. /*!*****************************************************!*\
  397. !*** ./node_modules/url-toolkit/src/url-toolkit.js ***!
  398. \*****************************************************/
  399. /*! no static exports found */
  400. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  401. /***/ (function(module, exports, __webpack_require__) {
  402. // see https://tools.ietf.org/html/rfc1808
  403. (function (root) {
  404. var URL_REGEX = /^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/?#]*\/)*[^;?#]*)?(;[^?#]*)?(\?[^#]*)?(#.*)?$/;
  405. var FIRST_SEGMENT_REGEX = /^([^\/?#]*)(.*)$/;
  406. var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
  407. var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
  408. var URLToolkit = {
  409. // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
  410. // E.g
  411. // With opts.alwaysNormalize = false (default, spec compliant)
  412. // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
  413. // With opts.alwaysNormalize = true (not spec compliant)
  414. // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
  415. buildAbsoluteURL: function (baseURL, relativeURL, opts) {
  416. opts = opts || {};
  417. // remove any remaining space and CRLF
  418. baseURL = baseURL.trim();
  419. relativeURL = relativeURL.trim();
  420. if (!relativeURL) {
  421. // 2a) If the embedded URL is entirely empty, it inherits the
  422. // entire base URL (i.e., is set equal to the base URL)
  423. // and we are done.
  424. if (!opts.alwaysNormalize) {
  425. return baseURL;
  426. }
  427. var basePartsForNormalise = URLToolkit.parseURL(baseURL);
  428. if (!basePartsForNormalise) {
  429. throw new Error('Error trying to parse base URL.');
  430. }
  431. basePartsForNormalise.path = URLToolkit.normalizePath(
  432. basePartsForNormalise.path
  433. );
  434. return URLToolkit.buildURLFromParts(basePartsForNormalise);
  435. }
  436. var relativeParts = URLToolkit.parseURL(relativeURL);
  437. if (!relativeParts) {
  438. throw new Error('Error trying to parse relative URL.');
  439. }
  440. if (relativeParts.scheme) {
  441. // 2b) If the embedded URL starts with a scheme name, it is
  442. // interpreted as an absolute URL and we are done.
  443. if (!opts.alwaysNormalize) {
  444. return relativeURL;
  445. }
  446. relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
  447. return URLToolkit.buildURLFromParts(relativeParts);
  448. }
  449. var baseParts = URLToolkit.parseURL(baseURL);
  450. if (!baseParts) {
  451. throw new Error('Error trying to parse base URL.');
  452. }
  453. if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
  454. // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
  455. // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
  456. var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
  457. baseParts.netLoc = pathParts[1];
  458. baseParts.path = pathParts[2];
  459. }
  460. if (baseParts.netLoc && !baseParts.path) {
  461. baseParts.path = '/';
  462. }
  463. var builtParts = {
  464. // 2c) Otherwise, the embedded URL inherits the scheme of
  465. // the base URL.
  466. scheme: baseParts.scheme,
  467. netLoc: relativeParts.netLoc,
  468. path: null,
  469. params: relativeParts.params,
  470. query: relativeParts.query,
  471. fragment: relativeParts.fragment,
  472. };
  473. if (!relativeParts.netLoc) {
  474. // 3) If the embedded URL's <net_loc> is non-empty, we skip to
  475. // Step 7. Otherwise, the embedded URL inherits the <net_loc>
  476. // (if any) of the base URL.
  477. builtParts.netLoc = baseParts.netLoc;
  478. // 4) If the embedded URL path is preceded by a slash "/", the
  479. // path is not relative and we skip to Step 7.
  480. if (relativeParts.path[0] !== '/') {
  481. if (!relativeParts.path) {
  482. // 5) If the embedded URL path is empty (and not preceded by a
  483. // slash), then the embedded URL inherits the base URL path
  484. builtParts.path = baseParts.path;
  485. // 5a) if the embedded URL's <params> is non-empty, we skip to
  486. // step 7; otherwise, it inherits the <params> of the base
  487. // URL (if any) and
  488. if (!relativeParts.params) {
  489. builtParts.params = baseParts.params;
  490. // 5b) if the embedded URL's <query> is non-empty, we skip to
  491. // step 7; otherwise, it inherits the <query> of the base
  492. // URL (if any) and we skip to step 7.
  493. if (!relativeParts.query) {
  494. builtParts.query = baseParts.query;
  495. }
  496. }
  497. } else {
  498. // 6) The last segment of the base URL's path (anything
  499. // following the rightmost slash "/", or the entire path if no
  500. // slash is present) is removed and the embedded URL's path is
  501. // appended in its place.
  502. var baseURLPath = baseParts.path;
  503. var newPath =
  504. baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) +
  505. relativeParts.path;
  506. builtParts.path = URLToolkit.normalizePath(newPath);
  507. }
  508. }
  509. }
  510. if (builtParts.path === null) {
  511. builtParts.path = opts.alwaysNormalize
  512. ? URLToolkit.normalizePath(relativeParts.path)
  513. : relativeParts.path;
  514. }
  515. return URLToolkit.buildURLFromParts(builtParts);
  516. },
  517. parseURL: function (url) {
  518. var parts = URL_REGEX.exec(url);
  519. if (!parts) {
  520. return null;
  521. }
  522. return {
  523. scheme: parts[1] || '',
  524. netLoc: parts[2] || '',
  525. path: parts[3] || '',
  526. params: parts[4] || '',
  527. query: parts[5] || '',
  528. fragment: parts[6] || '',
  529. };
  530. },
  531. normalizePath: function (path) {
  532. // The following operations are
  533. // then applied, in order, to the new path:
  534. // 6a) All occurrences of "./", where "." is a complete path
  535. // segment, are removed.
  536. // 6b) If the path ends with "." as a complete path segment,
  537. // that "." is removed.
  538. path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');
  539. // 6c) All occurrences of "<segment>/../", where <segment> is a
  540. // complete path segment not equal to "..", are removed.
  541. // Removal of these path segments is performed iteratively,
  542. // removing the leftmost matching pattern on each iteration,
  543. // until no matching pattern remains.
  544. // 6d) If the path ends with "<segment>/..", where <segment> is a
  545. // complete path segment not equal to "..", that
  546. // "<segment>/.." is removed.
  547. while (
  548. path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length
  549. ) {}
  550. return path.split('').reverse().join('');
  551. },
  552. buildURLFromParts: function (parts) {
  553. return (
  554. parts.scheme +
  555. parts.netLoc +
  556. parts.path +
  557. parts.params +
  558. parts.query +
  559. parts.fragment
  560. );
  561. },
  562. };
  563. if (true)
  564. module.exports = URLToolkit;
  565. else {}
  566. })(this);
  567. /***/ }),
  568. /***/ "./node_modules/webworkify-webpack/index.js":
  569. /*!**************************************************!*\
  570. !*** ./node_modules/webworkify-webpack/index.js ***!
  571. \**************************************************/
  572. /*! no static exports found */
  573. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  574. /***/ (function(module, exports, __webpack_require__) {
  575. function webpackBootstrapFunc (modules) {
  576. /******/ // The module cache
  577. /******/ var installedModules = {};
  578. /******/ // The require function
  579. /******/ function __webpack_require__(moduleId) {
  580. /******/ // Check if module is in cache
  581. /******/ if(installedModules[moduleId])
  582. /******/ return installedModules[moduleId].exports;
  583. /******/ // Create a new module (and put it into the cache)
  584. /******/ var module = installedModules[moduleId] = {
  585. /******/ i: moduleId,
  586. /******/ l: false,
  587. /******/ exports: {}
  588. /******/ };
  589. /******/ // Execute the module function
  590. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  591. /******/ // Flag the module as loaded
  592. /******/ module.l = true;
  593. /******/ // Return the exports of the module
  594. /******/ return module.exports;
  595. /******/ }
  596. /******/ // expose the modules object (__webpack_modules__)
  597. /******/ __webpack_require__.m = modules;
  598. /******/ // expose the module cache
  599. /******/ __webpack_require__.c = installedModules;
  600. /******/ // identity function for calling harmony imports with the correct context
  601. /******/ __webpack_require__.i = function(value) { return value; };
  602. /******/ // define getter function for harmony exports
  603. /******/ __webpack_require__.d = function(exports, name, getter) {
  604. /******/ if(!__webpack_require__.o(exports, name)) {
  605. /******/ Object.defineProperty(exports, name, {
  606. /******/ configurable: false,
  607. /******/ enumerable: true,
  608. /******/ get: getter
  609. /******/ });
  610. /******/ }
  611. /******/ };
  612. /******/ // define __esModule on exports
  613. /******/ __webpack_require__.r = function(exports) {
  614. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  615. /******/ };
  616. /******/ // getDefaultExport function for compatibility with non-harmony modules
  617. /******/ __webpack_require__.n = function(module) {
  618. /******/ var getter = module && module.__esModule ?
  619. /******/ function getDefault() { return module['default']; } :
  620. /******/ function getModuleExports() { return module; };
  621. /******/ __webpack_require__.d(getter, 'a', getter);
  622. /******/ return getter;
  623. /******/ };
  624. /******/ // Object.prototype.hasOwnProperty.call
  625. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  626. /******/ // __webpack_public_path__
  627. /******/ __webpack_require__.p = "/";
  628. /******/ // on error function for async loading
  629. /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; };
  630. var f = __webpack_require__(__webpack_require__.s = ENTRY_MODULE)
  631. return f.default || f // try to call default if defined to also support babel esmodule exports
  632. }
  633. var moduleNameReqExp = '[\\.|\\-|\\+|\\w|\/|@]+'
  634. var dependencyRegExp = '\\(\\s*(\/\\*.*?\\*\/)?\\s*.*?(' + moduleNameReqExp + ').*?\\)' // additional chars when output.pathinfo is true
  635. // http://stackoverflow.com/a/2593661/130442
  636. function quoteRegExp (str) {
  637. return (str + '').replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&')
  638. }
  639. function isNumeric(n) {
  640. return !isNaN(1 * n); // 1 * n converts integers, integers as string ("123"), 1e3 and "1e3" to integers and strings to NaN
  641. }
  642. function getModuleDependencies (sources, module, queueName) {
  643. var retval = {}
  644. retval[queueName] = []
  645. var fnString = module.toString()
  646. var wrapperSignature = fnString.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/)
  647. if (!wrapperSignature) return retval
  648. var webpackRequireName = wrapperSignature[1]
  649. // main bundle deps
  650. var re = new RegExp('(\\\\n|\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g')
  651. var match
  652. while ((match = re.exec(fnString))) {
  653. if (match[3] === 'dll-reference') continue
  654. retval[queueName].push(match[3])
  655. }
  656. // dll deps
  657. re = new RegExp('\\(' + quoteRegExp(webpackRequireName) + '\\("(dll-reference\\s(' + moduleNameReqExp + '))"\\)\\)' + dependencyRegExp, 'g')
  658. while ((match = re.exec(fnString))) {
  659. if (!sources[match[2]]) {
  660. retval[queueName].push(match[1])
  661. sources[match[2]] = __webpack_require__(match[1]).m
  662. }
  663. retval[match[2]] = retval[match[2]] || []
  664. retval[match[2]].push(match[4])
  665. }
  666. // convert 1e3 back to 1000 - this can be important after uglify-js converted 1000 to 1e3
  667. var keys = Object.keys(retval);
  668. for (var i = 0; i < keys.length; i++) {
  669. for (var j = 0; j < retval[keys[i]].length; j++) {
  670. if (isNumeric(retval[keys[i]][j])) {
  671. retval[keys[i]][j] = 1 * retval[keys[i]][j];
  672. }
  673. }
  674. }
  675. return retval
  676. }
  677. function hasValuesInQueues (queues) {
  678. var keys = Object.keys(queues)
  679. return keys.reduce(function (hasValues, key) {
  680. return hasValues || queues[key].length > 0
  681. }, false)
  682. }
  683. function getRequiredModules (sources, moduleId) {
  684. var modulesQueue = {
  685. main: [moduleId]
  686. }
  687. var requiredModules = {
  688. main: []
  689. }
  690. var seenModules = {
  691. main: {}
  692. }
  693. while (hasValuesInQueues(modulesQueue)) {
  694. var queues = Object.keys(modulesQueue)
  695. for (var i = 0; i < queues.length; i++) {
  696. var queueName = queues[i]
  697. var queue = modulesQueue[queueName]
  698. var moduleToCheck = queue.pop()
  699. seenModules[queueName] = seenModules[queueName] || {}
  700. if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue
  701. seenModules[queueName][moduleToCheck] = true
  702. requiredModules[queueName] = requiredModules[queueName] || []
  703. requiredModules[queueName].push(moduleToCheck)
  704. var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName)
  705. var newModulesKeys = Object.keys(newModules)
  706. for (var j = 0; j < newModulesKeys.length; j++) {
  707. modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || []
  708. modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]])
  709. }
  710. }
  711. }
  712. return requiredModules
  713. }
  714. module.exports = function (moduleId, options) {
  715. options = options || {}
  716. var sources = {
  717. main: __webpack_require__.m
  718. }
  719. var requiredModules = options.all ? { main: Object.keys(sources.main) } : getRequiredModules(sources, moduleId)
  720. var src = ''
  721. Object.keys(requiredModules).filter(function (m) { return m !== 'main' }).forEach(function (module) {
  722. var entryModule = 0
  723. while (requiredModules[module][entryModule]) {
  724. entryModule++
  725. }
  726. requiredModules[module].push(entryModule)
  727. sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })'
  728. 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'
  729. })
  730. src = src + 'new ((' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.main.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources.main[id].toString() }).join(',') + '}))(self);'
  731. var blob = new window.Blob([src], { type: 'text/javascript' })
  732. if (options.bare) { return blob }
  733. var URL = window.URL || window.webkitURL || window.mozURL || window.msURL
  734. var workerUrl = URL.createObjectURL(blob)
  735. var worker = new window.Worker(workerUrl)
  736. worker.objectURL = workerUrl
  737. return worker
  738. }
  739. /***/ }),
  740. /***/ "./src/crypt/decrypter.js":
  741. /*!********************************************!*\
  742. !*** ./src/crypt/decrypter.js + 3 modules ***!
  743. \********************************************/
  744. /*! exports provided: default */
  745. /*! ModuleConcatenation bailout: Cannot concat with ./src/errors.ts because of ./src/hls.ts */
  746. /*! ModuleConcatenation bailout: Cannot concat with ./src/events.js because of ./src/hls.ts */
  747. /*! ModuleConcatenation bailout: Cannot concat with ./src/utils/get-self-scope.js because of ./src/hls.ts */
  748. /*! ModuleConcatenation bailout: Cannot concat with ./src/utils/logger.js because of ./src/hls.ts */
  749. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  750. "use strict";
  751. // ESM COMPAT FLAG
  752. __webpack_require__.r(__webpack_exports__);
  753. // CONCATENATED MODULE: ./src/crypt/aes-crypto.js
  754. var AESCrypto = /*#__PURE__*/function () {
  755. function AESCrypto(subtle, iv) {
  756. this.subtle = subtle;
  757. this.aesIV = iv;
  758. }
  759. var _proto = AESCrypto.prototype;
  760. _proto.decrypt = function decrypt(data, key) {
  761. return this.subtle.decrypt({
  762. name: 'AES-CBC',
  763. iv: this.aesIV
  764. }, key, data);
  765. };
  766. return AESCrypto;
  767. }();
  768. // CONCATENATED MODULE: ./src/crypt/fast-aes-key.js
  769. var FastAESKey = /*#__PURE__*/function () {
  770. function FastAESKey(subtle, key) {
  771. this.subtle = subtle;
  772. this.key = key;
  773. }
  774. var _proto = FastAESKey.prototype;
  775. _proto.expandKey = function expandKey() {
  776. return this.subtle.importKey('raw', this.key, {
  777. name: 'AES-CBC'
  778. }, false, ['encrypt', 'decrypt']);
  779. };
  780. return FastAESKey;
  781. }();
  782. /* harmony default export */ var fast_aes_key = (FastAESKey);
  783. // CONCATENATED MODULE: ./src/crypt/aes-decryptor.js
  784. // PKCS7
  785. function removePadding(buffer) {
  786. var outputBytes = buffer.byteLength;
  787. var paddingBytes = outputBytes && new DataView(buffer).getUint8(outputBytes - 1);
  788. if (paddingBytes) {
  789. return buffer.slice(0, outputBytes - paddingBytes);
  790. } else {
  791. return buffer;
  792. }
  793. }
  794. var AESDecryptor = /*#__PURE__*/function () {
  795. function AESDecryptor() {
  796. // Static after running initTable
  797. this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
  798. this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  799. this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  800. this.sBox = new Uint32Array(256);
  801. this.invSBox = new Uint32Array(256); // Changes during runtime
  802. this.key = new Uint32Array(0);
  803. this.initTable();
  804. } // Using view.getUint32() also swaps the byte order.
  805. var _proto = AESDecryptor.prototype;
  806. _proto.uint8ArrayToUint32Array_ = function uint8ArrayToUint32Array_(arrayBuffer) {
  807. var view = new DataView(arrayBuffer);
  808. var newArray = new Uint32Array(4);
  809. for (var i = 0; i < 4; i++) {
  810. newArray[i] = view.getUint32(i * 4);
  811. }
  812. return newArray;
  813. };
  814. _proto.initTable = function initTable() {
  815. var sBox = this.sBox;
  816. var invSBox = this.invSBox;
  817. var subMix = this.subMix;
  818. var subMix0 = subMix[0];
  819. var subMix1 = subMix[1];
  820. var subMix2 = subMix[2];
  821. var subMix3 = subMix[3];
  822. var invSubMix = this.invSubMix;
  823. var invSubMix0 = invSubMix[0];
  824. var invSubMix1 = invSubMix[1];
  825. var invSubMix2 = invSubMix[2];
  826. var invSubMix3 = invSubMix[3];
  827. var d = new Uint32Array(256);
  828. var x = 0;
  829. var xi = 0;
  830. var i = 0;
  831. for (i = 0; i < 256; i++) {
  832. if (i < 128) {
  833. d[i] = i << 1;
  834. } else {
  835. d[i] = i << 1 ^ 0x11b;
  836. }
  837. }
  838. for (i = 0; i < 256; i++) {
  839. var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
  840. sx = sx >>> 8 ^ sx & 0xff ^ 0x63;
  841. sBox[x] = sx;
  842. invSBox[sx] = x; // Compute multiplication
  843. var x2 = d[x];
  844. var x4 = d[x2];
  845. var x8 = d[x4]; // Compute sub/invSub bytes, mix columns tables
  846. var t = d[sx] * 0x101 ^ sx * 0x1010100;
  847. subMix0[x] = t << 24 | t >>> 8;
  848. subMix1[x] = t << 16 | t >>> 16;
  849. subMix2[x] = t << 8 | t >>> 24;
  850. subMix3[x] = t; // Compute inv sub bytes, inv mix columns tables
  851. t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  852. invSubMix0[sx] = t << 24 | t >>> 8;
  853. invSubMix1[sx] = t << 16 | t >>> 16;
  854. invSubMix2[sx] = t << 8 | t >>> 24;
  855. invSubMix3[sx] = t; // Compute next counter
  856. if (!x) {
  857. x = xi = 1;
  858. } else {
  859. x = x2 ^ d[d[d[x8 ^ x2]]];
  860. xi ^= d[d[xi]];
  861. }
  862. }
  863. };
  864. _proto.expandKey = function expandKey(keyBuffer) {
  865. // convert keyBuffer to Uint32Array
  866. var key = this.uint8ArrayToUint32Array_(keyBuffer);
  867. var sameKey = true;
  868. var offset = 0;
  869. while (offset < key.length && sameKey) {
  870. sameKey = key[offset] === this.key[offset];
  871. offset++;
  872. }
  873. if (sameKey) {
  874. return;
  875. }
  876. this.key = key;
  877. var keySize = this.keySize = key.length;
  878. if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
  879. throw new Error('Invalid aes key size=' + keySize);
  880. }
  881. var ksRows = this.ksRows = (keySize + 6 + 1) * 4;
  882. var ksRow;
  883. var invKsRow;
  884. var keySchedule = this.keySchedule = new Uint32Array(ksRows);
  885. var invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
  886. var sbox = this.sBox;
  887. var rcon = this.rcon;
  888. var invSubMix = this.invSubMix;
  889. var invSubMix0 = invSubMix[0];
  890. var invSubMix1 = invSubMix[1];
  891. var invSubMix2 = invSubMix[2];
  892. var invSubMix3 = invSubMix[3];
  893. var prev;
  894. var t;
  895. for (ksRow = 0; ksRow < ksRows; ksRow++) {
  896. if (ksRow < keySize) {
  897. prev = keySchedule[ksRow] = key[ksRow];
  898. continue;
  899. }
  900. t = prev;
  901. if (ksRow % keySize === 0) {
  902. // Rot word
  903. t = t << 8 | t >>> 24; // Sub word
  904. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff]; // Mix Rcon
  905. t ^= rcon[ksRow / keySize | 0] << 24;
  906. } else if (keySize > 6 && ksRow % keySize === 4) {
  907. // Sub word
  908. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  909. }
  910. keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
  911. }
  912. for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
  913. ksRow = ksRows - invKsRow;
  914. if (invKsRow & 3) {
  915. t = keySchedule[ksRow];
  916. } else {
  917. t = keySchedule[ksRow - 4];
  918. }
  919. if (invKsRow < 4 || ksRow <= 4) {
  920. invKeySchedule[invKsRow] = t;
  921. } else {
  922. invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]];
  923. }
  924. invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
  925. }
  926. } // Adding this as a method greatly improves performance.
  927. ;
  928. _proto.networkToHostOrderSwap = function networkToHostOrderSwap(word) {
  929. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  930. };
  931. _proto.decrypt = function decrypt(inputArrayBuffer, offset, aesIV, removePKCS7Padding) {
  932. var nRounds = this.keySize + 6;
  933. var invKeySchedule = this.invKeySchedule;
  934. var invSBOX = this.invSBox;
  935. var invSubMix = this.invSubMix;
  936. var invSubMix0 = invSubMix[0];
  937. var invSubMix1 = invSubMix[1];
  938. var invSubMix2 = invSubMix[2];
  939. var invSubMix3 = invSubMix[3];
  940. var initVector = this.uint8ArrayToUint32Array_(aesIV);
  941. var initVector0 = initVector[0];
  942. var initVector1 = initVector[1];
  943. var initVector2 = initVector[2];
  944. var initVector3 = initVector[3];
  945. var inputInt32 = new Int32Array(inputArrayBuffer);
  946. var outputInt32 = new Int32Array(inputInt32.length);
  947. var t0, t1, t2, t3;
  948. var s0, s1, s2, s3;
  949. var inputWords0, inputWords1, inputWords2, inputWords3;
  950. var ksRow, i;
  951. var swapWord = this.networkToHostOrderSwap;
  952. while (offset < inputInt32.length) {
  953. inputWords0 = swapWord(inputInt32[offset]);
  954. inputWords1 = swapWord(inputInt32[offset + 1]);
  955. inputWords2 = swapWord(inputInt32[offset + 2]);
  956. inputWords3 = swapWord(inputInt32[offset + 3]);
  957. s0 = inputWords0 ^ invKeySchedule[0];
  958. s1 = inputWords3 ^ invKeySchedule[1];
  959. s2 = inputWords2 ^ invKeySchedule[2];
  960. s3 = inputWords1 ^ invKeySchedule[3];
  961. ksRow = 4; // Iterate through the rounds of decryption
  962. for (i = 1; i < nRounds; i++) {
  963. t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];
  964. t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  965. t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  966. t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3]; // Update state
  967. s0 = t0;
  968. s1 = t1;
  969. s2 = t2;
  970. s3 = t3;
  971. ksRow = ksRow + 4;
  972. } // Shift rows, sub bytes, add round key
  973. t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow];
  974. t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  975. t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  976. t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  977. ksRow = ksRow + 3; // Write
  978. outputInt32[offset] = swapWord(t0 ^ initVector0);
  979. outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
  980. outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
  981. outputInt32[offset + 3] = swapWord(t1 ^ initVector3); // reset initVector to last 4 unsigned int
  982. initVector0 = inputWords0;
  983. initVector1 = inputWords1;
  984. initVector2 = inputWords2;
  985. initVector3 = inputWords3;
  986. offset = offset + 4;
  987. }
  988. return removePKCS7Padding ? removePadding(outputInt32.buffer) : outputInt32.buffer;
  989. };
  990. _proto.destroy = function destroy() {
  991. this.key = undefined;
  992. this.keySize = undefined;
  993. this.ksRows = undefined;
  994. this.sBox = undefined;
  995. this.invSBox = undefined;
  996. this.subMix = undefined;
  997. this.invSubMix = undefined;
  998. this.keySchedule = undefined;
  999. this.invKeySchedule = undefined;
  1000. this.rcon = undefined;
  1001. };
  1002. return AESDecryptor;
  1003. }();
  1004. /* harmony default export */ var aes_decryptor = (AESDecryptor);
  1005. // EXTERNAL MODULE: ./src/errors.ts
  1006. var errors = __webpack_require__("./src/errors.ts");
  1007. // EXTERNAL MODULE: ./src/utils/logger.js
  1008. var logger = __webpack_require__("./src/utils/logger.js");
  1009. // EXTERNAL MODULE: ./src/events.js
  1010. var events = __webpack_require__("./src/events.js");
  1011. // EXTERNAL MODULE: ./src/utils/get-self-scope.js
  1012. var get_self_scope = __webpack_require__("./src/utils/get-self-scope.js");
  1013. // CONCATENATED MODULE: ./src/crypt/decrypter.js
  1014. // see https://stackoverflow.com/a/11237259/589493
  1015. var global = Object(get_self_scope["getSelfScope"])(); // safeguard for code that might run both on worker and main thread
  1016. var decrypter_Decrypter = /*#__PURE__*/function () {
  1017. function Decrypter(observer, config, _temp) {
  1018. var _ref = _temp === void 0 ? {} : _temp,
  1019. _ref$removePKCS7Paddi = _ref.removePKCS7Padding,
  1020. removePKCS7Padding = _ref$removePKCS7Paddi === void 0 ? true : _ref$removePKCS7Paddi;
  1021. this.logEnabled = true;
  1022. this.observer = observer;
  1023. this.config = config;
  1024. this.removePKCS7Padding = removePKCS7Padding; // built in decryptor expects PKCS7 padding
  1025. if (removePKCS7Padding) {
  1026. try {
  1027. var browserCrypto = global.crypto;
  1028. if (browserCrypto) {
  1029. this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
  1030. }
  1031. } catch (e) {}
  1032. }
  1033. this.disableWebCrypto = !this.subtle;
  1034. }
  1035. var _proto = Decrypter.prototype;
  1036. _proto.isSync = function isSync() {
  1037. return this.disableWebCrypto && this.config.enableSoftwareAES;
  1038. };
  1039. _proto.decrypt = function decrypt(data, key, iv, callback) {
  1040. var _this = this;
  1041. if (this.disableWebCrypto && this.config.enableSoftwareAES) {
  1042. if (this.logEnabled) {
  1043. logger["logger"].log('JS AES decrypt');
  1044. this.logEnabled = false;
  1045. }
  1046. var decryptor = this.decryptor;
  1047. if (!decryptor) {
  1048. this.decryptor = decryptor = new aes_decryptor();
  1049. }
  1050. decryptor.expandKey(key);
  1051. callback(decryptor.decrypt(data, 0, iv, this.removePKCS7Padding));
  1052. } else {
  1053. if (this.logEnabled) {
  1054. logger["logger"].log('WebCrypto AES decrypt');
  1055. this.logEnabled = false;
  1056. }
  1057. var subtle = this.subtle;
  1058. if (this.key !== key) {
  1059. this.key = key;
  1060. this.fastAesKey = new fast_aes_key(subtle, key);
  1061. }
  1062. this.fastAesKey.expandKey().then(function (aesKey) {
  1063. // decrypt using web crypto
  1064. var crypto = new AESCrypto(subtle, iv);
  1065. crypto.decrypt(data, aesKey).catch(function (err) {
  1066. _this.onWebCryptoError(err, data, key, iv, callback);
  1067. }).then(function (result) {
  1068. callback(result);
  1069. });
  1070. }).catch(function (err) {
  1071. _this.onWebCryptoError(err, data, key, iv, callback);
  1072. });
  1073. }
  1074. };
  1075. _proto.onWebCryptoError = function onWebCryptoError(err, data, key, iv, callback) {
  1076. if (this.config.enableSoftwareAES) {
  1077. logger["logger"].log('WebCrypto Error, disable WebCrypto API');
  1078. this.disableWebCrypto = true;
  1079. this.logEnabled = true;
  1080. this.decrypt(data, key, iv, callback);
  1081. } else {
  1082. logger["logger"].error("decrypting error : " + err.message);
  1083. this.observer.trigger(events["default"].ERROR, {
  1084. type: errors["ErrorTypes"].MEDIA_ERROR,
  1085. details: errors["ErrorDetails"].FRAG_DECRYPT_ERROR,
  1086. fatal: true,
  1087. reason: err.message
  1088. });
  1089. }
  1090. };
  1091. _proto.destroy = function destroy() {
  1092. var decryptor = this.decryptor;
  1093. if (decryptor) {
  1094. decryptor.destroy();
  1095. this.decryptor = undefined;
  1096. }
  1097. };
  1098. return Decrypter;
  1099. }();
  1100. /* harmony default export */ var decrypter = __webpack_exports__["default"] = (decrypter_Decrypter);
  1101. /***/ }),
  1102. /***/ "./src/demux/demuxer-inline.js":
  1103. /*!**************************************************!*\
  1104. !*** ./src/demux/demuxer-inline.js + 12 modules ***!
  1105. \**************************************************/
  1106. /*! exports provided: default */
  1107. /*! ModuleConcatenation bailout: Cannot concat with ./src/crypt/decrypter.js because of ./src/hls.ts */
  1108. /*! ModuleConcatenation bailout: Cannot concat with ./src/demux/id3.js because of ./src/hls.ts */
  1109. /*! ModuleConcatenation bailout: Cannot concat with ./src/demux/mp4demuxer.js because of ./src/hls.ts */
  1110. /*! ModuleConcatenation bailout: Cannot concat with ./src/errors.ts because of ./src/hls.ts */
  1111. /*! ModuleConcatenation bailout: Cannot concat with ./src/events.js because of ./src/hls.ts */
  1112. /*! ModuleConcatenation bailout: Cannot concat with ./src/polyfills/number.js because of ./src/hls.ts */
  1113. /*! ModuleConcatenation bailout: Cannot concat with ./src/utils/get-self-scope.js because of ./src/hls.ts */
  1114. /*! ModuleConcatenation bailout: Cannot concat with ./src/utils/logger.js because of ./src/hls.ts */
  1115. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  1116. "use strict";
  1117. // ESM COMPAT FLAG
  1118. __webpack_require__.r(__webpack_exports__);
  1119. // EXTERNAL MODULE: ./src/events.js
  1120. var events = __webpack_require__("./src/events.js");
  1121. // EXTERNAL MODULE: ./src/errors.ts
  1122. var errors = __webpack_require__("./src/errors.ts");
  1123. // EXTERNAL MODULE: ./src/crypt/decrypter.js + 3 modules
  1124. var crypt_decrypter = __webpack_require__("./src/crypt/decrypter.js");
  1125. // EXTERNAL MODULE: ./src/polyfills/number.js
  1126. var number = __webpack_require__("./src/polyfills/number.js");
  1127. // EXTERNAL MODULE: ./src/utils/logger.js
  1128. var logger = __webpack_require__("./src/utils/logger.js");
  1129. // EXTERNAL MODULE: ./src/utils/get-self-scope.js
  1130. var get_self_scope = __webpack_require__("./src/utils/get-self-scope.js");
  1131. // CONCATENATED MODULE: ./src/demux/adts.js
  1132. /**
  1133. * ADTS parser helper
  1134. * @link https://wiki.multimedia.cx/index.php?title=ADTS
  1135. */
  1136. function getAudioConfig(observer, data, offset, audioCodec) {
  1137. var adtsObjectType,
  1138. // :int
  1139. adtsSampleingIndex,
  1140. // :int
  1141. adtsExtensionSampleingIndex,
  1142. // :int
  1143. adtsChanelConfig,
  1144. // :int
  1145. config,
  1146. userAgent = navigator.userAgent.toLowerCase(),
  1147. manifestCodec = audioCodec,
  1148. adtsSampleingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; // byte 2
  1149. adtsObjectType = ((data[offset + 2] & 0xC0) >>> 6) + 1;
  1150. adtsSampleingIndex = (data[offset + 2] & 0x3C) >>> 2;
  1151. if (adtsSampleingIndex > adtsSampleingRates.length - 1) {
  1152. observer.trigger(events["default"].ERROR, {
  1153. type: errors["ErrorTypes"].MEDIA_ERROR,
  1154. details: errors["ErrorDetails"].FRAG_PARSING_ERROR,
  1155. fatal: true,
  1156. reason: "invalid ADTS sampling index:" + adtsSampleingIndex
  1157. });
  1158. return;
  1159. }
  1160. adtsChanelConfig = (data[offset + 2] & 0x01) << 2; // byte 3
  1161. adtsChanelConfig |= (data[offset + 3] & 0xC0) >>> 6;
  1162. logger["logger"].log("manifest codec:" + audioCodec + ",ADTS data:type:" + adtsObjectType + ",sampleingIndex:" + adtsSampleingIndex + "[" + adtsSampleingRates[adtsSampleingIndex] + "Hz],channelConfig:" + adtsChanelConfig); // firefox: freq less than 24kHz = AAC SBR (HE-AAC)
  1163. if (/firefox/i.test(userAgent)) {
  1164. if (adtsSampleingIndex >= 6) {
  1165. adtsObjectType = 5;
  1166. config = new Array(4); // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  1167. // there is a factor 2 between frame sample rate and output sample rate
  1168. // multiply frequency by 2 (see table below, equivalent to substract 3)
  1169. adtsExtensionSampleingIndex = adtsSampleingIndex - 3;
  1170. } else {
  1171. adtsObjectType = 2;
  1172. config = new Array(2);
  1173. adtsExtensionSampleingIndex = adtsSampleingIndex;
  1174. } // Android : always use AAC
  1175. } else if (userAgent.indexOf('android') !== -1) {
  1176. adtsObjectType = 2;
  1177. config = new Array(2);
  1178. adtsExtensionSampleingIndex = adtsSampleingIndex;
  1179. } else {
  1180. /* for other browsers (Chrome/Vivaldi/Opera ...)
  1181. always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)
  1182. */
  1183. adtsObjectType = 5;
  1184. config = new Array(4); // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)
  1185. if (audioCodec && (audioCodec.indexOf('mp4a.40.29') !== -1 || audioCodec.indexOf('mp4a.40.5') !== -1) || !audioCodec && adtsSampleingIndex >= 6) {
  1186. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  1187. // there is a factor 2 between frame sample rate and output sample rate
  1188. // multiply frequency by 2 (see table below, equivalent to substract 3)
  1189. adtsExtensionSampleingIndex = adtsSampleingIndex - 3;
  1190. } else {
  1191. // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)
  1192. // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.
  1193. if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && (adtsSampleingIndex >= 6 && adtsChanelConfig === 1 || /vivaldi/i.test(userAgent)) || !audioCodec && adtsChanelConfig === 1) {
  1194. adtsObjectType = 2;
  1195. config = new Array(2);
  1196. }
  1197. adtsExtensionSampleingIndex = adtsSampleingIndex;
  1198. }
  1199. }
  1200. /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config
  1201. ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()
  1202. Audio Profile / Audio Object Type
  1203. 0: Null
  1204. 1: AAC Main
  1205. 2: AAC LC (Low Complexity)
  1206. 3: AAC SSR (Scalable Sample Rate)
  1207. 4: AAC LTP (Long Term Prediction)
  1208. 5: SBR (Spectral Band Replication)
  1209. 6: AAC Scalable
  1210. sampling freq
  1211. 0: 96000 Hz
  1212. 1: 88200 Hz
  1213. 2: 64000 Hz
  1214. 3: 48000 Hz
  1215. 4: 44100 Hz
  1216. 5: 32000 Hz
  1217. 6: 24000 Hz
  1218. 7: 22050 Hz
  1219. 8: 16000 Hz
  1220. 9: 12000 Hz
  1221. 10: 11025 Hz
  1222. 11: 8000 Hz
  1223. 12: 7350 Hz
  1224. 13: Reserved
  1225. 14: Reserved
  1226. 15: frequency is written explictly
  1227. Channel Configurations
  1228. These are the channel configurations:
  1229. 0: Defined in AOT Specifc Config
  1230. 1: 1 channel: front-center
  1231. 2: 2 channels: front-left, front-right
  1232. */
  1233. // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1
  1234. config[0] = adtsObjectType << 3; // samplingFrequencyIndex
  1235. config[0] |= (adtsSampleingIndex & 0x0E) >> 1;
  1236. config[1] |= (adtsSampleingIndex & 0x01) << 7; // channelConfiguration
  1237. config[1] |= adtsChanelConfig << 3;
  1238. if (adtsObjectType === 5) {
  1239. // adtsExtensionSampleingIndex
  1240. config[1] |= (adtsExtensionSampleingIndex & 0x0E) >> 1;
  1241. config[2] = (adtsExtensionSampleingIndex & 0x01) << 7; // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???
  1242. // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc
  1243. config[2] |= 2 << 2;
  1244. config[3] = 0;
  1245. }
  1246. return {
  1247. config: config,
  1248. samplerate: adtsSampleingRates[adtsSampleingIndex],
  1249. channelCount: adtsChanelConfig,
  1250. codec: 'mp4a.40.' + adtsObjectType,
  1251. manifestCodec: manifestCodec
  1252. };
  1253. }
  1254. function isHeaderPattern(data, offset) {
  1255. return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;
  1256. }
  1257. function getHeaderLength(data, offset) {
  1258. return data[offset + 1] & 0x01 ? 7 : 9;
  1259. }
  1260. function getFullFrameLength(data, offset) {
  1261. return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xE0) >>> 5;
  1262. }
  1263. function isHeader(data, offset) {
  1264. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  1265. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  1266. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  1267. if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
  1268. return true;
  1269. }
  1270. return false;
  1271. }
  1272. function adts_probe(data, offset) {
  1273. // same as isHeader but we also check that ADTS frame follows last ADTS frame
  1274. // or end of data is reached
  1275. if (isHeader(data, offset)) {
  1276. // ADTS header Length
  1277. var headerLength = getHeaderLength(data, offset);
  1278. if (offset + headerLength >= data.length) {
  1279. return false;
  1280. } // ADTS frame Length
  1281. var frameLength = getFullFrameLength(data, offset);
  1282. if (frameLength <= headerLength) {
  1283. return false;
  1284. }
  1285. var newOffset = offset + frameLength;
  1286. if (newOffset === data.length || newOffset + 1 < data.length && isHeaderPattern(data, newOffset)) {
  1287. return true;
  1288. }
  1289. }
  1290. return false;
  1291. }
  1292. function initTrackConfig(track, observer, data, offset, audioCodec) {
  1293. if (!track.samplerate) {
  1294. var config = getAudioConfig(observer, data, offset, audioCodec);
  1295. track.config = config.config;
  1296. track.samplerate = config.samplerate;
  1297. track.channelCount = config.channelCount;
  1298. track.codec = config.codec;
  1299. track.manifestCodec = config.manifestCodec;
  1300. logger["logger"].log("parsed codec:" + track.codec + ",rate:" + config.samplerate + ",nb channel:" + config.channelCount);
  1301. }
  1302. }
  1303. function getFrameDuration(samplerate) {
  1304. return 1024 * 90000 / samplerate;
  1305. }
  1306. function parseFrameHeader(data, offset, pts, frameIndex, frameDuration) {
  1307. var headerLength, frameLength, stamp;
  1308. var length = data.length; // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
  1309. headerLength = getHeaderLength(data, offset); // retrieve frame size
  1310. frameLength = getFullFrameLength(data, offset);
  1311. frameLength -= headerLength;
  1312. if (frameLength > 0 && offset + headerLength + frameLength <= length) {
  1313. stamp = pts + frameIndex * frameDuration; // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
  1314. return {
  1315. headerLength: headerLength,
  1316. frameLength: frameLength,
  1317. stamp: stamp
  1318. };
  1319. }
  1320. return undefined;
  1321. }
  1322. function appendFrame(track, data, offset, pts, frameIndex) {
  1323. var frameDuration = getFrameDuration(track.samplerate);
  1324. var header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration);
  1325. if (header) {
  1326. var stamp = header.stamp;
  1327. var headerLength = header.headerLength;
  1328. var frameLength = header.frameLength; // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
  1329. var aacSample = {
  1330. unit: data.subarray(offset + headerLength, offset + headerLength + frameLength),
  1331. pts: stamp,
  1332. dts: stamp
  1333. };
  1334. track.samples.push(aacSample);
  1335. return {
  1336. sample: aacSample,
  1337. length: frameLength + headerLength
  1338. };
  1339. }
  1340. return undefined;
  1341. }
  1342. // EXTERNAL MODULE: ./src/demux/id3.js
  1343. var id3 = __webpack_require__("./src/demux/id3.js");
  1344. // CONCATENATED MODULE: ./src/demux/aacdemuxer.js
  1345. /**
  1346. * AAC demuxer
  1347. */
  1348. var aacdemuxer_AACDemuxer = /*#__PURE__*/function () {
  1349. function AACDemuxer(observer, remuxer, config) {
  1350. this.observer = observer;
  1351. this.config = config;
  1352. this.remuxer = remuxer;
  1353. }
  1354. var _proto = AACDemuxer.prototype;
  1355. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
  1356. this._audioTrack = {
  1357. container: 'audio/adts',
  1358. type: 'audio',
  1359. id: 0,
  1360. sequenceNumber: 0,
  1361. isAAC: true,
  1362. samples: [],
  1363. len: 0,
  1364. manifestCodec: audioCodec,
  1365. duration: duration,
  1366. inputTimeScale: 90000
  1367. };
  1368. };
  1369. _proto.resetTimeStamp = function resetTimeStamp() {};
  1370. AACDemuxer.probe = function probe(data) {
  1371. if (!data) {
  1372. return false;
  1373. } // Check for the ADTS sync word
  1374. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  1375. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  1376. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  1377. var id3Data = id3["default"].getID3Data(data, 0) || [];
  1378. var offset = id3Data.length;
  1379. for (var length = data.length; offset < length; offset++) {
  1380. if (adts_probe(data, offset)) {
  1381. logger["logger"].log('ADTS sync word found !');
  1382. return true;
  1383. }
  1384. }
  1385. return false;
  1386. } // feed incoming data to the front of the parsing pipeline
  1387. ;
  1388. _proto.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {
  1389. var track = this._audioTrack;
  1390. var id3Data = id3["default"].getID3Data(data, 0) || [];
  1391. var timestamp = id3["default"].getTimeStamp(id3Data);
  1392. var pts = Object(number["isFiniteNumber"])(timestamp) ? timestamp * 90 : timeOffset * 90000;
  1393. var frameIndex = 0;
  1394. var stamp = pts;
  1395. var length = data.length;
  1396. var offset = id3Data.length;
  1397. var id3Samples = [{
  1398. pts: stamp,
  1399. dts: stamp,
  1400. data: id3Data
  1401. }];
  1402. while (offset < length - 1) {
  1403. if (isHeader(data, offset) && offset + 5 < length) {
  1404. initTrackConfig(track, this.observer, data, offset, track.manifestCodec);
  1405. var frame = appendFrame(track, data, offset, pts, frameIndex);
  1406. if (frame) {
  1407. offset += frame.length;
  1408. stamp = frame.sample.pts;
  1409. frameIndex++;
  1410. } else {
  1411. logger["logger"].log('Unable to parse AAC frame');
  1412. break;
  1413. }
  1414. } else if (id3["default"].isHeader(data, offset)) {
  1415. id3Data = id3["default"].getID3Data(data, offset);
  1416. id3Samples.push({
  1417. pts: stamp,
  1418. dts: stamp,
  1419. data: id3Data
  1420. });
  1421. offset += id3Data.length;
  1422. } else {
  1423. // nothing found, keep looking
  1424. offset++;
  1425. }
  1426. }
  1427. this.remuxer.remux(track, {
  1428. samples: []
  1429. }, {
  1430. samples: id3Samples,
  1431. inputTimeScale: 90000
  1432. }, {
  1433. samples: []
  1434. }, timeOffset, contiguous, accurateTimeOffset);
  1435. };
  1436. _proto.destroy = function destroy() {};
  1437. return AACDemuxer;
  1438. }();
  1439. /* harmony default export */ var aacdemuxer = (aacdemuxer_AACDemuxer);
  1440. // EXTERNAL MODULE: ./src/demux/mp4demuxer.js
  1441. var mp4demuxer = __webpack_require__("./src/demux/mp4demuxer.js");
  1442. // CONCATENATED MODULE: ./src/demux/mpegaudio.js
  1443. /**
  1444. * MPEG parser helper
  1445. */
  1446. var MpegAudio = {
  1447. 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],
  1448. SamplingRateMap: [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000],
  1449. SamplesCoefficients: [// MPEG 2.5
  1450. [0, // Reserved
  1451. 72, // Layer3
  1452. 144, // Layer2
  1453. 12 // Layer1
  1454. ], // Reserved
  1455. [0, // Reserved
  1456. 0, // Layer3
  1457. 0, // Layer2
  1458. 0 // Layer1
  1459. ], // MPEG 2
  1460. [0, // Reserved
  1461. 72, // Layer3
  1462. 144, // Layer2
  1463. 12 // Layer1
  1464. ], // MPEG 1
  1465. [0, // Reserved
  1466. 144, // Layer3
  1467. 144, // Layer2
  1468. 12 // Layer1
  1469. ]],
  1470. BytesInSlot: [0, // Reserved
  1471. 1, // Layer3
  1472. 1, // Layer2
  1473. 4 // Layer1
  1474. ],
  1475. appendFrame: function appendFrame(track, data, offset, pts, frameIndex) {
  1476. // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference
  1477. if (offset + 24 > data.length) {
  1478. return undefined;
  1479. }
  1480. var header = this.parseHeader(data, offset);
  1481. if (header && offset + header.frameLength <= data.length) {
  1482. var frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;
  1483. var stamp = pts + frameIndex * frameDuration;
  1484. var sample = {
  1485. unit: data.subarray(offset, offset + header.frameLength),
  1486. pts: stamp,
  1487. dts: stamp
  1488. };
  1489. track.config = [];
  1490. track.channelCount = header.channelCount;
  1491. track.samplerate = header.sampleRate;
  1492. track.samples.push(sample);
  1493. return {
  1494. sample: sample,
  1495. length: header.frameLength
  1496. };
  1497. }
  1498. return undefined;
  1499. },
  1500. parseHeader: function parseHeader(data, offset) {
  1501. var headerB = data[offset + 1] >> 3 & 3;
  1502. var headerC = data[offset + 1] >> 1 & 3;
  1503. var headerE = data[offset + 2] >> 4 & 15;
  1504. var headerF = data[offset + 2] >> 2 & 3;
  1505. var headerG = data[offset + 2] >> 1 & 1;
  1506. if (headerB !== 1 && headerE !== 0 && headerE !== 15 && headerF !== 3) {
  1507. var columnInBitrates = headerB === 3 ? 3 - headerC : headerC === 3 ? 3 : 4;
  1508. var bitRate = MpegAudio.BitratesMap[columnInBitrates * 14 + headerE - 1] * 1000;
  1509. var columnInSampleRates = headerB === 3 ? 0 : headerB === 2 ? 1 : 2;
  1510. var sampleRate = MpegAudio.SamplingRateMap[columnInSampleRates * 3 + headerF];
  1511. var channelCount = data[offset + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)
  1512. var sampleCoefficient = MpegAudio.SamplesCoefficients[headerB][headerC];
  1513. var bytesInSlot = MpegAudio.BytesInSlot[headerC];
  1514. var samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
  1515. var frameLength = parseInt(sampleCoefficient * bitRate / sampleRate + headerG, 10) * bytesInSlot;
  1516. return {
  1517. sampleRate: sampleRate,
  1518. channelCount: channelCount,
  1519. frameLength: frameLength,
  1520. samplesPerFrame: samplesPerFrame
  1521. };
  1522. }
  1523. return undefined;
  1524. },
  1525. isHeaderPattern: function isHeaderPattern(data, offset) {
  1526. return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;
  1527. },
  1528. isHeader: function isHeader(data, offset) {
  1529. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  1530. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  1531. // More info http://www.mp3-tech.org/programmer/frame_header.html
  1532. if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {
  1533. return true;
  1534. }
  1535. return false;
  1536. },
  1537. probe: function probe(data, offset) {
  1538. // same as isHeader but we also check that MPEG frame follows last MPEG frame
  1539. // or end of data is reached
  1540. if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {
  1541. // MPEG header Length
  1542. var headerLength = 4; // MPEG frame Length
  1543. var header = this.parseHeader(data, offset);
  1544. var frameLength = headerLength;
  1545. if (header && header.frameLength) {
  1546. frameLength = header.frameLength;
  1547. }
  1548. var newOffset = offset + frameLength;
  1549. if (newOffset === data.length || newOffset + 1 < data.length && this.isHeaderPattern(data, newOffset)) {
  1550. return true;
  1551. }
  1552. }
  1553. return false;
  1554. }
  1555. };
  1556. /* harmony default export */ var mpegaudio = (MpegAudio);
  1557. // CONCATENATED MODULE: ./src/demux/exp-golomb.js
  1558. /**
  1559. * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
  1560. */
  1561. var exp_golomb_ExpGolomb = /*#__PURE__*/function () {
  1562. function ExpGolomb(data) {
  1563. this.data = data; // the number of bytes left to examine in this.data
  1564. this.bytesAvailable = data.byteLength; // the current word being examined
  1565. this.word = 0; // :uint
  1566. // the number of bits left to examine in the current word
  1567. this.bitsAvailable = 0; // :uint
  1568. } // ():void
  1569. var _proto = ExpGolomb.prototype;
  1570. _proto.loadWord = function loadWord() {
  1571. var data = this.data,
  1572. bytesAvailable = this.bytesAvailable,
  1573. position = data.byteLength - bytesAvailable,
  1574. workingBytes = new Uint8Array(4),
  1575. availableBytes = Math.min(4, bytesAvailable);
  1576. if (availableBytes === 0) {
  1577. throw new Error('no bytes available');
  1578. }
  1579. workingBytes.set(data.subarray(position, position + availableBytes));
  1580. this.word = new DataView(workingBytes.buffer).getUint32(0); // track the amount of this.data that has been processed
  1581. this.bitsAvailable = availableBytes * 8;
  1582. this.bytesAvailable -= availableBytes;
  1583. } // (count:int):void
  1584. ;
  1585. _proto.skipBits = function skipBits(count) {
  1586. var skipBytes; // :int
  1587. if (this.bitsAvailable > count) {
  1588. this.word <<= count;
  1589. this.bitsAvailable -= count;
  1590. } else {
  1591. count -= this.bitsAvailable;
  1592. skipBytes = count >> 3;
  1593. count -= skipBytes >> 3;
  1594. this.bytesAvailable -= skipBytes;
  1595. this.loadWord();
  1596. this.word <<= count;
  1597. this.bitsAvailable -= count;
  1598. }
  1599. } // (size:int):uint
  1600. ;
  1601. _proto.readBits = function readBits(size) {
  1602. var bits = Math.min(this.bitsAvailable, size),
  1603. // :uint
  1604. valu = this.word >>> 32 - bits; // :uint
  1605. if (size > 32) {
  1606. logger["logger"].error('Cannot read more than 32 bits at a time');
  1607. }
  1608. this.bitsAvailable -= bits;
  1609. if (this.bitsAvailable > 0) {
  1610. this.word <<= bits;
  1611. } else if (this.bytesAvailable > 0) {
  1612. this.loadWord();
  1613. }
  1614. bits = size - bits;
  1615. if (bits > 0 && this.bitsAvailable) {
  1616. return valu << bits | this.readBits(bits);
  1617. } else {
  1618. return valu;
  1619. }
  1620. } // ():uint
  1621. ;
  1622. _proto.skipLZ = function skipLZ() {
  1623. var leadingZeroCount; // :uint
  1624. for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
  1625. if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) {
  1626. // the first bit of working word is 1
  1627. this.word <<= leadingZeroCount;
  1628. this.bitsAvailable -= leadingZeroCount;
  1629. return leadingZeroCount;
  1630. }
  1631. } // we exhausted word and still have not found a 1
  1632. this.loadWord();
  1633. return leadingZeroCount + this.skipLZ();
  1634. } // ():void
  1635. ;
  1636. _proto.skipUEG = function skipUEG() {
  1637. this.skipBits(1 + this.skipLZ());
  1638. } // ():void
  1639. ;
  1640. _proto.skipEG = function skipEG() {
  1641. this.skipBits(1 + this.skipLZ());
  1642. } // ():uint
  1643. ;
  1644. _proto.readUEG = function readUEG() {
  1645. var clz = this.skipLZ(); // :uint
  1646. return this.readBits(clz + 1) - 1;
  1647. } // ():int
  1648. ;
  1649. _proto.readEG = function readEG() {
  1650. var valu = this.readUEG(); // :int
  1651. if (0x01 & valu) {
  1652. // the number is odd if the low order bit is set
  1653. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  1654. } else {
  1655. return -1 * (valu >>> 1); // divide by two then make it negative
  1656. }
  1657. } // Some convenience functions
  1658. // :Boolean
  1659. ;
  1660. _proto.readBoolean = function readBoolean() {
  1661. return this.readBits(1) === 1;
  1662. } // ():int
  1663. ;
  1664. _proto.readUByte = function readUByte() {
  1665. return this.readBits(8);
  1666. } // ():int
  1667. ;
  1668. _proto.readUShort = function readUShort() {
  1669. return this.readBits(16);
  1670. } // ():int
  1671. ;
  1672. _proto.readUInt = function readUInt() {
  1673. return this.readBits(32);
  1674. }
  1675. /**
  1676. * Advance the ExpGolomb decoder past a scaling list. The scaling
  1677. * list is optionally transmitted as part of a sequence parameter
  1678. * set and is not relevant to transmuxing.
  1679. * @param count {number} the number of entries in this scaling list
  1680. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  1681. */
  1682. ;
  1683. _proto.skipScalingList = function skipScalingList(count) {
  1684. var lastScale = 8,
  1685. nextScale = 8,
  1686. j,
  1687. deltaScale;
  1688. for (j = 0; j < count; j++) {
  1689. if (nextScale !== 0) {
  1690. deltaScale = this.readEG();
  1691. nextScale = (lastScale + deltaScale + 256) % 256;
  1692. }
  1693. lastScale = nextScale === 0 ? lastScale : nextScale;
  1694. }
  1695. }
  1696. /**
  1697. * Read a sequence parameter set and return some interesting video
  1698. * properties. A sequence parameter set is the H264 metadata that
  1699. * describes the properties of upcoming video frames.
  1700. * @param data {Uint8Array} the bytes of a sequence parameter set
  1701. * @return {object} an object with configuration parsed from the
  1702. * sequence parameter set, including the dimensions of the
  1703. * associated video frames.
  1704. */
  1705. ;
  1706. _proto.readSPS = function readSPS() {
  1707. var frameCropLeftOffset = 0,
  1708. frameCropRightOffset = 0,
  1709. frameCropTopOffset = 0,
  1710. frameCropBottomOffset = 0,
  1711. profileIdc,
  1712. profileCompat,
  1713. levelIdc,
  1714. numRefFramesInPicOrderCntCycle,
  1715. picWidthInMbsMinus1,
  1716. picHeightInMapUnitsMinus1,
  1717. frameMbsOnlyFlag,
  1718. scalingListCount,
  1719. i,
  1720. readUByte = this.readUByte.bind(this),
  1721. readBits = this.readBits.bind(this),
  1722. readUEG = this.readUEG.bind(this),
  1723. readBoolean = this.readBoolean.bind(this),
  1724. skipBits = this.skipBits.bind(this),
  1725. skipEG = this.skipEG.bind(this),
  1726. skipUEG = this.skipUEG.bind(this),
  1727. skipScalingList = this.skipScalingList.bind(this);
  1728. readUByte();
  1729. profileIdc = readUByte(); // profile_idc
  1730. profileCompat = readBits(5); // constraint_set[0-4]_flag, u(5)
  1731. skipBits(3); // reserved_zero_3bits u(3),
  1732. levelIdc = readUByte(); // level_idc u(8)
  1733. skipUEG(); // seq_parameter_set_id
  1734. // some profiles have more optional data we don't need
  1735. if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
  1736. var chromaFormatIdc = readUEG();
  1737. if (chromaFormatIdc === 3) {
  1738. skipBits(1);
  1739. } // separate_colour_plane_flag
  1740. skipUEG(); // bit_depth_luma_minus8
  1741. skipUEG(); // bit_depth_chroma_minus8
  1742. skipBits(1); // qpprime_y_zero_transform_bypass_flag
  1743. if (readBoolean()) {
  1744. // seq_scaling_matrix_present_flag
  1745. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  1746. for (i = 0; i < scalingListCount; i++) {
  1747. if (readBoolean()) {
  1748. // seq_scaling_list_present_flag[ i ]
  1749. if (i < 6) {
  1750. skipScalingList(16);
  1751. } else {
  1752. skipScalingList(64);
  1753. }
  1754. }
  1755. }
  1756. }
  1757. }
  1758. skipUEG(); // log2_max_frame_num_minus4
  1759. var picOrderCntType = readUEG();
  1760. if (picOrderCntType === 0) {
  1761. readUEG(); // log2_max_pic_order_cnt_lsb_minus4
  1762. } else if (picOrderCntType === 1) {
  1763. skipBits(1); // delta_pic_order_always_zero_flag
  1764. skipEG(); // offset_for_non_ref_pic
  1765. skipEG(); // offset_for_top_to_bottom_field
  1766. numRefFramesInPicOrderCntCycle = readUEG();
  1767. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  1768. skipEG();
  1769. } // offset_for_ref_frame[ i ]
  1770. }
  1771. skipUEG(); // max_num_ref_frames
  1772. skipBits(1); // gaps_in_frame_num_value_allowed_flag
  1773. picWidthInMbsMinus1 = readUEG();
  1774. picHeightInMapUnitsMinus1 = readUEG();
  1775. frameMbsOnlyFlag = readBits(1);
  1776. if (frameMbsOnlyFlag === 0) {
  1777. skipBits(1);
  1778. } // mb_adaptive_frame_field_flag
  1779. skipBits(1); // direct_8x8_inference_flag
  1780. if (readBoolean()) {
  1781. // frame_cropping_flag
  1782. frameCropLeftOffset = readUEG();
  1783. frameCropRightOffset = readUEG();
  1784. frameCropTopOffset = readUEG();
  1785. frameCropBottomOffset = readUEG();
  1786. }
  1787. var pixelRatio = [1, 1];
  1788. if (readBoolean()) {
  1789. // vui_parameters_present_flag
  1790. if (readBoolean()) {
  1791. // aspect_ratio_info_present_flag
  1792. var aspectRatioIdc = readUByte();
  1793. switch (aspectRatioIdc) {
  1794. case 1:
  1795. pixelRatio = [1, 1];
  1796. break;
  1797. case 2:
  1798. pixelRatio = [12, 11];
  1799. break;
  1800. case 3:
  1801. pixelRatio = [10, 11];
  1802. break;
  1803. case 4:
  1804. pixelRatio = [16, 11];
  1805. break;
  1806. case 5:
  1807. pixelRatio = [40, 33];
  1808. break;
  1809. case 6:
  1810. pixelRatio = [24, 11];
  1811. break;
  1812. case 7:
  1813. pixelRatio = [20, 11];
  1814. break;
  1815. case 8:
  1816. pixelRatio = [32, 11];
  1817. break;
  1818. case 9:
  1819. pixelRatio = [80, 33];
  1820. break;
  1821. case 10:
  1822. pixelRatio = [18, 11];
  1823. break;
  1824. case 11:
  1825. pixelRatio = [15, 11];
  1826. break;
  1827. case 12:
  1828. pixelRatio = [64, 33];
  1829. break;
  1830. case 13:
  1831. pixelRatio = [160, 99];
  1832. break;
  1833. case 14:
  1834. pixelRatio = [4, 3];
  1835. break;
  1836. case 15:
  1837. pixelRatio = [3, 2];
  1838. break;
  1839. case 16:
  1840. pixelRatio = [2, 1];
  1841. break;
  1842. case 255:
  1843. {
  1844. pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
  1845. break;
  1846. }
  1847. }
  1848. }
  1849. }
  1850. return {
  1851. width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
  1852. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
  1853. pixelRatio: pixelRatio
  1854. };
  1855. };
  1856. _proto.readSliceType = function readSliceType() {
  1857. // skip NALu type
  1858. this.readUByte(); // discard first_mb_in_slice
  1859. this.readUEG(); // return slice_type
  1860. return this.readUEG();
  1861. };
  1862. return ExpGolomb;
  1863. }();
  1864. /* harmony default export */ var exp_golomb = (exp_golomb_ExpGolomb);
  1865. // CONCATENATED MODULE: ./src/demux/sample-aes.js
  1866. /**
  1867. * SAMPLE-AES decrypter
  1868. */
  1869. var sample_aes_SampleAesDecrypter = /*#__PURE__*/function () {
  1870. function SampleAesDecrypter(observer, config, decryptdata, discardEPB) {
  1871. this.decryptdata = decryptdata;
  1872. this.discardEPB = discardEPB;
  1873. this.decrypter = new crypt_decrypter["default"](observer, config, {
  1874. removePKCS7Padding: false
  1875. });
  1876. }
  1877. var _proto = SampleAesDecrypter.prototype;
  1878. _proto.decryptBuffer = function decryptBuffer(encryptedData, callback) {
  1879. this.decrypter.decrypt(encryptedData, this.decryptdata.key.buffer, this.decryptdata.iv.buffer, callback);
  1880. } // AAC - encrypt all full 16 bytes blocks starting from offset 16
  1881. ;
  1882. _proto.decryptAacSample = function decryptAacSample(samples, sampleIndex, callback, sync) {
  1883. var curUnit = samples[sampleIndex].unit;
  1884. var encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
  1885. var encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
  1886. var localthis = this;
  1887. this.decryptBuffer(encryptedBuffer, function (decryptedData) {
  1888. decryptedData = new Uint8Array(decryptedData);
  1889. curUnit.set(decryptedData, 16);
  1890. if (!sync) {
  1891. localthis.decryptAacSamples(samples, sampleIndex + 1, callback);
  1892. }
  1893. });
  1894. };
  1895. _proto.decryptAacSamples = function decryptAacSamples(samples, sampleIndex, callback) {
  1896. for (;; sampleIndex++) {
  1897. if (sampleIndex >= samples.length) {
  1898. callback();
  1899. return;
  1900. }
  1901. if (samples[sampleIndex].unit.length < 32) {
  1902. continue;
  1903. }
  1904. var sync = this.decrypter.isSync();
  1905. this.decryptAacSample(samples, sampleIndex, callback, sync);
  1906. if (!sync) {
  1907. return;
  1908. }
  1909. }
  1910. } // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
  1911. ;
  1912. _proto.getAvcEncryptedData = function getAvcEncryptedData(decodedData) {
  1913. var encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
  1914. var encryptedData = new Int8Array(encryptedDataLen);
  1915. var outputPos = 0;
  1916. for (var inputPos = 32; inputPos <= decodedData.length - 16; inputPos += 160, outputPos += 16) {
  1917. encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
  1918. }
  1919. return encryptedData;
  1920. };
  1921. _proto.getAvcDecryptedUnit = function getAvcDecryptedUnit(decodedData, decryptedData) {
  1922. decryptedData = new Uint8Array(decryptedData);
  1923. var inputPos = 0;
  1924. for (var outputPos = 32; outputPos <= decodedData.length - 16; outputPos += 160, inputPos += 16) {
  1925. decodedData.set(decryptedData.subarray(inputPos, inputPos + 16), outputPos);
  1926. }
  1927. return decodedData;
  1928. };
  1929. _proto.decryptAvcSample = function decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync) {
  1930. var decodedData = this.discardEPB(curUnit.data);
  1931. var encryptedData = this.getAvcEncryptedData(decodedData);
  1932. var localthis = this;
  1933. this.decryptBuffer(encryptedData.buffer, function (decryptedData) {
  1934. curUnit.data = localthis.getAvcDecryptedUnit(decodedData, decryptedData);
  1935. if (!sync) {
  1936. localthis.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
  1937. }
  1938. });
  1939. };
  1940. _proto.decryptAvcSamples = function decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
  1941. for (;; sampleIndex++, unitIndex = 0) {
  1942. if (sampleIndex >= samples.length) {
  1943. callback();
  1944. return;
  1945. }
  1946. var curUnits = samples[sampleIndex].units;
  1947. for (;; unitIndex++) {
  1948. if (unitIndex >= curUnits.length) {
  1949. break;
  1950. }
  1951. var curUnit = curUnits[unitIndex];
  1952. if (curUnit.data.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
  1953. continue;
  1954. }
  1955. var sync = this.decrypter.isSync();
  1956. this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync);
  1957. if (!sync) {
  1958. return;
  1959. }
  1960. }
  1961. }
  1962. };
  1963. return SampleAesDecrypter;
  1964. }();
  1965. /* harmony default export */ var sample_aes = (sample_aes_SampleAesDecrypter);
  1966. // CONCATENATED MODULE: ./src/demux/tsdemuxer.js
  1967. /**
  1968. * highly optimized TS demuxer:
  1969. * parse PAT, PMT
  1970. * extract PES packet from audio and video PIDs
  1971. * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet
  1972. * trigger the remuxer upon parsing completion
  1973. * 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.
  1974. * it also controls the remuxing process :
  1975. * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.
  1976. */
  1977. // import Hex from '../utils/hex';
  1978. // We are using fixed track IDs for driving the MP4 remuxer
  1979. // instead of following the TS PIDs.
  1980. // There is no reason not to do this and some browsers/SourceBuffer-demuxers
  1981. // may not like if there are TrackID "switches"
  1982. // See https://github.com/video-dev/hls.js/issues/1331
  1983. // Here we are mapping our internal track types to constant MP4 track IDs
  1984. // With MSE currently one can only have one track of each, and we are muxing
  1985. // whatever video/audio rendition in them.
  1986. var RemuxerTrackIdConfig = {
  1987. video: 1,
  1988. audio: 2,
  1989. id3: 3,
  1990. text: 4
  1991. };
  1992. var tsdemuxer_TSDemuxer = /*#__PURE__*/function () {
  1993. function TSDemuxer(observer, remuxer, config, typeSupported) {
  1994. this.observer = observer;
  1995. this.config = config;
  1996. this.typeSupported = typeSupported;
  1997. this.remuxer = remuxer;
  1998. this.sampleAes = null;
  1999. this.pmtUnknownTypes = {};
  2000. }
  2001. var _proto = TSDemuxer.prototype;
  2002. _proto.setDecryptData = function setDecryptData(decryptdata) {
  2003. if (decryptdata != null && decryptdata.key != null && decryptdata.method === 'SAMPLE-AES') {
  2004. this.sampleAes = new sample_aes(this.observer, this.config, decryptdata, this.discardEPB);
  2005. } else {
  2006. this.sampleAes = null;
  2007. }
  2008. };
  2009. TSDemuxer.probe = function probe(data) {
  2010. var syncOffset = TSDemuxer._syncOffset(data);
  2011. if (syncOffset < 0) {
  2012. return false;
  2013. } else {
  2014. if (syncOffset) {
  2015. logger["logger"].warn("MPEG2-TS detected but first sync word found @ offset " + syncOffset + ", junk ahead ?");
  2016. }
  2017. return true;
  2018. }
  2019. };
  2020. TSDemuxer._syncOffset = function _syncOffset(data) {
  2021. // scan 1000 first bytes
  2022. var scanwindow = Math.min(1000, data.length - 3 * 188);
  2023. var i = 0;
  2024. while (i < scanwindow) {
  2025. // a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47
  2026. if (data[i] === 0x47 && data[i + 188] === 0x47 && data[i + 2 * 188] === 0x47) {
  2027. return i;
  2028. } else {
  2029. i++;
  2030. }
  2031. }
  2032. return -1;
  2033. }
  2034. /**
  2035. * Creates a track model internal to demuxer used to drive remuxing input
  2036. *
  2037. * @param {string} type 'audio' | 'video' | 'id3' | 'text'
  2038. * @param {number} duration
  2039. * @return {object} TSDemuxer's internal track model
  2040. */
  2041. ;
  2042. TSDemuxer.createTrack = function createTrack(type, duration) {
  2043. return {
  2044. container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,
  2045. type: type,
  2046. id: RemuxerTrackIdConfig[type],
  2047. pid: -1,
  2048. inputTimeScale: 90000,
  2049. sequenceNumber: 0,
  2050. samples: [],
  2051. dropped: type === 'video' ? 0 : undefined,
  2052. isAAC: type === 'audio' ? true : undefined,
  2053. duration: type === 'audio' ? duration : undefined
  2054. };
  2055. }
  2056. /**
  2057. * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
  2058. * Resets all internal track instances of the demuxer.
  2059. *
  2060. * @override Implements generic demuxing/remuxing interface (see DemuxerInline)
  2061. * @param {object} initSegment
  2062. * @param {string} audioCodec
  2063. * @param {string} videoCodec
  2064. * @param {number} duration (in TS timescale = 90kHz)
  2065. */
  2066. ;
  2067. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
  2068. this.pmtParsed = false;
  2069. this._pmtId = -1;
  2070. this.pmtUnknownTypes = {};
  2071. this._avcTrack = TSDemuxer.createTrack('video', duration);
  2072. this._audioTrack = TSDemuxer.createTrack('audio', duration);
  2073. this._id3Track = TSDemuxer.createTrack('id3', duration);
  2074. this._txtTrack = TSDemuxer.createTrack('text', duration); // flush any partial content
  2075. this.aacOverFlow = null;
  2076. this.aacLastPTS = null;
  2077. this.avcSample = null;
  2078. this.audioCodec = audioCodec;
  2079. this.videoCodec = videoCodec;
  2080. this._duration = duration;
  2081. }
  2082. /**
  2083. *
  2084. * @override
  2085. */
  2086. ;
  2087. _proto.resetTimeStamp = function resetTimeStamp() {} // feed incoming data to the front of the parsing pipeline
  2088. ;
  2089. _proto.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {
  2090. var start,
  2091. len = data.length,
  2092. stt,
  2093. pid,
  2094. atf,
  2095. offset,
  2096. pes,
  2097. unknownPIDs = false;
  2098. this.pmtUnknownTypes = {};
  2099. this.contiguous = contiguous;
  2100. var pmtParsed = this.pmtParsed,
  2101. avcTrack = this._avcTrack,
  2102. audioTrack = this._audioTrack,
  2103. id3Track = this._id3Track,
  2104. avcId = avcTrack.pid,
  2105. audioId = audioTrack.pid,
  2106. id3Id = id3Track.pid,
  2107. pmtId = this._pmtId,
  2108. avcData = avcTrack.pesData,
  2109. audioData = audioTrack.pesData,
  2110. id3Data = id3Track.pesData,
  2111. parsePAT = this._parsePAT,
  2112. parsePMT = this._parsePMT.bind(this),
  2113. parsePES = this._parsePES,
  2114. parseAVCPES = this._parseAVCPES.bind(this),
  2115. parseAACPES = this._parseAACPES.bind(this),
  2116. parseMPEGPES = this._parseMPEGPES.bind(this),
  2117. parseID3PES = this._parseID3PES.bind(this);
  2118. var syncOffset = TSDemuxer._syncOffset(data); // don't parse last TS packet if incomplete
  2119. len -= (len + syncOffset) % 188; // loop through TS packets
  2120. for (start = syncOffset; start < len; start += 188) {
  2121. if (data[start] === 0x47) {
  2122. stt = !!(data[start + 1] & 0x40); // pid is a 13-bit field starting at the last bit of TS[1]
  2123. pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];
  2124. atf = (data[start + 3] & 0x30) >> 4; // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.
  2125. if (atf > 1) {
  2126. offset = start + 5 + data[start + 4]; // continue if there is only adaptation field
  2127. if (offset === start + 188) {
  2128. continue;
  2129. }
  2130. } else {
  2131. offset = start + 4;
  2132. }
  2133. switch (pid) {
  2134. case avcId:
  2135. if (stt) {
  2136. if (avcData && (pes = parsePES(avcData))) {
  2137. parseAVCPES(pes, false);
  2138. }
  2139. avcData = {
  2140. data: [],
  2141. size: 0
  2142. };
  2143. }
  2144. if (avcData) {
  2145. avcData.data.push(data.subarray(offset, start + 188));
  2146. avcData.size += start + 188 - offset;
  2147. }
  2148. break;
  2149. case audioId:
  2150. if (stt) {
  2151. if (audioData && (pes = parsePES(audioData))) {
  2152. if (audioTrack.isAAC) {
  2153. parseAACPES(pes);
  2154. } else {
  2155. parseMPEGPES(pes);
  2156. }
  2157. }
  2158. audioData = {
  2159. data: [],
  2160. size: 0
  2161. };
  2162. }
  2163. if (audioData) {
  2164. audioData.data.push(data.subarray(offset, start + 188));
  2165. audioData.size += start + 188 - offset;
  2166. }
  2167. break;
  2168. case id3Id:
  2169. if (stt) {
  2170. if (id3Data && (pes = parsePES(id3Data))) {
  2171. parseID3PES(pes);
  2172. }
  2173. id3Data = {
  2174. data: [],
  2175. size: 0
  2176. };
  2177. }
  2178. if (id3Data) {
  2179. id3Data.data.push(data.subarray(offset, start + 188));
  2180. id3Data.size += start + 188 - offset;
  2181. }
  2182. break;
  2183. case 0:
  2184. if (stt) {
  2185. offset += data[offset] + 1;
  2186. }
  2187. pmtId = this._pmtId = parsePAT(data, offset);
  2188. break;
  2189. case pmtId:
  2190. if (stt) {
  2191. offset += data[offset] + 1;
  2192. }
  2193. var parsedPIDs = parsePMT(data, offset, this.typeSupported.mpeg === true || this.typeSupported.mp3 === true, this.sampleAes != null); // only update track id if track PID found while parsing PMT
  2194. // this is to avoid resetting the PID to -1 in case
  2195. // track PID transiently disappears from the stream
  2196. // this could happen in case of transient missing audio samples for example
  2197. // NOTE this is only the PID of the track as found in TS,
  2198. // but we are not using this for MP4 track IDs.
  2199. avcId = parsedPIDs.avc;
  2200. if (avcId > 0) {
  2201. avcTrack.pid = avcId;
  2202. }
  2203. audioId = parsedPIDs.audio;
  2204. if (audioId > 0) {
  2205. audioTrack.pid = audioId;
  2206. audioTrack.isAAC = parsedPIDs.isAAC;
  2207. }
  2208. id3Id = parsedPIDs.id3;
  2209. if (id3Id > 0) {
  2210. id3Track.pid = id3Id;
  2211. }
  2212. if (unknownPIDs && !pmtParsed) {
  2213. logger["logger"].log('reparse from beginning');
  2214. unknownPIDs = false; // we set it to -188, the += 188 in the for loop will reset start to 0
  2215. start = syncOffset - 188;
  2216. }
  2217. pmtParsed = this.pmtParsed = true;
  2218. break;
  2219. case 17:
  2220. case 0x1fff:
  2221. break;
  2222. default:
  2223. unknownPIDs = true;
  2224. break;
  2225. }
  2226. } else {
  2227. this.observer.trigger(events["default"].ERROR, {
  2228. type: errors["ErrorTypes"].MEDIA_ERROR,
  2229. details: errors["ErrorDetails"].FRAG_PARSING_ERROR,
  2230. fatal: false,
  2231. reason: 'TS packet did not start with 0x47'
  2232. });
  2233. }
  2234. } // try to parse last PES packets
  2235. if (avcData && (pes = parsePES(avcData))) {
  2236. parseAVCPES(pes, true);
  2237. avcTrack.pesData = null;
  2238. } else {
  2239. // either avcData null or PES truncated, keep it for next frag parsing
  2240. avcTrack.pesData = avcData;
  2241. }
  2242. if (audioData && (pes = parsePES(audioData))) {
  2243. if (audioTrack.isAAC) {
  2244. parseAACPES(pes);
  2245. } else {
  2246. parseMPEGPES(pes);
  2247. }
  2248. audioTrack.pesData = null;
  2249. } else {
  2250. if (audioData && audioData.size) {
  2251. logger["logger"].log('last AAC PES packet truncated,might overlap between fragments');
  2252. } // either audioData null or PES truncated, keep it for next frag parsing
  2253. audioTrack.pesData = audioData;
  2254. }
  2255. if (id3Data && (pes = parsePES(id3Data))) {
  2256. parseID3PES(pes);
  2257. id3Track.pesData = null;
  2258. } else {
  2259. // either id3Data null or PES truncated, keep it for next frag parsing
  2260. id3Track.pesData = id3Data;
  2261. }
  2262. if (this.sampleAes == null) {
  2263. this.remuxer.remux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);
  2264. } else {
  2265. this.decryptAndRemux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);
  2266. }
  2267. };
  2268. _proto.decryptAndRemux = function decryptAndRemux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
  2269. if (audioTrack.samples && audioTrack.isAAC) {
  2270. var localthis = this;
  2271. this.sampleAes.decryptAacSamples(audioTrack.samples, 0, function () {
  2272. localthis.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
  2273. });
  2274. } else {
  2275. this.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
  2276. }
  2277. };
  2278. _proto.decryptAndRemuxAvc = function decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
  2279. if (videoTrack.samples) {
  2280. var localthis = this;
  2281. this.sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, function () {
  2282. localthis.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
  2283. });
  2284. } else {
  2285. this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
  2286. }
  2287. };
  2288. _proto.destroy = function destroy() {
  2289. this._initPTS = this._initDTS = undefined;
  2290. this._duration = 0;
  2291. };
  2292. _proto._parsePAT = function _parsePAT(data, offset) {
  2293. // skip the PSI header and parse the first PMT entry
  2294. return (data[offset + 10] & 0x1F) << 8 | data[offset + 11]; // logger.log('PMT PID:' + this._pmtId);
  2295. };
  2296. _proto._trackUnknownPmt = function _trackUnknownPmt(type, logLevel, message) {
  2297. // Only log unknown and unsupported stream types once per append or stream (by resetting this.pmtUnknownTypes)
  2298. // For more information on elementary stream types see:
  2299. // https://en.wikipedia.org/wiki/Program-specific_information#Elementary_stream_types
  2300. var result = this.pmtUnknownTypes[type] || 0;
  2301. if (result === 0) {
  2302. this.pmtUnknownTypes[type] = 0;
  2303. logLevel.call(logger["logger"], message);
  2304. }
  2305. this.pmtUnknownTypes[type]++;
  2306. return result;
  2307. };
  2308. _proto._parsePMT = function _parsePMT(data, offset, mpegSupported, isSampleAes) {
  2309. var sectionLength,
  2310. tableEnd,
  2311. programInfoLength,
  2312. pid,
  2313. result = {
  2314. audio: -1,
  2315. avc: -1,
  2316. id3: -1,
  2317. isAAC: true
  2318. };
  2319. sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
  2320. tableEnd = offset + 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  2321. // long the program info descriptors are
  2322. programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11]; // advance the offset to the first entry in the mapping table
  2323. offset += 12 + programInfoLength;
  2324. while (offset < tableEnd) {
  2325. pid = (data[offset + 1] & 0x1F) << 8 | data[offset + 2];
  2326. switch (data[offset]) {
  2327. case 0xcf:
  2328. // SAMPLE-AES AAC
  2329. if (!isSampleAes) {
  2330. this._trackUnknownPmt(data[offset], logger["logger"].warn, 'ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream');
  2331. break;
  2332. }
  2333. /* falls through */
  2334. // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
  2335. case 0x0f:
  2336. // logger.log('AAC PID:' + pid);
  2337. if (result.audio === -1) {
  2338. result.audio = pid;
  2339. }
  2340. break;
  2341. // Packetized metadata (ID3)
  2342. case 0x15:
  2343. // logger.log('ID3 PID:' + pid);
  2344. if (result.id3 === -1) {
  2345. result.id3 = pid;
  2346. }
  2347. break;
  2348. case 0xdb:
  2349. // SAMPLE-AES AVC
  2350. if (!isSampleAes) {
  2351. this._trackUnknownPmt(data[offset], logger["logger"].warn, 'H.264 with AES-128-CBC slice encryption found in unencrypted stream');
  2352. break;
  2353. }
  2354. /* falls through */
  2355. // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
  2356. case 0x1b:
  2357. // logger.log('AVC PID:' + pid);
  2358. if (result.avc === -1) {
  2359. result.avc = pid;
  2360. }
  2361. break;
  2362. // ISO/IEC 11172-3 (MPEG-1 audio)
  2363. // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)
  2364. case 0x03:
  2365. case 0x04:
  2366. // logger.log('MPEG PID:' + pid);
  2367. if (!mpegSupported) {
  2368. this._trackUnknownPmt(data[offset], logger["logger"].warn, 'MPEG audio found, not supported in this browser');
  2369. } else if (result.audio === -1) {
  2370. result.audio = pid;
  2371. result.isAAC = false;
  2372. }
  2373. break;
  2374. case 0x24:
  2375. this._trackUnknownPmt(data[offset], logger["logger"].warn, 'Unsupported HEVC stream type found');
  2376. break;
  2377. default:
  2378. this._trackUnknownPmt(data[offset], logger["logger"].log, 'Unknown stream type:' + data[offset]);
  2379. break;
  2380. } // move to the next table entry
  2381. // skip past the elementary stream descriptors, if present
  2382. offset += ((data[offset + 3] & 0x0F) << 8 | data[offset + 4]) + 5;
  2383. }
  2384. return result;
  2385. };
  2386. _proto._parsePES = function _parsePES(stream) {
  2387. var i = 0,
  2388. frag,
  2389. pesFlags,
  2390. pesPrefix,
  2391. pesLen,
  2392. pesHdrLen,
  2393. pesData,
  2394. pesPts,
  2395. pesDts,
  2396. payloadStartOffset,
  2397. data = stream.data; // safety check
  2398. if (!stream || stream.size === 0) {
  2399. return null;
  2400. } // we might need up to 19 bytes to read PES header
  2401. // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes
  2402. // usually only one merge is needed (and this is rare ...)
  2403. while (data[0].length < 19 && data.length > 1) {
  2404. var newData = new Uint8Array(data[0].length + data[1].length);
  2405. newData.set(data[0]);
  2406. newData.set(data[1], data[0].length);
  2407. data[0] = newData;
  2408. data.splice(1, 1);
  2409. } // retrieve PTS/DTS from first fragment
  2410. frag = data[0];
  2411. pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
  2412. if (pesPrefix === 1) {
  2413. pesLen = (frag[4] << 8) + frag[5]; // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated
  2414. // minus 6 : PES header size
  2415. if (pesLen && pesLen > stream.size - 6) {
  2416. return null;
  2417. }
  2418. pesFlags = frag[7];
  2419. if (pesFlags & 0xC0) {
  2420. /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  2421. as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
  2422. as Bitwise operators treat their operands as a sequence of 32 bits */
  2423. pesPts = (frag[9] & 0x0E) * 536870912 + // 1 << 29
  2424. (frag[10] & 0xFF) * 4194304 + // 1 << 22
  2425. (frag[11] & 0xFE) * 16384 + // 1 << 14
  2426. (frag[12] & 0xFF) * 128 + // 1 << 7
  2427. (frag[13] & 0xFE) / 2;
  2428. if (pesFlags & 0x40) {
  2429. pesDts = (frag[14] & 0x0E) * 536870912 + // 1 << 29
  2430. (frag[15] & 0xFF) * 4194304 + // 1 << 22
  2431. (frag[16] & 0xFE) * 16384 + // 1 << 14
  2432. (frag[17] & 0xFF) * 128 + // 1 << 7
  2433. (frag[18] & 0xFE) / 2;
  2434. if (pesPts - pesDts > 60 * 90000) {
  2435. logger["logger"].warn(Math.round((pesPts - pesDts) / 90000) + "s delta between PTS and DTS, align them");
  2436. pesPts = pesDts;
  2437. }
  2438. } else {
  2439. pesDts = pesPts;
  2440. }
  2441. }
  2442. pesHdrLen = frag[8]; // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension
  2443. payloadStartOffset = pesHdrLen + 9;
  2444. if (stream.size <= payloadStartOffset) {
  2445. return null;
  2446. }
  2447. stream.size -= payloadStartOffset; // reassemble PES packet
  2448. pesData = new Uint8Array(stream.size);
  2449. for (var j = 0, dataLen = data.length; j < dataLen; j++) {
  2450. frag = data[j];
  2451. var len = frag.byteLength;
  2452. if (payloadStartOffset) {
  2453. if (payloadStartOffset > len) {
  2454. // trim full frag if PES header bigger than frag
  2455. payloadStartOffset -= len;
  2456. continue;
  2457. } else {
  2458. // trim partial frag if PES header smaller than frag
  2459. frag = frag.subarray(payloadStartOffset);
  2460. len -= payloadStartOffset;
  2461. payloadStartOffset = 0;
  2462. }
  2463. }
  2464. pesData.set(frag, i);
  2465. i += len;
  2466. }
  2467. if (pesLen) {
  2468. // payload size : remove PES header + PES extension
  2469. pesLen -= pesHdrLen + 3;
  2470. }
  2471. return {
  2472. data: pesData,
  2473. pts: pesPts,
  2474. dts: pesDts,
  2475. len: pesLen
  2476. };
  2477. } else {
  2478. return null;
  2479. }
  2480. };
  2481. _proto.pushAccesUnit = function pushAccesUnit(avcSample, avcTrack) {
  2482. if (avcSample.units.length && avcSample.frame) {
  2483. var samples = avcTrack.samples;
  2484. var nbSamples = samples.length; // if sample does not have PTS/DTS, patch with last sample PTS/DTS
  2485. if (isNaN(avcSample.pts)) {
  2486. if (nbSamples) {
  2487. var lastSample = samples[nbSamples - 1];
  2488. avcSample.pts = lastSample.pts;
  2489. avcSample.dts = lastSample.dts;
  2490. } else {
  2491. // dropping samples, no timestamp found
  2492. avcTrack.dropped++;
  2493. return;
  2494. }
  2495. } // only push AVC sample if starting with a keyframe is not mandatory OR
  2496. // if keyframe already found in this fragment OR
  2497. // keyframe found in last fragment (track.sps) AND
  2498. // samples already appended (we already found a keyframe in this fragment) OR fragment is contiguous
  2499. if (!this.config.forceKeyFrameOnDiscontinuity || avcSample.key === true || avcTrack.sps && (nbSamples || this.contiguous)) {
  2500. avcSample.id = nbSamples;
  2501. samples.push(avcSample);
  2502. } else {
  2503. // dropped samples, track it
  2504. avcTrack.dropped++;
  2505. }
  2506. }
  2507. if (avcSample.debug.length) {
  2508. logger["logger"].log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug);
  2509. }
  2510. };
  2511. _proto._parseAVCPES = function _parseAVCPES(pes, last) {
  2512. var _this = this;
  2513. // logger.log('parse new PES');
  2514. var track = this._avcTrack,
  2515. units = this._parseAVCNALu(pes.data),
  2516. debug = false,
  2517. expGolombDecoder,
  2518. avcSample = this.avcSample,
  2519. push,
  2520. spsfound = false,
  2521. i,
  2522. pushAccesUnit = this.pushAccesUnit.bind(this),
  2523. createAVCSample = function createAVCSample(key, pts, dts, debug) {
  2524. return {
  2525. key: key,
  2526. pts: pts,
  2527. dts: dts,
  2528. units: [],
  2529. debug: debug
  2530. };
  2531. }; // free pes.data to save up some memory
  2532. pes.data = null; // if new NAL units found and last sample still there, let's push ...
  2533. // this helps parsing streams with missing AUD (only do this if AUD never found)
  2534. if (avcSample && units.length && !track.audFound) {
  2535. pushAccesUnit(avcSample, track);
  2536. avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, '');
  2537. }
  2538. units.forEach(function (unit) {
  2539. switch (unit.type) {
  2540. // NDR
  2541. case 1:
  2542. push = true;
  2543. if (!avcSample) {
  2544. avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
  2545. }
  2546. if (debug) {
  2547. avcSample.debug += 'NDR ';
  2548. }
  2549. avcSample.frame = true;
  2550. var data = unit.data; // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)
  2551. if (spsfound && data.length > 4) {
  2552. // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR
  2553. var sliceType = new exp_golomb(data).readSliceType(); // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice
  2554. // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.
  2555. // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.
  2556. // I slice: A slice that is not an SI slice that is decoded using intra prediction only.
  2557. // if (sliceType === 2 || sliceType === 7) {
  2558. if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
  2559. avcSample.key = true;
  2560. }
  2561. }
  2562. break;
  2563. // IDR
  2564. case 5:
  2565. push = true; // handle PES not starting with AUD
  2566. if (!avcSample) {
  2567. avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
  2568. }
  2569. if (debug) {
  2570. avcSample.debug += 'IDR ';
  2571. }
  2572. avcSample.key = true;
  2573. avcSample.frame = true;
  2574. break;
  2575. // SEI
  2576. case 6:
  2577. push = true;
  2578. if (debug && avcSample) {
  2579. avcSample.debug += 'SEI ';
  2580. }
  2581. expGolombDecoder = new exp_golomb(_this.discardEPB(unit.data)); // skip frameType
  2582. expGolombDecoder.readUByte();
  2583. var payloadType = 0;
  2584. var payloadSize = 0;
  2585. var endOfCaptions = false;
  2586. var b = 0;
  2587. while (!endOfCaptions && expGolombDecoder.bytesAvailable > 1) {
  2588. payloadType = 0;
  2589. do {
  2590. b = expGolombDecoder.readUByte();
  2591. payloadType += b;
  2592. } while (b === 0xFF); // Parse payload size.
  2593. payloadSize = 0;
  2594. do {
  2595. b = expGolombDecoder.readUByte();
  2596. payloadSize += b;
  2597. } while (b === 0xFF); // TODO: there can be more than one payload in an SEI packet...
  2598. // TODO: need to read type and size in a while loop to get them all
  2599. if (payloadType === 4 && expGolombDecoder.bytesAvailable !== 0) {
  2600. endOfCaptions = true;
  2601. var countryCode = expGolombDecoder.readUByte();
  2602. if (countryCode === 181) {
  2603. var providerCode = expGolombDecoder.readUShort();
  2604. if (providerCode === 49) {
  2605. var userStructure = expGolombDecoder.readUInt();
  2606. if (userStructure === 0x47413934) {
  2607. var userDataType = expGolombDecoder.readUByte(); // Raw CEA-608 bytes wrapped in CEA-708 packet
  2608. if (userDataType === 3) {
  2609. var firstByte = expGolombDecoder.readUByte();
  2610. var secondByte = expGolombDecoder.readUByte();
  2611. var totalCCs = 31 & firstByte;
  2612. var byteArray = [firstByte, secondByte];
  2613. for (i = 0; i < totalCCs; i++) {
  2614. // 3 bytes per CC
  2615. byteArray.push(expGolombDecoder.readUByte());
  2616. byteArray.push(expGolombDecoder.readUByte());
  2617. byteArray.push(expGolombDecoder.readUByte());
  2618. }
  2619. _this._insertSampleInOrder(_this._txtTrack.samples, {
  2620. type: 3,
  2621. pts: pes.pts,
  2622. bytes: byteArray
  2623. });
  2624. }
  2625. }
  2626. }
  2627. }
  2628. } else if (payloadType === 5 && expGolombDecoder.bytesAvailable !== 0) {
  2629. endOfCaptions = true;
  2630. if (payloadSize > 16) {
  2631. var uuidStrArray = [];
  2632. for (i = 0; i < 16; i++) {
  2633. uuidStrArray.push(expGolombDecoder.readUByte().toString(16));
  2634. if (i === 3 || i === 5 || i === 7 || i === 9) {
  2635. uuidStrArray.push('-');
  2636. }
  2637. }
  2638. var length = payloadSize - 16;
  2639. var userDataPayloadBytes = new Uint8Array(length);
  2640. for (i = 0; i < length; i++) {
  2641. userDataPayloadBytes[i] = expGolombDecoder.readUByte();
  2642. }
  2643. _this._insertSampleInOrder(_this._txtTrack.samples, {
  2644. pts: pes.pts,
  2645. payloadType: payloadType,
  2646. uuid: uuidStrArray.join(''),
  2647. userDataBytes: userDataPayloadBytes,
  2648. userData: Object(id3["utf8ArrayToStr"])(userDataPayloadBytes.buffer)
  2649. });
  2650. }
  2651. } else if (payloadSize < expGolombDecoder.bytesAvailable) {
  2652. for (i = 0; i < payloadSize; i++) {
  2653. expGolombDecoder.readUByte();
  2654. }
  2655. }
  2656. }
  2657. break;
  2658. // SPS
  2659. case 7:
  2660. push = true;
  2661. spsfound = true;
  2662. if (debug && avcSample) {
  2663. avcSample.debug += 'SPS ';
  2664. }
  2665. if (!track.sps) {
  2666. expGolombDecoder = new exp_golomb(unit.data);
  2667. var config = expGolombDecoder.readSPS();
  2668. track.width = config.width;
  2669. track.height = config.height;
  2670. track.pixelRatio = config.pixelRatio;
  2671. track.sps = [unit.data];
  2672. track.duration = _this._duration;
  2673. var codecarray = unit.data.subarray(1, 4);
  2674. var codecstring = 'avc1.';
  2675. for (i = 0; i < 3; i++) {
  2676. var h = codecarray[i].toString(16);
  2677. if (h.length < 2) {
  2678. h = '0' + h;
  2679. }
  2680. codecstring += h;
  2681. }
  2682. track.codec = codecstring;
  2683. }
  2684. break;
  2685. // PPS
  2686. case 8:
  2687. push = true;
  2688. if (debug && avcSample) {
  2689. avcSample.debug += 'PPS ';
  2690. }
  2691. if (!track.pps) {
  2692. track.pps = [unit.data];
  2693. }
  2694. break;
  2695. // AUD
  2696. case 9:
  2697. push = false;
  2698. track.audFound = true;
  2699. if (avcSample) {
  2700. pushAccesUnit(avcSample, track);
  2701. }
  2702. avcSample = _this.avcSample = createAVCSample(false, pes.pts, pes.dts, debug ? 'AUD ' : '');
  2703. break;
  2704. // Filler Data
  2705. case 12:
  2706. push = false;
  2707. break;
  2708. default:
  2709. push = false;
  2710. if (avcSample) {
  2711. avcSample.debug += 'unknown NAL ' + unit.type + ' ';
  2712. }
  2713. break;
  2714. }
  2715. if (avcSample && push) {
  2716. var _units = avcSample.units;
  2717. _units.push(unit);
  2718. }
  2719. }); // if last PES packet, push samples
  2720. if (last && avcSample) {
  2721. pushAccesUnit(avcSample, track);
  2722. this.avcSample = null;
  2723. }
  2724. };
  2725. _proto._insertSampleInOrder = function _insertSampleInOrder(arr, data) {
  2726. var len = arr.length;
  2727. if (len > 0) {
  2728. if (data.pts >= arr[len - 1].pts) {
  2729. arr.push(data);
  2730. } else {
  2731. for (var pos = len - 1; pos >= 0; pos--) {
  2732. if (data.pts < arr[pos].pts) {
  2733. arr.splice(pos, 0, data);
  2734. break;
  2735. }
  2736. }
  2737. }
  2738. } else {
  2739. arr.push(data);
  2740. }
  2741. };
  2742. _proto._getLastNalUnit = function _getLastNalUnit() {
  2743. var avcSample = this.avcSample,
  2744. lastUnit; // try to fallback to previous sample if current one is empty
  2745. if (!avcSample || avcSample.units.length === 0) {
  2746. var track = this._avcTrack,
  2747. samples = track.samples;
  2748. avcSample = samples[samples.length - 1];
  2749. }
  2750. if (avcSample) {
  2751. var units = avcSample.units;
  2752. lastUnit = units[units.length - 1];
  2753. }
  2754. return lastUnit;
  2755. };
  2756. _proto._parseAVCNALu = function _parseAVCNALu(array) {
  2757. var i = 0,
  2758. len = array.byteLength,
  2759. value,
  2760. overflow,
  2761. track = this._avcTrack,
  2762. state = track.naluState || 0,
  2763. lastState = state;
  2764. var units = [],
  2765. unit,
  2766. unitType,
  2767. lastUnitStart = -1,
  2768. lastUnitType; // logger.log('PES:' + Hex.hexDump(array));
  2769. if (state === -1) {
  2770. // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet
  2771. lastUnitStart = 0; // NALu type is value read from offset 0
  2772. lastUnitType = array[0] & 0x1f;
  2773. state = 0;
  2774. i = 1;
  2775. }
  2776. while (i < len) {
  2777. value = array[i++]; // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case
  2778. if (!state) {
  2779. state = value ? 0 : 1;
  2780. continue;
  2781. }
  2782. if (state === 1) {
  2783. state = value ? 0 : 2;
  2784. continue;
  2785. } // here we have state either equal to 2 or 3
  2786. if (!value) {
  2787. state = 3;
  2788. } else if (value === 1) {
  2789. if (lastUnitStart >= 0) {
  2790. unit = {
  2791. data: array.subarray(lastUnitStart, i - state - 1),
  2792. type: lastUnitType
  2793. }; // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
  2794. units.push(unit);
  2795. } else {
  2796. // lastUnitStart is undefined => this is the first start code found in this PES packet
  2797. // first check if start code delimiter is overlapping between 2 PES packets,
  2798. // ie it started in last packet (lastState not zero)
  2799. // and ended at the beginning of this PES packet (i <= 4 - lastState)
  2800. var lastUnit = this._getLastNalUnit();
  2801. if (lastUnit) {
  2802. if (lastState && i <= 4 - lastState) {
  2803. // start delimiter overlapping between PES packets
  2804. // strip start delimiter bytes from the end of last NAL unit
  2805. // check if lastUnit had a state different from zero
  2806. if (lastUnit.state) {
  2807. // strip last bytes
  2808. lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
  2809. }
  2810. } // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.
  2811. overflow = i - state - 1;
  2812. if (overflow > 0) {
  2813. // logger.log('first NALU found with overflow:' + overflow);
  2814. var tmp = new Uint8Array(lastUnit.data.byteLength + overflow);
  2815. tmp.set(lastUnit.data, 0);
  2816. tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);
  2817. lastUnit.data = tmp;
  2818. }
  2819. }
  2820. } // check if we can read unit type
  2821. if (i < len) {
  2822. unitType = array[i] & 0x1f; // logger.log('find NALU @ offset:' + i + ',type:' + unitType);
  2823. lastUnitStart = i;
  2824. lastUnitType = unitType;
  2825. state = 0;
  2826. } else {
  2827. // not enough byte to read unit type. let's read it on next PES parsing
  2828. state = -1;
  2829. }
  2830. } else {
  2831. state = 0;
  2832. }
  2833. }
  2834. if (lastUnitStart >= 0 && state >= 0) {
  2835. unit = {
  2836. data: array.subarray(lastUnitStart, len),
  2837. type: lastUnitType,
  2838. state: state
  2839. };
  2840. units.push(unit); // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);
  2841. } // no NALu found
  2842. if (units.length === 0) {
  2843. // append pes.data to previous NAL unit
  2844. var _lastUnit = this._getLastNalUnit();
  2845. if (_lastUnit) {
  2846. var _tmp = new Uint8Array(_lastUnit.data.byteLength + array.byteLength);
  2847. _tmp.set(_lastUnit.data, 0);
  2848. _tmp.set(array, _lastUnit.data.byteLength);
  2849. _lastUnit.data = _tmp;
  2850. }
  2851. }
  2852. track.naluState = state;
  2853. return units;
  2854. }
  2855. /**
  2856. * remove Emulation Prevention bytes from a RBSP
  2857. */
  2858. ;
  2859. _proto.discardEPB = function discardEPB(data) {
  2860. var length = data.byteLength,
  2861. EPBPositions = [],
  2862. i = 1,
  2863. newLength,
  2864. newData; // Find all `Emulation Prevention Bytes`
  2865. while (i < length - 2) {
  2866. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  2867. EPBPositions.push(i + 2);
  2868. i += 2;
  2869. } else {
  2870. i++;
  2871. }
  2872. } // If no Emulation Prevention Bytes were found just return the original
  2873. // array
  2874. if (EPBPositions.length === 0) {
  2875. return data;
  2876. } // Create a new array to hold the NAL unit data
  2877. newLength = length - EPBPositions.length;
  2878. newData = new Uint8Array(newLength);
  2879. var sourceIndex = 0;
  2880. for (i = 0; i < newLength; sourceIndex++, i++) {
  2881. if (sourceIndex === EPBPositions[0]) {
  2882. // Skip this byte
  2883. sourceIndex++; // Remove this position index
  2884. EPBPositions.shift();
  2885. }
  2886. newData[i] = data[sourceIndex];
  2887. }
  2888. return newData;
  2889. };
  2890. _proto._parseAACPES = function _parseAACPES(pes) {
  2891. var track = this._audioTrack,
  2892. data = pes.data,
  2893. pts = pes.pts,
  2894. startOffset = 0,
  2895. aacOverFlow = this.aacOverFlow,
  2896. aacLastPTS = this.aacLastPTS,
  2897. frameDuration,
  2898. frameIndex,
  2899. offset,
  2900. stamp,
  2901. len;
  2902. if (aacOverFlow) {
  2903. var tmp = new Uint8Array(aacOverFlow.byteLength + data.byteLength);
  2904. tmp.set(aacOverFlow, 0);
  2905. tmp.set(data, aacOverFlow.byteLength); // logger.log(`AAC: append overflowing ${aacOverFlow.byteLength} bytes to beginning of new PES`);
  2906. data = tmp;
  2907. } // look for ADTS header (0xFFFx)
  2908. for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
  2909. if (isHeader(data, offset)) {
  2910. break;
  2911. }
  2912. } // if ADTS header does not start straight from the beginning of the PES payload, raise an error
  2913. if (offset) {
  2914. var reason, fatal;
  2915. if (offset < len - 1) {
  2916. reason = "AAC PES did not start with ADTS header,offset:" + offset;
  2917. fatal = false;
  2918. } else {
  2919. reason = 'no ADTS header found in AAC PES';
  2920. fatal = true;
  2921. }
  2922. logger["logger"].warn("parsing error:" + reason);
  2923. this.observer.trigger(events["default"].ERROR, {
  2924. type: errors["ErrorTypes"].MEDIA_ERROR,
  2925. details: errors["ErrorDetails"].FRAG_PARSING_ERROR,
  2926. fatal: fatal,
  2927. reason: reason
  2928. });
  2929. if (fatal) {
  2930. return;
  2931. }
  2932. }
  2933. initTrackConfig(track, this.observer, data, offset, this.audioCodec);
  2934. frameIndex = 0;
  2935. frameDuration = getFrameDuration(track.samplerate); // if last AAC frame is overflowing, we should ensure timestamps are contiguous:
  2936. // first sample PTS should be equal to last sample PTS + frameDuration
  2937. if (aacOverFlow && aacLastPTS) {
  2938. var newPTS = aacLastPTS + frameDuration;
  2939. if (Math.abs(newPTS - pts) > 1) {
  2940. logger["logger"].log("AAC: align PTS for overlapping frames by " + Math.round((newPTS - pts) / 90));
  2941. pts = newPTS;
  2942. }
  2943. } // scan for aac samples
  2944. while (offset < len) {
  2945. if (isHeader(data, offset)) {
  2946. if (offset + 5 < len) {
  2947. var frame = appendFrame(track, data, offset, pts, frameIndex);
  2948. if (frame) {
  2949. offset += frame.length;
  2950. stamp = frame.sample.pts;
  2951. frameIndex++;
  2952. continue;
  2953. }
  2954. } // We are at an ADTS header, but do not have enough data for a frame
  2955. // Remaining data will be added to aacOverFlow
  2956. break;
  2957. } else {
  2958. // nothing found, keep looking
  2959. offset++;
  2960. }
  2961. }
  2962. if (offset < len) {
  2963. aacOverFlow = data.subarray(offset, len); // logger.log(`AAC: overflow detected:${len-offset}`);
  2964. } else {
  2965. aacOverFlow = null;
  2966. }
  2967. this.aacOverFlow = aacOverFlow;
  2968. this.aacLastPTS = stamp;
  2969. };
  2970. _proto._parseMPEGPES = function _parseMPEGPES(pes) {
  2971. var data = pes.data;
  2972. var length = data.length;
  2973. var frameIndex = 0;
  2974. var offset = 0;
  2975. var pts = pes.pts;
  2976. while (offset < length) {
  2977. if (mpegaudio.isHeader(data, offset)) {
  2978. var frame = mpegaudio.appendFrame(this._audioTrack, data, offset, pts, frameIndex);
  2979. if (frame) {
  2980. offset += frame.length;
  2981. frameIndex++;
  2982. } else {
  2983. // logger.log('Unable to parse Mpeg audio frame');
  2984. break;
  2985. }
  2986. } else {
  2987. // nothing found, keep looking
  2988. offset++;
  2989. }
  2990. }
  2991. };
  2992. _proto._parseID3PES = function _parseID3PES(pes) {
  2993. this._id3Track.samples.push(pes);
  2994. };
  2995. return TSDemuxer;
  2996. }();
  2997. /* harmony default export */ var tsdemuxer = (tsdemuxer_TSDemuxer);
  2998. // CONCATENATED MODULE: ./src/demux/mp3demuxer.js
  2999. /**
  3000. * MP3 demuxer
  3001. */
  3002. var mp3demuxer_MP3Demuxer = /*#__PURE__*/function () {
  3003. function MP3Demuxer(observer, remuxer, config) {
  3004. this.observer = observer;
  3005. this.config = config;
  3006. this.remuxer = remuxer;
  3007. }
  3008. var _proto = MP3Demuxer.prototype;
  3009. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
  3010. this._audioTrack = {
  3011. container: 'audio/mpeg',
  3012. type: 'audio',
  3013. id: -1,
  3014. sequenceNumber: 0,
  3015. isAAC: false,
  3016. samples: [],
  3017. len: 0,
  3018. manifestCodec: audioCodec,
  3019. duration: duration,
  3020. inputTimeScale: 90000
  3021. };
  3022. };
  3023. _proto.resetTimeStamp = function resetTimeStamp() {};
  3024. MP3Demuxer.probe = function probe(data) {
  3025. // check if data contains ID3 timestamp and MPEG sync word
  3026. var offset, length;
  3027. var id3Data = id3["default"].getID3Data(data, 0);
  3028. if (id3Data && id3["default"].getTimeStamp(id3Data) !== undefined) {
  3029. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  3030. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  3031. // More info http://www.mp3-tech.org/programmer/frame_header.html
  3032. for (offset = id3Data.length, length = Math.min(data.length - 1, offset + 100); offset < length; offset++) {
  3033. if (mpegaudio.probe(data, offset)) {
  3034. logger["logger"].log('MPEG Audio sync word found !');
  3035. return true;
  3036. }
  3037. }
  3038. }
  3039. return false;
  3040. } // feed incoming data to the front of the parsing pipeline
  3041. ;
  3042. _proto.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {
  3043. var id3Data = id3["default"].getID3Data(data, 0) || [];
  3044. var timestamp = id3["default"].getTimeStamp(id3Data);
  3045. var pts = timestamp !== undefined ? 90 * timestamp : timeOffset * 90000;
  3046. var offset = id3Data.length;
  3047. var length = data.length;
  3048. var frameIndex = 0,
  3049. stamp = 0;
  3050. var track = this._audioTrack;
  3051. var id3Samples = [{
  3052. pts: pts,
  3053. dts: pts,
  3054. data: id3Data
  3055. }];
  3056. while (offset < length) {
  3057. if (mpegaudio.isHeader(data, offset)) {
  3058. var frame = mpegaudio.appendFrame(track, data, offset, pts, frameIndex);
  3059. if (frame) {
  3060. offset += frame.length;
  3061. stamp = frame.sample.pts;
  3062. frameIndex++;
  3063. } else {
  3064. // logger.log('Unable to parse Mpeg audio frame');
  3065. break;
  3066. }
  3067. } else if (id3["default"].isHeader(data, offset)) {
  3068. id3Data = id3["default"].getID3Data(data, offset);
  3069. id3Samples.push({
  3070. pts: stamp,
  3071. dts: stamp,
  3072. data: id3Data
  3073. });
  3074. offset += id3Data.length;
  3075. } else {
  3076. // nothing found, keep looking
  3077. offset++;
  3078. }
  3079. }
  3080. this.remuxer.remux(track, {
  3081. samples: []
  3082. }, {
  3083. samples: id3Samples,
  3084. inputTimeScale: 90000
  3085. }, {
  3086. samples: []
  3087. }, timeOffset, contiguous, accurateTimeOffset);
  3088. };
  3089. _proto.destroy = function destroy() {};
  3090. return MP3Demuxer;
  3091. }();
  3092. /* harmony default export */ var mp3demuxer = (mp3demuxer_MP3Demuxer);
  3093. // CONCATENATED MODULE: ./src/remux/aac-helper.js
  3094. /**
  3095. * AAC helper
  3096. */
  3097. var AAC = /*#__PURE__*/function () {
  3098. function AAC() {}
  3099. AAC.getSilentFrame = function getSilentFrame(codec, channelCount) {
  3100. switch (codec) {
  3101. case 'mp4a.40.2':
  3102. if (channelCount === 1) {
  3103. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
  3104. } else if (channelCount === 2) {
  3105. return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
  3106. } else if (channelCount === 3) {
  3107. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
  3108. } else if (channelCount === 4) {
  3109. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
  3110. } else if (channelCount === 5) {
  3111. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
  3112. } else if (channelCount === 6) {
  3113. 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]);
  3114. }
  3115. break;
  3116. // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)
  3117. default:
  3118. if (channelCount === 1) {
  3119. // 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
  3120. 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]);
  3121. } else if (channelCount === 2) {
  3122. // 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
  3123. 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]);
  3124. } else if (channelCount === 3) {
  3125. // 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
  3126. 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]);
  3127. }
  3128. break;
  3129. }
  3130. return null;
  3131. };
  3132. return AAC;
  3133. }();
  3134. /* harmony default export */ var aac_helper = (AAC);
  3135. // CONCATENATED MODULE: ./src/remux/mp4-generator.js
  3136. /**
  3137. * Generate MP4 Box
  3138. */
  3139. var UINT32_MAX = Math.pow(2, 32) - 1;
  3140. var MP4 = /*#__PURE__*/function () {
  3141. function MP4() {}
  3142. MP4.init = function init() {
  3143. MP4.types = {
  3144. avc1: [],
  3145. // codingname
  3146. avcC: [],
  3147. btrt: [],
  3148. dinf: [],
  3149. dref: [],
  3150. esds: [],
  3151. ftyp: [],
  3152. hdlr: [],
  3153. mdat: [],
  3154. mdhd: [],
  3155. mdia: [],
  3156. mfhd: [],
  3157. minf: [],
  3158. moof: [],
  3159. moov: [],
  3160. mp4a: [],
  3161. '.mp3': [],
  3162. mvex: [],
  3163. mvhd: [],
  3164. pasp: [],
  3165. sdtp: [],
  3166. stbl: [],
  3167. stco: [],
  3168. stsc: [],
  3169. stsd: [],
  3170. stsz: [],
  3171. stts: [],
  3172. tfdt: [],
  3173. tfhd: [],
  3174. traf: [],
  3175. trak: [],
  3176. trun: [],
  3177. trex: [],
  3178. tkhd: [],
  3179. vmhd: [],
  3180. smhd: []
  3181. };
  3182. var i;
  3183. for (i in MP4.types) {
  3184. if (MP4.types.hasOwnProperty(i)) {
  3185. MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  3186. }
  3187. }
  3188. var videoHdlr = new Uint8Array([0x00, // version 0
  3189. 0x00, 0x00, 0x00, // flags
  3190. 0x00, 0x00, 0x00, 0x00, // pre_defined
  3191. 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
  3192. 0x00, 0x00, 0x00, 0x00, // reserved
  3193. 0x00, 0x00, 0x00, 0x00, // reserved
  3194. 0x00, 0x00, 0x00, 0x00, // reserved
  3195. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  3196. ]);
  3197. var audioHdlr = new Uint8Array([0x00, // version 0
  3198. 0x00, 0x00, 0x00, // flags
  3199. 0x00, 0x00, 0x00, 0x00, // pre_defined
  3200. 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
  3201. 0x00, 0x00, 0x00, 0x00, // reserved
  3202. 0x00, 0x00, 0x00, 0x00, // reserved
  3203. 0x00, 0x00, 0x00, 0x00, // reserved
  3204. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  3205. ]);
  3206. MP4.HDLR_TYPES = {
  3207. 'video': videoHdlr,
  3208. 'audio': audioHdlr
  3209. };
  3210. var dref = new Uint8Array([0x00, // version 0
  3211. 0x00, 0x00, 0x00, // flags
  3212. 0x00, 0x00, 0x00, 0x01, // entry_count
  3213. 0x00, 0x00, 0x00, 0x0c, // entry_size
  3214. 0x75, 0x72, 0x6c, 0x20, // 'url' type
  3215. 0x00, // version 0
  3216. 0x00, 0x00, 0x01 // entry_flags
  3217. ]);
  3218. var stco = new Uint8Array([0x00, // version
  3219. 0x00, 0x00, 0x00, // flags
  3220. 0x00, 0x00, 0x00, 0x00 // entry_count
  3221. ]);
  3222. MP4.STTS = MP4.STSC = MP4.STCO = stco;
  3223. MP4.STSZ = new Uint8Array([0x00, // version
  3224. 0x00, 0x00, 0x00, // flags
  3225. 0x00, 0x00, 0x00, 0x00, // sample_size
  3226. 0x00, 0x00, 0x00, 0x00 // sample_count
  3227. ]);
  3228. MP4.VMHD = new Uint8Array([0x00, // version
  3229. 0x00, 0x00, 0x01, // flags
  3230. 0x00, 0x00, // graphicsmode
  3231. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  3232. ]);
  3233. MP4.SMHD = new Uint8Array([0x00, // version
  3234. 0x00, 0x00, 0x00, // flags
  3235. 0x00, 0x00, // balance
  3236. 0x00, 0x00 // reserved
  3237. ]);
  3238. MP4.STSD = new Uint8Array([0x00, // version 0
  3239. 0x00, 0x00, 0x00, // flags
  3240. 0x00, 0x00, 0x00, 0x01]); // entry_count
  3241. var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom
  3242. var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1
  3243. var minorVersion = new Uint8Array([0, 0, 0, 1]);
  3244. MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
  3245. MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
  3246. };
  3247. MP4.box = function box(type) {
  3248. var payload = Array.prototype.slice.call(arguments, 1),
  3249. size = 8,
  3250. i = payload.length,
  3251. len = i,
  3252. result; // calculate the total size we need to allocate
  3253. while (i--) {
  3254. size += payload[i].byteLength;
  3255. }
  3256. result = new Uint8Array(size);
  3257. result[0] = size >> 24 & 0xff;
  3258. result[1] = size >> 16 & 0xff;
  3259. result[2] = size >> 8 & 0xff;
  3260. result[3] = size & 0xff;
  3261. result.set(type, 4); // copy the payload into the result
  3262. for (i = 0, size = 8; i < len; i++) {
  3263. // copy payload[i] array @ offset size
  3264. result.set(payload[i], size);
  3265. size += payload[i].byteLength;
  3266. }
  3267. return result;
  3268. };
  3269. MP4.hdlr = function hdlr(type) {
  3270. return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
  3271. };
  3272. MP4.mdat = function mdat(data) {
  3273. return MP4.box(MP4.types.mdat, data);
  3274. };
  3275. MP4.mdhd = function mdhd(timescale, duration) {
  3276. duration *= timescale;
  3277. var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  3278. var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  3279. return MP4.box(MP4.types.mdhd, new Uint8Array([0x01, // version 1
  3280. 0x00, 0x00, 0x00, // flags
  3281. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
  3282. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
  3283. timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale
  3284. 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)
  3285. 0x00, 0x00]));
  3286. };
  3287. MP4.mdia = function mdia(track) {
  3288. return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));
  3289. };
  3290. MP4.mfhd = function mfhd(sequenceNumber) {
  3291. return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
  3292. sequenceNumber >> 24, sequenceNumber >> 16 & 0xFF, sequenceNumber >> 8 & 0xFF, sequenceNumber & 0xFF // sequence_number
  3293. ]));
  3294. };
  3295. MP4.minf = function minf(track) {
  3296. if (track.type === 'audio') {
  3297. return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
  3298. } else {
  3299. return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
  3300. }
  3301. };
  3302. MP4.moof = function moof(sn, baseMediaDecodeTime, track) {
  3303. return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
  3304. }
  3305. /**
  3306. * @param tracks... (optional) {array} the tracks associated with this movie
  3307. */
  3308. ;
  3309. MP4.moov = function moov(tracks) {
  3310. var i = tracks.length,
  3311. boxes = [];
  3312. while (i--) {
  3313. boxes[i] = MP4.trak(tracks[i]);
  3314. }
  3315. return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));
  3316. };
  3317. MP4.mvex = function mvex(tracks) {
  3318. var i = tracks.length,
  3319. boxes = [];
  3320. while (i--) {
  3321. boxes[i] = MP4.trex(tracks[i]);
  3322. }
  3323. return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));
  3324. };
  3325. MP4.mvhd = function mvhd(timescale, duration) {
  3326. duration *= timescale;
  3327. var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  3328. var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  3329. var bytes = new Uint8Array([0x01, // version 1
  3330. 0x00, 0x00, 0x00, // flags
  3331. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
  3332. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
  3333. timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale
  3334. 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
  3335. 0x01, 0x00, // 1.0 volume
  3336. 0x00, 0x00, // reserved
  3337. 0x00, 0x00, 0x00, 0x00, // reserved
  3338. 0x00, 0x00, 0x00, 0x00, // reserved
  3339. 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
  3340. 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
  3341. 0xff, 0xff, 0xff, 0xff // next_track_ID
  3342. ]);
  3343. return MP4.box(MP4.types.mvhd, bytes);
  3344. };
  3345. MP4.sdtp = function sdtp(track) {
  3346. var samples = track.samples || [],
  3347. bytes = new Uint8Array(4 + samples.length),
  3348. flags,
  3349. i; // leave the full box header (4 bytes) all zero
  3350. // write the sample table
  3351. for (i = 0; i < samples.length; i++) {
  3352. flags = samples[i].flags;
  3353. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  3354. }
  3355. return MP4.box(MP4.types.sdtp, bytes);
  3356. };
  3357. MP4.stbl = function stbl(track) {
  3358. 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));
  3359. };
  3360. MP4.avc1 = function avc1(track) {
  3361. var sps = [],
  3362. pps = [],
  3363. i,
  3364. data,
  3365. len; // assemble the SPSs
  3366. for (i = 0; i < track.sps.length; i++) {
  3367. data = track.sps[i];
  3368. len = data.byteLength;
  3369. sps.push(len >>> 8 & 0xFF);
  3370. sps.push(len & 0xFF); // SPS
  3371. sps = sps.concat(Array.prototype.slice.call(data));
  3372. } // assemble the PPSs
  3373. for (i = 0; i < track.pps.length; i++) {
  3374. data = track.pps[i];
  3375. len = data.byteLength;
  3376. pps.push(len >>> 8 & 0xFF);
  3377. pps.push(len & 0xFF);
  3378. pps = pps.concat(Array.prototype.slice.call(data));
  3379. }
  3380. var avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01, // version
  3381. sps[3], // profile
  3382. sps[4], // profile compat
  3383. sps[5], // level
  3384. 0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes
  3385. 0xE0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets
  3386. ].concat(sps).concat([track.pps.length // numOfPictureParameterSets
  3387. ]).concat(pps))),
  3388. // "PPS"
  3389. width = track.width,
  3390. height = track.height,
  3391. hSpacing = track.pixelRatio[0],
  3392. vSpacing = track.pixelRatio[1];
  3393. return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00, // reserved
  3394. 0x00, 0x00, 0x00, // reserved
  3395. 0x00, 0x01, // data_reference_index
  3396. 0x00, 0x00, // pre_defined
  3397. 0x00, 0x00, // reserved
  3398. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
  3399. width >> 8 & 0xFF, width & 0xff, // width
  3400. height >> 8 & 0xFF, height & 0xff, // height
  3401. 0x00, 0x48, 0x00, 0x00, // horizresolution
  3402. 0x00, 0x48, 0x00, 0x00, // vertresolution
  3403. 0x00, 0x00, 0x00, 0x00, // reserved
  3404. 0x00, 0x01, // frame_count
  3405. 0x12, 0x64, 0x61, 0x69, 0x6C, // dailymotion/hls.js
  3406. 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
  3407. 0x00, 0x18, // depth = 24
  3408. 0x11, 0x11]), // pre_defined = -1
  3409. avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
  3410. 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
  3411. 0x00, 0x2d, 0xc6, 0xc0])), // avgBitrate
  3412. MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24, // hSpacing
  3413. hSpacing >> 16 & 0xFF, hSpacing >> 8 & 0xFF, hSpacing & 0xFF, vSpacing >> 24, // vSpacing
  3414. vSpacing >> 16 & 0xFF, vSpacing >> 8 & 0xFF, vSpacing & 0xFF])));
  3415. };
  3416. MP4.esds = function esds(track) {
  3417. var configlen = track.config.length;
  3418. return new Uint8Array([0x00, // version 0
  3419. 0x00, 0x00, 0x00, // flags
  3420. 0x03, // descriptor_type
  3421. 0x17 + configlen, // length
  3422. 0x00, 0x01, // es_id
  3423. 0x00, // stream_priority
  3424. 0x04, // descriptor_type
  3425. 0x0f + configlen, // length
  3426. 0x40, // codec : mpeg4_audio
  3427. 0x15, // stream_type
  3428. 0x00, 0x00, 0x00, // buffer_size
  3429. 0x00, 0x00, 0x00, 0x00, // maxBitrate
  3430. 0x00, 0x00, 0x00, 0x00, // avgBitrate
  3431. 0x05 // descriptor_type
  3432. ].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor
  3433. };
  3434. MP4.mp4a = function mp4a(track) {
  3435. var samplerate = track.samplerate;
  3436. return MP4.box(MP4.types.mp4a, new Uint8Array([0x00, 0x00, 0x00, // reserved
  3437. 0x00, 0x00, 0x00, // reserved
  3438. 0x00, 0x01, // data_reference_index
  3439. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  3440. 0x00, track.channelCount, // channelcount
  3441. 0x00, 0x10, // sampleSize:16bits
  3442. 0x00, 0x00, 0x00, 0x00, // reserved2
  3443. samplerate >> 8 & 0xFF, samplerate & 0xff, //
  3444. 0x00, 0x00]), MP4.box(MP4.types.esds, MP4.esds(track)));
  3445. };
  3446. MP4.mp3 = function mp3(track) {
  3447. var samplerate = track.samplerate;
  3448. return MP4.box(MP4.types['.mp3'], new Uint8Array([0x00, 0x00, 0x00, // reserved
  3449. 0x00, 0x00, 0x00, // reserved
  3450. 0x00, 0x01, // data_reference_index
  3451. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  3452. 0x00, track.channelCount, // channelcount
  3453. 0x00, 0x10, // sampleSize:16bits
  3454. 0x00, 0x00, 0x00, 0x00, // reserved2
  3455. samplerate >> 8 & 0xFF, samplerate & 0xff, //
  3456. 0x00, 0x00]));
  3457. };
  3458. MP4.stsd = function stsd(track) {
  3459. if (track.type === 'audio') {
  3460. if (!track.isAAC && track.codec === 'mp3') {
  3461. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));
  3462. }
  3463. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
  3464. } else {
  3465. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
  3466. }
  3467. };
  3468. MP4.tkhd = function tkhd(track) {
  3469. var id = track.id,
  3470. duration = track.duration * track.timescale,
  3471. width = track.width,
  3472. height = track.height,
  3473. upperWordDuration = Math.floor(duration / (UINT32_MAX + 1)),
  3474. lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  3475. return MP4.box(MP4.types.tkhd, new Uint8Array([0x01, // version 1
  3476. 0x00, 0x00, 0x07, // flags
  3477. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
  3478. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
  3479. id >> 24 & 0xFF, id >> 16 & 0xFF, id >> 8 & 0xFF, id & 0xFF, // track_ID
  3480. 0x00, 0x00, 0x00, 0x00, // reserved
  3481. 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
  3482. 0x00, 0x00, // layer
  3483. 0x00, 0x00, // alternate_group
  3484. 0x00, 0x00, // non-audio track volume
  3485. 0x00, 0x00, // reserved
  3486. 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
  3487. width >> 8 & 0xFF, width & 0xFF, 0x00, 0x00, // width
  3488. height >> 8 & 0xFF, height & 0xFF, 0x00, 0x00 // height
  3489. ]));
  3490. };
  3491. MP4.traf = function traf(track, baseMediaDecodeTime) {
  3492. var sampleDependencyTable = MP4.sdtp(track),
  3493. id = track.id,
  3494. upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1)),
  3495. lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
  3496. return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00, // version 0
  3497. 0x00, 0x00, 0x00, // flags
  3498. id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF // track_ID
  3499. ])), MP4.box(MP4.types.tfdt, new Uint8Array([0x01, // version 1
  3500. 0x00, 0x00, 0x00, // flags
  3501. 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
  3502. 20 + // tfdt
  3503. 8 + // traf header
  3504. 16 + // mfhd
  3505. 8 + // moof header
  3506. 8), // mdat header
  3507. sampleDependencyTable);
  3508. }
  3509. /**
  3510. * Generate a track box.
  3511. * @param track {object} a track definition
  3512. * @return {Uint8Array} the track box
  3513. */
  3514. ;
  3515. MP4.trak = function trak(track) {
  3516. track.duration = track.duration || 0xffffffff;
  3517. return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
  3518. };
  3519. MP4.trex = function trex(track) {
  3520. var id = track.id;
  3521. return MP4.box(MP4.types.trex, new Uint8Array([0x00, // version 0
  3522. 0x00, 0x00, 0x00, // flags
  3523. id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF, // track_ID
  3524. 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
  3525. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  3526. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  3527. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  3528. ]));
  3529. };
  3530. MP4.trun = function trun(track, offset) {
  3531. var samples = track.samples || [],
  3532. len = samples.length,
  3533. arraylen = 12 + 16 * len,
  3534. array = new Uint8Array(arraylen),
  3535. i,
  3536. sample,
  3537. duration,
  3538. size,
  3539. flags,
  3540. cts;
  3541. offset += 8 + arraylen;
  3542. array.set([0x00, // version 0
  3543. 0x00, 0x0f, 0x01, // flags
  3544. len >>> 24 & 0xFF, len >>> 16 & 0xFF, len >>> 8 & 0xFF, len & 0xFF, // sample_count
  3545. offset >>> 24 & 0xFF, offset >>> 16 & 0xFF, offset >>> 8 & 0xFF, offset & 0xFF // data_offset
  3546. ], 0);
  3547. for (i = 0; i < len; i++) {
  3548. sample = samples[i];
  3549. duration = sample.duration;
  3550. size = sample.size;
  3551. flags = sample.flags;
  3552. cts = sample.cts;
  3553. array.set([duration >>> 24 & 0xFF, duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, // sample_duration
  3554. size >>> 24 & 0xFF, size >>> 16 & 0xFF, size >>> 8 & 0xFF, size & 0xFF, // sample_size
  3555. 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
  3556. cts >>> 24 & 0xFF, cts >>> 16 & 0xFF, cts >>> 8 & 0xFF, cts & 0xFF // sample_composition_time_offset
  3557. ], 12 + 16 * i);
  3558. }
  3559. return MP4.box(MP4.types.trun, array);
  3560. };
  3561. MP4.initSegment = function initSegment(tracks) {
  3562. if (!MP4.types) {
  3563. MP4.init();
  3564. }
  3565. var movie = MP4.moov(tracks),
  3566. result;
  3567. result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);
  3568. result.set(MP4.FTYP);
  3569. result.set(movie, MP4.FTYP.byteLength);
  3570. return result;
  3571. };
  3572. return MP4;
  3573. }();
  3574. /* harmony default export */ var mp4_generator = (MP4);
  3575. // CONCATENATED MODULE: ./src/utils/timescale-conversion.ts
  3576. var MPEG_TS_CLOCK_FREQ_HZ = 90000;
  3577. function toTimescaleFromScale(value, destScale, srcScale, round) {
  3578. if (srcScale === void 0) {
  3579. srcScale = 1;
  3580. }
  3581. if (round === void 0) {
  3582. round = false;
  3583. }
  3584. return toTimescaleFromBase(value, destScale, 1 / srcScale);
  3585. }
  3586. function toTimescaleFromBase(value, destScale, srcBase, round) {
  3587. if (srcBase === void 0) {
  3588. srcBase = 1;
  3589. }
  3590. if (round === void 0) {
  3591. round = false;
  3592. }
  3593. var result = value * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)`
  3594. return round ? Math.round(result) : result;
  3595. }
  3596. function toMsFromMpegTsClock(value, round) {
  3597. if (round === void 0) {
  3598. round = false;
  3599. }
  3600. return toTimescaleFromBase(value, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);
  3601. }
  3602. function toMpegTsClockFromTimescale(value, srcScale) {
  3603. if (srcScale === void 0) {
  3604. srcScale = 1;
  3605. }
  3606. return toTimescaleFromBase(value, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);
  3607. }
  3608. // CONCATENATED MODULE: ./src/remux/mp4-remuxer.js
  3609. /**
  3610. * fMP4 remuxer
  3611. */
  3612. var MAX_SILENT_FRAME_DURATION_90KHZ = toMpegTsClockFromTimescale(10);
  3613. var PTS_DTS_SHIFT_TOLERANCE_90KHZ = toMpegTsClockFromTimescale(0.2);
  3614. var chromeVersion = null;
  3615. var mp4_remuxer_MP4Remuxer = /*#__PURE__*/function () {
  3616. function MP4Remuxer(observer, config, typeSupported, vendor) {
  3617. this.observer = observer;
  3618. this.config = config;
  3619. this.typeSupported = typeSupported;
  3620. this.ISGenerated = false;
  3621. if (chromeVersion === null) {
  3622. var result = navigator.userAgent.match(/Chrome\/(\d+)/i);
  3623. chromeVersion = result ? parseInt(result[1]) : 0;
  3624. }
  3625. }
  3626. var _proto = MP4Remuxer.prototype;
  3627. _proto.destroy = function destroy() {};
  3628. _proto.resetTimeStamp = function resetTimeStamp(defaultTimeStamp) {
  3629. this._initPTS = this._initDTS = defaultTimeStamp;
  3630. };
  3631. _proto.resetInitSegment = function resetInitSegment() {
  3632. this.ISGenerated = false;
  3633. };
  3634. _proto.getVideoStartPts = function getVideoStartPts(videoSamples) {
  3635. var rolloverDetected = false;
  3636. var startPTS = videoSamples.reduce(function (minPTS, sample) {
  3637. var delta = sample.pts - minPTS;
  3638. if (delta < -4294967296) {
  3639. // 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation
  3640. rolloverDetected = true;
  3641. return PTSNormalize(minPTS, sample.pts);
  3642. } else if (delta > 0) {
  3643. return minPTS;
  3644. } else {
  3645. return sample.pts;
  3646. }
  3647. }, videoSamples[0].pts);
  3648. if (rolloverDetected) {
  3649. logger["logger"].debug('PTS rollover detected');
  3650. }
  3651. return startPTS;
  3652. };
  3653. _proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
  3654. // generate Init Segment if needed
  3655. if (!this.ISGenerated) {
  3656. this.generateIS(audioTrack, videoTrack, timeOffset);
  3657. }
  3658. if (this.ISGenerated) {
  3659. var nbAudioSamples = audioTrack.samples.length;
  3660. var nbVideoSamples = videoTrack.samples.length;
  3661. var audioTimeOffset = timeOffset;
  3662. var videoTimeOffset = timeOffset;
  3663. if (nbAudioSamples && nbVideoSamples) {
  3664. // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)
  3665. // if first audio DTS is not aligned with first video DTS then we need to take that into account
  3666. // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small
  3667. // drift between audio and video streams
  3668. var startPTS = this.getVideoStartPts(videoTrack.samples);
  3669. var tsDelta = PTSNormalize(audioTrack.samples[0].pts, startPTS) - startPTS;
  3670. var audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;
  3671. audioTimeOffset += Math.max(0, audiovideoTimestampDelta);
  3672. videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);
  3673. } // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is
  3674. // calculated in remuxAudio.
  3675. // logger.log('nb AAC samples:' + audioTrack.samples.length);
  3676. if (nbAudioSamples) {
  3677. // if initSegment was generated without video samples, regenerate it again
  3678. if (!audioTrack.timescale) {
  3679. logger["logger"].warn('regenerate InitSegment as audio detected');
  3680. this.generateIS(audioTrack, videoTrack, timeOffset);
  3681. }
  3682. var audioData = this.remuxAudio(audioTrack, audioTimeOffset, contiguous, accurateTimeOffset); // logger.log('nb AVC samples:' + videoTrack.samples.length);
  3683. if (nbVideoSamples) {
  3684. var audioTrackLength;
  3685. if (audioData) {
  3686. audioTrackLength = audioData.endPTS - audioData.startPTS;
  3687. } // if initSegment was generated without video samples, regenerate it again
  3688. if (!videoTrack.timescale) {
  3689. logger["logger"].warn('regenerate InitSegment as video detected');
  3690. this.generateIS(audioTrack, videoTrack, timeOffset);
  3691. }
  3692. this.remuxVideo(videoTrack, videoTimeOffset, contiguous, audioTrackLength);
  3693. }
  3694. } else {
  3695. // logger.log('nb AVC samples:' + videoTrack.samples.length);
  3696. if (nbVideoSamples) {
  3697. var videoData = this.remuxVideo(videoTrack, videoTimeOffset, contiguous, 0, accurateTimeOffset);
  3698. if (videoData && audioTrack.codec) {
  3699. this.remuxEmptyAudio(audioTrack, audioTimeOffset, contiguous, videoData);
  3700. }
  3701. }
  3702. }
  3703. } // logger.log('nb ID3 samples:' + audioTrack.samples.length);
  3704. if (id3Track.samples.length) {
  3705. this.remuxID3(id3Track, timeOffset);
  3706. } // logger.log('nb ID3 samples:' + audioTrack.samples.length);
  3707. if (textTrack.samples.length) {
  3708. this.remuxText(textTrack, timeOffset);
  3709. } // notify end of parsing
  3710. this.observer.trigger(events["default"].FRAG_PARSED);
  3711. };
  3712. _proto.generateIS = function generateIS(audioTrack, videoTrack, timeOffset) {
  3713. var observer = this.observer,
  3714. audioSamples = audioTrack.samples,
  3715. videoSamples = videoTrack.samples,
  3716. typeSupported = this.typeSupported,
  3717. container = 'audio/mp4',
  3718. tracks = {},
  3719. data = {
  3720. tracks: tracks
  3721. },
  3722. computePTSDTS = this._initPTS === undefined,
  3723. initPTS,
  3724. initDTS;
  3725. if (computePTSDTS) {
  3726. initPTS = initDTS = Infinity;
  3727. }
  3728. if (audioTrack.config && audioSamples.length) {
  3729. // let's use audio sampling rate as MP4 time scale.
  3730. // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)
  3731. // using audio sampling rate here helps having an integer MP4 frame duration
  3732. // this avoids potential rounding issue and AV sync issue
  3733. audioTrack.timescale = audioTrack.samplerate;
  3734. logger["logger"].log("audio sampling rate : " + audioTrack.samplerate);
  3735. if (!audioTrack.isAAC) {
  3736. if (typeSupported.mpeg) {
  3737. // Chrome and Safari
  3738. container = 'audio/mpeg';
  3739. audioTrack.codec = '';
  3740. } else if (typeSupported.mp3) {
  3741. // Firefox
  3742. audioTrack.codec = 'mp3';
  3743. }
  3744. }
  3745. tracks.audio = {
  3746. container: container,
  3747. codec: audioTrack.codec,
  3748. initSegment: !audioTrack.isAAC && typeSupported.mpeg ? new Uint8Array() : mp4_generator.initSegment([audioTrack]),
  3749. metadata: {
  3750. channelCount: audioTrack.channelCount
  3751. }
  3752. };
  3753. if (computePTSDTS) {
  3754. // remember first PTS of this demuxing context. for audio, PTS = DTS
  3755. initPTS = initDTS = audioSamples[0].pts - Math.round(audioTrack.inputTimeScale * timeOffset);
  3756. }
  3757. }
  3758. if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
  3759. // let's use input time scale as MP4 video timescale
  3760. // we use input time scale straight away to avoid rounding issues on frame duration / cts computation
  3761. var inputTimeScale = videoTrack.inputTimeScale;
  3762. videoTrack.timescale = inputTimeScale;
  3763. tracks.video = {
  3764. container: 'video/mp4',
  3765. codec: videoTrack.codec,
  3766. initSegment: mp4_generator.initSegment([videoTrack]),
  3767. metadata: {
  3768. width: videoTrack.width,
  3769. height: videoTrack.height
  3770. }
  3771. };
  3772. if (computePTSDTS) {
  3773. var startPTS = this.getVideoStartPts(videoSamples);
  3774. var startOffset = Math.round(inputTimeScale * timeOffset);
  3775. initDTS = Math.min(initDTS, PTSNormalize(videoSamples[0].dts, startPTS) - startOffset);
  3776. initPTS = Math.min(initPTS, startPTS - startOffset);
  3777. this.observer.trigger(events["default"].INIT_PTS_FOUND, {
  3778. initPTS: initPTS
  3779. });
  3780. }
  3781. } else if (computePTSDTS && tracks.audio) {
  3782. // initPTS found for audio-only stream with main and alt audio
  3783. this.observer.trigger(events["default"].INIT_PTS_FOUND, {
  3784. initPTS: initPTS
  3785. });
  3786. }
  3787. if (Object.keys(tracks).length) {
  3788. observer.trigger(events["default"].FRAG_PARSING_INIT_SEGMENT, data);
  3789. this.ISGenerated = true;
  3790. if (computePTSDTS) {
  3791. this._initPTS = initPTS;
  3792. this._initDTS = initDTS;
  3793. }
  3794. } else {
  3795. observer.trigger(events["default"].ERROR, {
  3796. type: errors["ErrorTypes"].MEDIA_ERROR,
  3797. details: errors["ErrorDetails"].FRAG_PARSING_ERROR,
  3798. fatal: false,
  3799. reason: 'no audio/video samples found'
  3800. });
  3801. }
  3802. };
  3803. _proto.remuxVideo = function remuxVideo(track, timeOffset, contiguous, audioTrackLength) {
  3804. var timeScale = track.timescale;
  3805. var inputSamples = track.samples;
  3806. var outputSamples = [];
  3807. var nbSamples = inputSamples.length;
  3808. var initPTS = this._initPTS;
  3809. var offset = 8;
  3810. var mp4SampleDuration;
  3811. var mdat;
  3812. var moof;
  3813. var firstDTS;
  3814. var lastDTS;
  3815. var minPTS = Number.POSITIVE_INFINITY;
  3816. var maxPTS = Number.NEGATIVE_INFINITY;
  3817. var ptsDtsShift = 0;
  3818. var sortSamples = false; // if parsed fragment is contiguous with last one, let's use last DTS value as reference
  3819. var nextAvcDts = this.nextAvcDts;
  3820. if (nbSamples === 0) {
  3821. return;
  3822. }
  3823. if (!contiguous) {
  3824. var pts = timeOffset * timeScale;
  3825. var cts = inputSamples[0].pts - PTSNormalize(inputSamples[0].dts, inputSamples[0].pts); // if not contiguous, let's use target timeOffset
  3826. nextAvcDts = pts - cts;
  3827. } // PTS is coded on 33bits, and can loop from -2^32 to 2^32
  3828. // PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value
  3829. for (var i = 0; i < nbSamples; i++) {
  3830. var sample = inputSamples[i];
  3831. sample.pts = PTSNormalize(sample.pts - initPTS, nextAvcDts);
  3832. sample.dts = PTSNormalize(sample.dts - initPTS, nextAvcDts);
  3833. if (sample.dts > sample.pts) {
  3834. ptsDtsShift = Math.max(Math.min(ptsDtsShift, sample.pts - sample.dts), -1 * PTS_DTS_SHIFT_TOLERANCE_90KHZ);
  3835. }
  3836. if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {
  3837. sortSamples = true;
  3838. }
  3839. } // sort video samples by DTS then PTS then demux id order
  3840. if (sortSamples) {
  3841. inputSamples.sort(function (a, b) {
  3842. var deltadts = a.dts - b.dts;
  3843. var deltapts = a.pts - b.pts;
  3844. return deltadts || deltapts || a.id - b.id;
  3845. });
  3846. } // Get first/last DTS
  3847. firstDTS = inputSamples[0].dts;
  3848. lastDTS = inputSamples[nbSamples - 1].dts; // on Safari let's signal the same sample duration for all samples
  3849. // sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS
  3850. // set this constant duration as being the avg delta between consecutive DTS.
  3851. var averageSampleDuration = Math.round((lastDTS - firstDTS) / (nbSamples - 1)); // handle broken streams with PTS < DTS, tolerance up 0.2 seconds
  3852. if (ptsDtsShift < 0) {
  3853. if (ptsDtsShift < averageSampleDuration * -2) {
  3854. // Fix for "CNN special report, with CC" in test-streams (including Safari browser)
  3855. // With large PTS < DTS errors such as this, we want to correct CTS while maintaining increasing DTS values
  3856. logger["logger"].warn("PTS < DTS detected in video samples, offsetting DTS from PTS by " + toMsFromMpegTsClock(-averageSampleDuration, true) + " ms");
  3857. var lastDts = ptsDtsShift;
  3858. for (var _i = 0; _i < nbSamples; _i++) {
  3859. inputSamples[_i].dts = lastDts = Math.max(lastDts, inputSamples[_i].pts - averageSampleDuration);
  3860. inputSamples[_i].pts = Math.max(lastDts, inputSamples[_i].pts);
  3861. }
  3862. } else {
  3863. // Fix for "Custom IV with bad PTS DTS" in test-streams
  3864. // With smaller PTS < DTS errors we can simply move all DTS back. This increases CTS without causing buffer gaps or decode errors in Safari
  3865. logger["logger"].warn("PTS < DTS detected in video samples, shifting DTS by " + toMsFromMpegTsClock(ptsDtsShift, true) + " ms to overcome this issue");
  3866. for (var _i2 = 0; _i2 < nbSamples; _i2++) {
  3867. inputSamples[_i2].dts = inputSamples[_i2].dts + ptsDtsShift;
  3868. }
  3869. }
  3870. firstDTS = inputSamples[0].dts;
  3871. lastDTS = inputSamples[nbSamples - 1].dts;
  3872. } // if fragment are contiguous, detect hole/overlapping between fragments
  3873. if (contiguous) {
  3874. // check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)
  3875. var delta = firstDTS - nextAvcDts;
  3876. var foundHole = delta > averageSampleDuration;
  3877. var foundOverlap = delta < -1;
  3878. if (foundHole || foundOverlap) {
  3879. if (foundHole) {
  3880. logger["logger"].warn("AVC: " + toMsFromMpegTsClock(delta, true) + " ms (" + delta + "dts) hole between fragments detected, filling it");
  3881. } else {
  3882. logger["logger"].warn("AVC: " + toMsFromMpegTsClock(-delta, true) + " ms (" + delta + "dts) overlapping between fragments detected");
  3883. }
  3884. firstDTS = nextAvcDts;
  3885. var firstPTS = inputSamples[0].pts - delta;
  3886. inputSamples[0].dts = firstDTS;
  3887. inputSamples[0].pts = firstPTS;
  3888. logger["logger"].log("Video: First PTS/DTS adjusted: " + toMsFromMpegTsClock(firstPTS, true) + "/" + toMsFromMpegTsClock(firstDTS, true) + ", delta: " + toMsFromMpegTsClock(delta, true) + " ms");
  3889. }
  3890. }
  3891. if (chromeVersion && chromeVersion < 75) {
  3892. firstDTS = Math.max(0, firstDTS);
  3893. }
  3894. var nbNalu = 0;
  3895. var naluLen = 0;
  3896. for (var _i3 = 0; _i3 < nbSamples; _i3++) {
  3897. // compute total/avc sample length and nb of NAL units
  3898. var _sample = inputSamples[_i3];
  3899. var units = _sample.units;
  3900. var nbUnits = units.length;
  3901. var sampleLen = 0;
  3902. for (var j = 0; j < nbUnits; j++) {
  3903. sampleLen += units[j].data.length;
  3904. }
  3905. naluLen += sampleLen;
  3906. nbNalu += nbUnits;
  3907. _sample.length = sampleLen; // normalize PTS/DTS
  3908. // ensure sample monotonic DTS
  3909. _sample.dts = Math.max(_sample.dts, firstDTS); // ensure that computed value is greater or equal than sample DTS
  3910. _sample.pts = Math.max(_sample.pts, _sample.dts, 0);
  3911. minPTS = Math.min(_sample.pts, minPTS);
  3912. maxPTS = Math.max(_sample.pts, maxPTS);
  3913. }
  3914. lastDTS = inputSamples[nbSamples - 1].dts;
  3915. /* concatenate the video data and construct the mdat in place
  3916. (need 8 more bytes to fill length and mpdat type) */
  3917. var mdatSize = naluLen + 4 * nbNalu + 8;
  3918. try {
  3919. mdat = new Uint8Array(mdatSize);
  3920. } catch (err) {
  3921. this.observer.trigger(events["default"].ERROR, {
  3922. type: errors["ErrorTypes"].MUX_ERROR,
  3923. details: errors["ErrorDetails"].REMUX_ALLOC_ERROR,
  3924. fatal: false,
  3925. bytes: mdatSize,
  3926. reason: "fail allocating video mdat " + mdatSize
  3927. });
  3928. return;
  3929. }
  3930. var view = new DataView(mdat.buffer);
  3931. view.setUint32(0, mdatSize);
  3932. mdat.set(mp4_generator.types.mdat, 4);
  3933. for (var _i4 = 0; _i4 < nbSamples; _i4++) {
  3934. var avcSample = inputSamples[_i4];
  3935. var avcSampleUnits = avcSample.units;
  3936. var mp4SampleLength = 0;
  3937. var compositionTimeOffset = void 0; // convert NALU bitstream to MP4 format (prepend NALU with size field)
  3938. for (var _j = 0, _nbUnits = avcSampleUnits.length; _j < _nbUnits; _j++) {
  3939. var unit = avcSampleUnits[_j];
  3940. var unitData = unit.data;
  3941. var unitDataLen = unit.data.byteLength;
  3942. view.setUint32(offset, unitDataLen);
  3943. offset += 4;
  3944. mdat.set(unitData, offset);
  3945. offset += unitDataLen;
  3946. mp4SampleLength += 4 + unitDataLen;
  3947. } // expected sample duration is the Decoding Timestamp diff of consecutive samples
  3948. if (_i4 < nbSamples - 1) {
  3949. mp4SampleDuration = inputSamples[_i4 + 1].dts - avcSample.dts;
  3950. } else {
  3951. var config = this.config;
  3952. var lastFrameDuration = avcSample.dts - inputSamples[_i4 > 0 ? _i4 - 1 : _i4].dts;
  3953. if (config.stretchShortVideoTrack) {
  3954. // In some cases, a segment's audio track duration may exceed the video track duration.
  3955. // Since we've already remuxed audio, and we know how long the audio track is, we look to
  3956. // see if the delta to the next segment is longer than maxBufferHole.
  3957. // If so, playback would potentially get stuck, so we artificially inflate
  3958. // the duration of the last frame to minimize any potential gap between segments.
  3959. var maxBufferHole = config.maxBufferHole;
  3960. var gapTolerance = Math.floor(maxBufferHole * timeScale);
  3961. var deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts;
  3962. if (deltaToFrameEnd > gapTolerance) {
  3963. // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video
  3964. // frame overlap. maxBufferHole should be >> lastFrameDuration anyway.
  3965. mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
  3966. if (mp4SampleDuration < 0) {
  3967. mp4SampleDuration = lastFrameDuration;
  3968. }
  3969. logger["logger"].log("It is approximately " + toMsFromMpegTsClock(deltaToFrameEnd, false) + " ms to the next segment; using duration " + toMsFromMpegTsClock(mp4SampleDuration, false) + " ms for the last video frame.");
  3970. } else {
  3971. mp4SampleDuration = lastFrameDuration;
  3972. }
  3973. } else {
  3974. mp4SampleDuration = lastFrameDuration;
  3975. }
  3976. }
  3977. compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts); // console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${avcSample.pts}/${avcSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(avcSample.pts/4294967296).toFixed(3)}');
  3978. outputSamples.push({
  3979. size: mp4SampleLength,
  3980. // constant duration
  3981. duration: mp4SampleDuration,
  3982. cts: compositionTimeOffset,
  3983. flags: {
  3984. isLeading: 0,
  3985. isDependedOn: 0,
  3986. hasRedundancy: 0,
  3987. degradPrio: 0,
  3988. dependsOn: avcSample.key ? 2 : 1,
  3989. isNonSync: avcSample.key ? 0 : 1
  3990. }
  3991. });
  3992. } // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)
  3993. this.nextAvcDts = lastDTS + mp4SampleDuration;
  3994. var dropped = track.dropped;
  3995. track.nbNalu = 0;
  3996. track.dropped = 0;
  3997. if (outputSamples.length && navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
  3998. var flags = outputSamples[0].flags; // chrome workaround, mark first sample as being a Random Access Point to avoid sourcebuffer append issue
  3999. // https://code.google.com/p/chromium/issues/detail?id=229412
  4000. flags.dependsOn = 2;
  4001. flags.isNonSync = 0;
  4002. }
  4003. track.samples = outputSamples;
  4004. moof = mp4_generator.moof(track.sequenceNumber++, firstDTS, track);
  4005. track.samples = [];
  4006. var data = {
  4007. data1: moof,
  4008. data2: mdat,
  4009. startPTS: minPTS / timeScale,
  4010. endPTS: (maxPTS + mp4SampleDuration) / timeScale,
  4011. startDTS: firstDTS / timeScale,
  4012. endDTS: this.nextAvcDts / timeScale,
  4013. type: 'video',
  4014. hasAudio: false,
  4015. hasVideo: true,
  4016. nb: outputSamples.length,
  4017. dropped: dropped
  4018. };
  4019. this.observer.trigger(events["default"].FRAG_PARSING_DATA, data);
  4020. return data;
  4021. };
  4022. _proto.remuxAudio = function remuxAudio(track, timeOffset, contiguous, accurateTimeOffset) {
  4023. var inputTimeScale = track.inputTimeScale;
  4024. var mp4timeScale = track.timescale;
  4025. var scaleFactor = inputTimeScale / mp4timeScale;
  4026. var mp4SampleDuration = track.isAAC ? 1024 : 1152;
  4027. var inputSampleDuration = mp4SampleDuration * scaleFactor;
  4028. var initPTS = this._initPTS;
  4029. var rawMPEG = !track.isAAC && this.typeSupported.mpeg;
  4030. var mp4Sample;
  4031. var fillFrame;
  4032. var mdat;
  4033. var moof;
  4034. var firstPTS;
  4035. var lastPTS;
  4036. var offset = rawMPEG ? 0 : 8;
  4037. var inputSamples = track.samples;
  4038. var outputSamples = [];
  4039. var nextAudioPts = this.nextAudioPts; // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),
  4040. // for sake of clarity:
  4041. // consecutive fragments are frags with
  4042. // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
  4043. // - less than 20 audio frames distance
  4044. // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
  4045. // this helps ensuring audio continuity
  4046. // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame
  4047. contiguous |= inputSamples.length && nextAudioPts && (accurateTimeOffset && Math.abs(timeOffset - nextAudioPts / inputTimeScale) < 0.1 || Math.abs(inputSamples[0].pts - nextAudioPts - initPTS) < 20 * inputSampleDuration); // compute normalized PTS
  4048. inputSamples.forEach(function (sample) {
  4049. sample.pts = sample.dts = PTSNormalize(sample.pts - initPTS, timeOffset * inputTimeScale);
  4050. }); // filter out sample with negative PTS that are not playable anyway
  4051. // if we don't remove these negative samples, they will shift all audio samples forward.
  4052. // leading to audio overlap between current / next fragment
  4053. inputSamples = inputSamples.filter(function (sample) {
  4054. return sample.pts >= 0;
  4055. }); // in case all samples have negative PTS, and have been filtered out, return now
  4056. if (inputSamples.length === 0) {
  4057. return;
  4058. }
  4059. if (!contiguous) {
  4060. if (!accurateTimeOffset) {
  4061. // if frag are mot contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS
  4062. nextAudioPts = inputSamples[0].pts;
  4063. } else {
  4064. // if timeOffset is accurate, let's use it as predicted next audio PTS
  4065. nextAudioPts = Math.max(0, timeOffset * inputTimeScale);
  4066. }
  4067. } // If the audio track is missing samples, the frames seem to get "left-shifted" within the
  4068. // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.
  4069. // In an effort to prevent this from happening, we inject frames here where there are gaps.
  4070. // When possible, we inject a silent frame; when that's not possible, we duplicate the last
  4071. // frame.
  4072. if (track.isAAC) {
  4073. var maxAudioFramesDrift = this.config.maxAudioFramesDrift;
  4074. for (var i = 0, nextPts = nextAudioPts; i < inputSamples.length;) {
  4075. // First, let's see how far off this frame is from where we expect it to be
  4076. var sample = inputSamples[i];
  4077. var pts = sample.pts;
  4078. var delta = pts - nextPts; // If we're overlapping by more than a duration, drop this sample
  4079. if (delta <= -maxAudioFramesDrift * inputSampleDuration) {
  4080. if (contiguous || i > 0) {
  4081. logger["logger"].warn("Dropping 1 audio frame @ " + toMsFromMpegTsClock(nextPts, true) / 1000 + "s due to " + toMsFromMpegTsClock(delta, true) + " ms overlap.");
  4082. inputSamples.splice(i, 1); // Don't touch nextPtsNorm or i
  4083. } else {
  4084. // When changing qualities we can't trust that audio has been appended up to nextAudioPts
  4085. // Warn about the overlap but do not drop samples as that can introduce buffer gaps
  4086. logger["logger"].warn("Audio frame @ " + toMsFromMpegTsClock(pts, true) / 1000 + "s overlaps nextAudioPts by " + toMsFromMpegTsClock(delta, true) + " ms.");
  4087. nextPts = pts + inputSampleDuration;
  4088. i++;
  4089. }
  4090. } // eslint-disable-line brace-style
  4091. // Insert missing frames if:
  4092. // 1: We're more than maxAudioFramesDrift frame away
  4093. // 2: Not more than MAX_SILENT_FRAME_DURATION away
  4094. // 3: currentTime (aka nextPtsNorm) is not 0
  4095. else if (delta >= maxAudioFramesDrift * inputSampleDuration && delta < MAX_SILENT_FRAME_DURATION_90KHZ && nextPts) {
  4096. var missing = Math.round(delta / inputSampleDuration);
  4097. logger["logger"].warn("Injecting " + missing + " audio frames @ " + toMsFromMpegTsClock(nextPts, true) / 1000 + "s due to " + toMsFromMpegTsClock(delta, true) + " ms gap.");
  4098. for (var j = 0; j < missing; j++) {
  4099. var newStamp = Math.max(nextPts, 0);
  4100. fillFrame = aac_helper.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  4101. if (!fillFrame) {
  4102. logger["logger"].log('Unable to get silent frame for given audio codec; duplicating last frame instead.');
  4103. fillFrame = sample.unit.subarray();
  4104. }
  4105. inputSamples.splice(i, 0, {
  4106. unit: fillFrame,
  4107. pts: newStamp,
  4108. dts: newStamp
  4109. });
  4110. nextPts += inputSampleDuration;
  4111. i++;
  4112. } // Adjust sample to next expected pts
  4113. sample.pts = sample.dts = nextPts;
  4114. nextPts += inputSampleDuration;
  4115. i++;
  4116. } else {
  4117. // Otherwise, just adjust pts
  4118. if (Math.abs(delta) > 0.1 * inputSampleDuration) {// logger.log(`Invalid frame delta ${Math.round(delta + inputSampleDuration)} at PTS ${Math.round(pts / 90)} (should be ${Math.round(inputSampleDuration)}).`);
  4119. }
  4120. sample.pts = sample.dts = nextPts;
  4121. nextPts += inputSampleDuration;
  4122. i++;
  4123. }
  4124. }
  4125. } // compute mdat size, as we eventually filtered/added some samples
  4126. var nbSamples = inputSamples.length;
  4127. var mdatSize = 0;
  4128. while (nbSamples--) {
  4129. mdatSize += inputSamples[nbSamples].unit.byteLength;
  4130. }
  4131. for (var _j2 = 0, _nbSamples = inputSamples.length; _j2 < _nbSamples; _j2++) {
  4132. var audioSample = inputSamples[_j2];
  4133. var unit = audioSample.unit;
  4134. var _pts = audioSample.pts; // logger.log(`Audio/PTS:${toMsFromMpegTsClock(pts, true)}`);
  4135. // if not first sample
  4136. if (lastPTS !== undefined && mp4Sample) {
  4137. mp4Sample.duration = Math.round((_pts - lastPTS) / scaleFactor);
  4138. } else {
  4139. var _delta = _pts - nextAudioPts;
  4140. var numMissingFrames = 0; // if fragment are contiguous, detect hole/overlapping between fragments
  4141. // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
  4142. if (contiguous && track.isAAC) {
  4143. // log delta
  4144. if (_delta) {
  4145. if (_delta > 0 && _delta < MAX_SILENT_FRAME_DURATION_90KHZ) {
  4146. // Q: why do we have to round here, shouldn't this always result in an integer if timestamps are correct,
  4147. // and if not, shouldn't we actually Math.ceil() instead?
  4148. numMissingFrames = Math.round((_pts - nextAudioPts) / inputSampleDuration);
  4149. logger["logger"].log(toMsFromMpegTsClock(_delta, true) + " ms hole between AAC samples detected,filling it");
  4150. if (numMissingFrames > 0) {
  4151. fillFrame = aac_helper.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  4152. if (!fillFrame) {
  4153. fillFrame = unit.subarray();
  4154. }
  4155. mdatSize += numMissingFrames * fillFrame.length;
  4156. } // if we have frame overlap, overlapping for more than half a frame duraion
  4157. } else if (_delta < -12) {
  4158. // drop overlapping audio frames... browser will deal with it
  4159. logger["logger"].log("drop overlapping AAC sample, expected/parsed/delta: " + toMsFromMpegTsClock(nextAudioPts, true) + " ms / " + toMsFromMpegTsClock(_pts, true) + " ms / " + toMsFromMpegTsClock(-_delta, true) + " ms");
  4160. mdatSize -= unit.byteLength;
  4161. continue;
  4162. } // set PTS/DTS to expected PTS/DTS
  4163. _pts = nextAudioPts;
  4164. }
  4165. } // remember first PTS of our audioSamples
  4166. firstPTS = _pts;
  4167. if (mdatSize > 0) {
  4168. mdatSize += offset;
  4169. try {
  4170. mdat = new Uint8Array(mdatSize);
  4171. } catch (err) {
  4172. this.observer.trigger(events["default"].ERROR, {
  4173. type: errors["ErrorTypes"].MUX_ERROR,
  4174. details: errors["ErrorDetails"].REMUX_ALLOC_ERROR,
  4175. fatal: false,
  4176. bytes: mdatSize,
  4177. reason: "fail allocating audio mdat " + mdatSize
  4178. });
  4179. return;
  4180. }
  4181. if (!rawMPEG) {
  4182. var view = new DataView(mdat.buffer);
  4183. view.setUint32(0, mdatSize);
  4184. mdat.set(mp4_generator.types.mdat, 4);
  4185. }
  4186. } else {
  4187. // no audio samples
  4188. return;
  4189. }
  4190. for (var _i5 = 0; _i5 < numMissingFrames; _i5++) {
  4191. fillFrame = aac_helper.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  4192. if (!fillFrame) {
  4193. logger["logger"].log('Unable to get silent frame for given audio codec; duplicating this frame instead.');
  4194. fillFrame = unit.subarray();
  4195. }
  4196. mdat.set(fillFrame, offset);
  4197. offset += fillFrame.byteLength;
  4198. mp4Sample = {
  4199. size: fillFrame.byteLength,
  4200. cts: 0,
  4201. duration: 1024,
  4202. flags: {
  4203. isLeading: 0,
  4204. isDependedOn: 0,
  4205. hasRedundancy: 0,
  4206. degradPrio: 0,
  4207. dependsOn: 1
  4208. }
  4209. };
  4210. outputSamples.push(mp4Sample);
  4211. }
  4212. }
  4213. mdat.set(unit, offset);
  4214. var unitLen = unit.byteLength;
  4215. offset += unitLen; // console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${audioSample.pts}/${audioSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(audioSample.pts/4294967296).toFixed(3)}');
  4216. mp4Sample = {
  4217. size: unitLen,
  4218. cts: 0,
  4219. duration: 0,
  4220. flags: {
  4221. isLeading: 0,
  4222. isDependedOn: 0,
  4223. hasRedundancy: 0,
  4224. degradPrio: 0,
  4225. dependsOn: 1
  4226. }
  4227. };
  4228. outputSamples.push(mp4Sample);
  4229. lastPTS = _pts;
  4230. }
  4231. var lastSampleDuration = 0;
  4232. nbSamples = outputSamples.length; // set last sample duration as being identical to previous sample
  4233. if (nbSamples >= 2) {
  4234. lastSampleDuration = outputSamples[nbSamples - 2].duration;
  4235. mp4Sample.duration = lastSampleDuration;
  4236. }
  4237. if (nbSamples) {
  4238. // next audio sample PTS should be equal to last sample PTS + duration
  4239. this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSampleDuration; // logger.log('Audio/PTS/PTSend:' + audioSample.pts.toFixed(0) + '/' + this.nextAacDts.toFixed(0));
  4240. track.samples = outputSamples;
  4241. if (rawMPEG) {
  4242. moof = new Uint8Array();
  4243. } else {
  4244. moof = mp4_generator.moof(track.sequenceNumber++, firstPTS / scaleFactor, track);
  4245. }
  4246. track.samples = [];
  4247. var start = firstPTS / inputTimeScale;
  4248. var end = nextAudioPts / inputTimeScale;
  4249. var audioData = {
  4250. data1: moof,
  4251. data2: mdat,
  4252. startPTS: start,
  4253. endPTS: end,
  4254. startDTS: start,
  4255. endDTS: end,
  4256. type: 'audio',
  4257. hasAudio: true,
  4258. hasVideo: false,
  4259. nb: nbSamples
  4260. };
  4261. this.observer.trigger(events["default"].FRAG_PARSING_DATA, audioData);
  4262. return audioData;
  4263. }
  4264. return null;
  4265. };
  4266. _proto.remuxEmptyAudio = function remuxEmptyAudio(track, timeOffset, contiguous, videoData) {
  4267. var inputTimeScale = track.inputTimeScale;
  4268. var mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
  4269. var scaleFactor = inputTimeScale / mp4timeScale;
  4270. var nextAudioPts = this.nextAudioPts; // sync with video's timestamp
  4271. var startDTS = (nextAudioPts !== undefined ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS;
  4272. var endDTS = videoData.endDTS * inputTimeScale + this._initDTS; // one sample's duration value
  4273. var sampleDuration = 1024;
  4274. var frameDuration = scaleFactor * sampleDuration; // samples count of this segment's duration
  4275. var nbSamples = Math.ceil((endDTS - startDTS) / frameDuration); // silent frame
  4276. var silentFrame = aac_helper.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  4277. logger["logger"].warn('remux empty Audio'); // Can't remux if we can't generate a silent frame...
  4278. if (!silentFrame) {
  4279. logger["logger"].trace('Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!');
  4280. return;
  4281. }
  4282. var samples = [];
  4283. for (var i = 0; i < nbSamples; i++) {
  4284. var stamp = startDTS + i * frameDuration;
  4285. samples.push({
  4286. unit: silentFrame,
  4287. pts: stamp,
  4288. dts: stamp
  4289. });
  4290. }
  4291. track.samples = samples;
  4292. this.remuxAudio(track, timeOffset, contiguous);
  4293. };
  4294. _proto.remuxID3 = function remuxID3(track, timeOffset) {
  4295. var length = track.samples.length;
  4296. if (!length) {
  4297. return;
  4298. }
  4299. var inputTimeScale = track.inputTimeScale;
  4300. var initPTS = this._initPTS;
  4301. var initDTS = this._initDTS; // consume samples
  4302. for (var index = 0; index < length; index++) {
  4303. var sample = track.samples[index]; // setting id3 pts, dts to relative time
  4304. // using this._initPTS and this._initDTS to calculate relative time
  4305. sample.pts = PTSNormalize(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale;
  4306. sample.dts = PTSNormalize(sample.dts - initDTS, timeOffset * inputTimeScale) / inputTimeScale;
  4307. }
  4308. this.observer.trigger(events["default"].FRAG_PARSING_METADATA, {
  4309. samples: track.samples
  4310. });
  4311. track.samples = [];
  4312. };
  4313. _proto.remuxText = function remuxText(track, timeOffset) {
  4314. var length = track.samples.length;
  4315. var inputTimeScale = track.inputTimeScale;
  4316. var initPTS = this._initPTS; // consume samples
  4317. if (length) {
  4318. for (var index = 0; index < length; index++) {
  4319. var sample = track.samples[index]; // setting text pts, dts to relative time
  4320. // using this._initPTS and this._initDTS to calculate relative time
  4321. sample.pts = PTSNormalize(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale;
  4322. }
  4323. track.samples.sort(function (a, b) {
  4324. return a.pts - b.pts;
  4325. });
  4326. this.observer.trigger(events["default"].FRAG_PARSING_USERDATA, {
  4327. samples: track.samples
  4328. });
  4329. }
  4330. track.samples = [];
  4331. };
  4332. return MP4Remuxer;
  4333. }();
  4334. function PTSNormalize(value, reference) {
  4335. var offset;
  4336. if (reference === undefined) {
  4337. return value;
  4338. }
  4339. if (reference < value) {
  4340. // - 2^33
  4341. offset = -8589934592;
  4342. } else {
  4343. // + 2^33
  4344. offset = 8589934592;
  4345. }
  4346. /* PTS is 33bit (from 0 to 2^33 -1)
  4347. if diff between value and reference is bigger than half of the amplitude (2^32) then it means that
  4348. PTS looping occured. fill the gap */
  4349. while (Math.abs(value - reference) > 4294967296) {
  4350. value += offset;
  4351. }
  4352. return value;
  4353. }
  4354. /* harmony default export */ var mp4_remuxer = (mp4_remuxer_MP4Remuxer);
  4355. // CONCATENATED MODULE: ./src/remux/passthrough-remuxer.js
  4356. /**
  4357. * passthrough remuxer
  4358. */
  4359. var passthrough_remuxer_PassThroughRemuxer = /*#__PURE__*/function () {
  4360. function PassThroughRemuxer(observer) {
  4361. this.observer = observer;
  4362. }
  4363. var _proto = PassThroughRemuxer.prototype;
  4364. _proto.destroy = function destroy() {};
  4365. _proto.resetTimeStamp = function resetTimeStamp() {};
  4366. _proto.resetInitSegment = function resetInitSegment() {};
  4367. _proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset, rawData) {
  4368. var observer = this.observer;
  4369. var streamType = '';
  4370. if (audioTrack) {
  4371. streamType += 'audio';
  4372. }
  4373. if (videoTrack) {
  4374. streamType += 'video';
  4375. }
  4376. observer.trigger(events["default"].FRAG_PARSING_DATA, {
  4377. data1: rawData,
  4378. startPTS: timeOffset,
  4379. startDTS: timeOffset,
  4380. type: streamType,
  4381. hasAudio: !!audioTrack,
  4382. hasVideo: !!videoTrack,
  4383. nb: 1,
  4384. dropped: 0
  4385. }); // notify end of parsing
  4386. observer.trigger(events["default"].FRAG_PARSED);
  4387. };
  4388. return PassThroughRemuxer;
  4389. }();
  4390. /* harmony default export */ var passthrough_remuxer = (passthrough_remuxer_PassThroughRemuxer);
  4391. // CONCATENATED MODULE: ./src/demux/demuxer-inline.js
  4392. /**
  4393. *
  4394. * inline demuxer: probe fragments and instantiate
  4395. * appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...)
  4396. *
  4397. */
  4398. // see https://stackoverflow.com/a/11237259/589493
  4399. var global = Object(get_self_scope["getSelfScope"])(); // safeguard for code that might run both on worker and main thread
  4400. var now; // performance.now() not available on WebWorker, at least on Safari Desktop
  4401. try {
  4402. now = global.performance.now.bind(global.performance);
  4403. } catch (err) {
  4404. logger["logger"].debug('Unable to use Performance API on this environment');
  4405. now = global.Date.now;
  4406. }
  4407. var demuxer_inline_DemuxerInline = /*#__PURE__*/function () {
  4408. function DemuxerInline(observer, typeSupported, config, vendor) {
  4409. this.observer = observer;
  4410. this.typeSupported = typeSupported;
  4411. this.config = config;
  4412. this.vendor = vendor;
  4413. }
  4414. var _proto = DemuxerInline.prototype;
  4415. _proto.destroy = function destroy() {
  4416. var demuxer = this.demuxer;
  4417. if (demuxer) {
  4418. demuxer.destroy();
  4419. }
  4420. };
  4421. _proto.push = function push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {
  4422. var _this = this;
  4423. if (data.byteLength > 0 && decryptdata != null && decryptdata.key != null && decryptdata.method === 'AES-128') {
  4424. var decrypter = this.decrypter;
  4425. if (decrypter == null) {
  4426. decrypter = this.decrypter = new crypt_decrypter["default"](this.observer, this.config);
  4427. }
  4428. var startTime = now();
  4429. decrypter.decrypt(data, decryptdata.key.buffer, decryptdata.iv.buffer, function (decryptedData) {
  4430. var endTime = now();
  4431. _this.observer.trigger(events["default"].FRAG_DECRYPTED, {
  4432. stats: {
  4433. tstart: startTime,
  4434. tdecrypt: endTime
  4435. }
  4436. });
  4437. _this.pushDecrypted(new Uint8Array(decryptedData), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
  4438. });
  4439. } else {
  4440. this.pushDecrypted(new Uint8Array(data), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
  4441. }
  4442. };
  4443. _proto.pushDecrypted = function pushDecrypted(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {
  4444. var demuxer = this.demuxer;
  4445. var remuxer = this.remuxer;
  4446. if (!demuxer || // in case of continuity change, or track switch
  4447. // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)
  4448. discontinuity || trackSwitch) {
  4449. var observer = this.observer;
  4450. var typeSupported = this.typeSupported;
  4451. var config = this.config; // probing order is TS/MP4/AAC/MP3
  4452. var muxConfig = [{
  4453. demux: tsdemuxer,
  4454. remux: mp4_remuxer
  4455. }, {
  4456. demux: mp4demuxer["default"],
  4457. remux: passthrough_remuxer
  4458. }, {
  4459. demux: aacdemuxer,
  4460. remux: mp4_remuxer
  4461. }, {
  4462. demux: mp3demuxer,
  4463. remux: mp4_remuxer
  4464. }]; // probe for content type
  4465. var mux;
  4466. for (var i = 0, len = muxConfig.length; i < len; i++) {
  4467. mux = muxConfig[i];
  4468. if (mux.demux.probe(data)) {
  4469. break;
  4470. }
  4471. }
  4472. if (!mux) {
  4473. observer.trigger(events["default"].ERROR, {
  4474. type: errors["ErrorTypes"].MEDIA_ERROR,
  4475. details: errors["ErrorDetails"].FRAG_PARSING_ERROR,
  4476. fatal: true,
  4477. reason: 'no demux matching with content found'
  4478. });
  4479. return;
  4480. } // so let's check that current remuxer and demuxer are still valid
  4481. if (!remuxer || !(remuxer instanceof mux.remux)) {
  4482. remuxer = new mux.remux(observer, config, typeSupported, this.vendor);
  4483. }
  4484. if (!demuxer || !(demuxer instanceof mux.demux)) {
  4485. demuxer = new mux.demux(observer, remuxer, config, typeSupported);
  4486. this.probe = mux.demux.probe;
  4487. }
  4488. this.demuxer = demuxer;
  4489. this.remuxer = remuxer;
  4490. }
  4491. if (discontinuity || trackSwitch) {
  4492. demuxer.resetInitSegment(initSegment, audioCodec, videoCodec, duration);
  4493. remuxer.resetInitSegment();
  4494. }
  4495. if (discontinuity) {
  4496. demuxer.resetTimeStamp(defaultInitPTS);
  4497. remuxer.resetTimeStamp(defaultInitPTS);
  4498. }
  4499. if (typeof demuxer.setDecryptData === 'function') {
  4500. demuxer.setDecryptData(decryptdata);
  4501. }
  4502. demuxer.append(data, timeOffset, contiguous, accurateTimeOffset);
  4503. };
  4504. return DemuxerInline;
  4505. }();
  4506. /* harmony default export */ var demuxer_inline = __webpack_exports__["default"] = (demuxer_inline_DemuxerInline);
  4507. /***/ }),
  4508. /***/ "./src/demux/demuxer-worker.js":
  4509. /*!*************************************!*\
  4510. !*** ./src/demux/demuxer-worker.js ***!
  4511. \*************************************/
  4512. /*! exports provided: default */
  4513. /*! ModuleConcatenation bailout: Module is referenced from these modules with unsupported syntax: ./src/demux/demuxer.js (referenced with require.resolve) */
  4514. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  4515. "use strict";
  4516. __webpack_require__.r(__webpack_exports__);
  4517. /* harmony import */ var _demux_demuxer_inline__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../demux/demuxer-inline */ "./src/demux/demuxer-inline.js");
  4518. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.js");
  4519. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  4520. /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/eventemitter3/index.js");
  4521. /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_3__);
  4522. /* demuxer web worker.
  4523. * - listen to worker message, and trigger DemuxerInline upon reception of Fragments.
  4524. * - 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.
  4525. */
  4526. var DemuxerWorker = function DemuxerWorker(self) {
  4527. // observer setup
  4528. var observer = new eventemitter3__WEBPACK_IMPORTED_MODULE_3__["EventEmitter"]();
  4529. observer.trigger = function trigger(event) {
  4530. for (var _len = arguments.length, data = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4531. data[_key - 1] = arguments[_key];
  4532. }
  4533. observer.emit.apply(observer, [event, event].concat(data));
  4534. };
  4535. observer.off = function off(event) {
  4536. for (var _len2 = arguments.length, data = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  4537. data[_key2 - 1] = arguments[_key2];
  4538. }
  4539. observer.removeListener.apply(observer, [event].concat(data));
  4540. };
  4541. var forwardMessage = function forwardMessage(ev, data) {
  4542. self.postMessage({
  4543. event: ev,
  4544. data: data
  4545. });
  4546. };
  4547. self.addEventListener('message', function (ev) {
  4548. var data = ev.data; // console.log('demuxer cmd:' + data.cmd);
  4549. switch (data.cmd) {
  4550. case 'init':
  4551. var config = JSON.parse(data.config);
  4552. self.demuxer = new _demux_demuxer_inline__WEBPACK_IMPORTED_MODULE_0__["default"](observer, data.typeSupported, config, data.vendor);
  4553. Object(_utils_logger__WEBPACK_IMPORTED_MODULE_2__["enableLogs"])(config.debug); // signal end of worker init
  4554. forwardMessage('init', null);
  4555. break;
  4556. case 'demux':
  4557. 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);
  4558. break;
  4559. default:
  4560. break;
  4561. }
  4562. }); // forward events to main thread
  4563. observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["default"].FRAG_DECRYPTED, forwardMessage);
  4564. observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["default"].FRAG_PARSING_INIT_SEGMENT, forwardMessage);
  4565. observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["default"].FRAG_PARSED, forwardMessage);
  4566. observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["default"].ERROR, forwardMessage);
  4567. observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["default"].FRAG_PARSING_METADATA, forwardMessage);
  4568. observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["default"].FRAG_PARSING_USERDATA, forwardMessage);
  4569. observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["default"].INIT_PTS_FOUND, forwardMessage); // special case for FRAG_PARSING_DATA: pass data1/data2 as transferable object (no copy)
  4570. observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["default"].FRAG_PARSING_DATA, function (ev, data) {
  4571. var transferable = [];
  4572. var message = {
  4573. event: ev,
  4574. data: data
  4575. };
  4576. if (data.data1) {
  4577. message.data1 = data.data1.buffer;
  4578. transferable.push(data.data1.buffer);
  4579. delete data.data1;
  4580. }
  4581. if (data.data2) {
  4582. message.data2 = data.data2.buffer;
  4583. transferable.push(data.data2.buffer);
  4584. delete data.data2;
  4585. }
  4586. self.postMessage(message, transferable);
  4587. });
  4588. };
  4589. /* harmony default export */ __webpack_exports__["default"] = (DemuxerWorker);
  4590. /***/ }),
  4591. /***/ "./src/demux/id3.js":
  4592. /*!**************************!*\
  4593. !*** ./src/demux/id3.js ***!
  4594. \**************************/
  4595. /*! exports provided: default, utf8ArrayToStr */
  4596. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  4597. "use strict";
  4598. __webpack_require__.r(__webpack_exports__);
  4599. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "utf8ArrayToStr", function() { return utf8ArrayToStr; });
  4600. /* harmony import */ var _utils_get_self_scope__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/get-self-scope */ "./src/utils/get-self-scope.js");
  4601. /**
  4602. * ID3 parser
  4603. */
  4604. var ID3 = /*#__PURE__*/function () {
  4605. function ID3() {}
  4606. /**
  4607. * Returns true if an ID3 header can be found at offset in data
  4608. * @param {Uint8Array} data - The data to search in
  4609. * @param {number} offset - The offset at which to start searching
  4610. * @return {boolean} - True if an ID3 header is found
  4611. */
  4612. ID3.isHeader = function isHeader(data, offset) {
  4613. /*
  4614. * http://id3.org/id3v2.3.0
  4615. * [0] = 'I'
  4616. * [1] = 'D'
  4617. * [2] = '3'
  4618. * [3,4] = {Version}
  4619. * [5] = {Flags}
  4620. * [6-9] = {ID3 Size}
  4621. *
  4622. * An ID3v2 tag can be detected with the following pattern:
  4623. * $49 44 33 yy yy xx zz zz zz zz
  4624. * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80
  4625. */
  4626. if (offset + 10 <= data.length) {
  4627. // look for 'ID3' identifier
  4628. if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) {
  4629. // check version is within range
  4630. if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) {
  4631. // check size is within range
  4632. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  4633. return true;
  4634. }
  4635. }
  4636. }
  4637. }
  4638. return false;
  4639. }
  4640. /**
  4641. * Returns true if an ID3 footer can be found at offset in data
  4642. * @param {Uint8Array} data - The data to search in
  4643. * @param {number} offset - The offset at which to start searching
  4644. * @return {boolean} - True if an ID3 footer is found
  4645. */
  4646. ;
  4647. ID3.isFooter = function isFooter(data, offset) {
  4648. /*
  4649. * The footer is a copy of the header, but with a different identifier
  4650. */
  4651. if (offset + 10 <= data.length) {
  4652. // look for '3DI' identifier
  4653. if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) {
  4654. // check version is within range
  4655. if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) {
  4656. // check size is within range
  4657. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  4658. return true;
  4659. }
  4660. }
  4661. }
  4662. }
  4663. return false;
  4664. }
  4665. /**
  4666. * Returns any adjacent ID3 tags found in data starting at offset, as one block of data
  4667. * @param {Uint8Array} data - The data to search in
  4668. * @param {number} offset - The offset at which to start searching
  4669. * @return {Uint8Array} - The block of data containing any ID3 tags found
  4670. */
  4671. ;
  4672. ID3.getID3Data = function getID3Data(data, offset) {
  4673. var front = offset;
  4674. var length = 0;
  4675. while (ID3.isHeader(data, offset)) {
  4676. // ID3 header is 10 bytes
  4677. length += 10;
  4678. var size = ID3._readSize(data, offset + 6);
  4679. length += size;
  4680. if (ID3.isFooter(data, offset + 10)) {
  4681. // ID3 footer is 10 bytes
  4682. length += 10;
  4683. }
  4684. offset += length;
  4685. }
  4686. if (length > 0) {
  4687. return data.subarray(front, front + length);
  4688. }
  4689. return undefined;
  4690. };
  4691. ID3._readSize = function _readSize(data, offset) {
  4692. var size = 0;
  4693. size = (data[offset] & 0x7f) << 21;
  4694. size |= (data[offset + 1] & 0x7f) << 14;
  4695. size |= (data[offset + 2] & 0x7f) << 7;
  4696. size |= data[offset + 3] & 0x7f;
  4697. return size;
  4698. }
  4699. /**
  4700. * Searches for the Elementary Stream timestamp found in the ID3 data chunk
  4701. * @param {Uint8Array} data - Block of data containing one or more ID3 tags
  4702. * @return {number} - The timestamp
  4703. */
  4704. ;
  4705. ID3.getTimeStamp = function getTimeStamp(data) {
  4706. var frames = ID3.getID3Frames(data);
  4707. for (var i = 0; i < frames.length; i++) {
  4708. var frame = frames[i];
  4709. if (ID3.isTimeStampFrame(frame)) {
  4710. return ID3._readTimeStamp(frame);
  4711. }
  4712. }
  4713. return undefined;
  4714. }
  4715. /**
  4716. * Returns true if the ID3 frame is an Elementary Stream timestamp frame
  4717. * @param {ID3 frame} frame
  4718. */
  4719. ;
  4720. ID3.isTimeStampFrame = function isTimeStampFrame(frame) {
  4721. return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp';
  4722. };
  4723. ID3._getFrameData = function _getFrameData(data) {
  4724. /*
  4725. Frame ID $xx xx xx xx (four characters)
  4726. Size $xx xx xx xx
  4727. Flags $xx xx
  4728. */
  4729. var type = String.fromCharCode(data[0], data[1], data[2], data[3]);
  4730. var size = ID3._readSize(data, 4); // skip frame id, size, and flags
  4731. var offset = 10;
  4732. return {
  4733. type: type,
  4734. size: size,
  4735. data: data.subarray(offset, offset + size)
  4736. };
  4737. }
  4738. /**
  4739. * Returns an array of ID3 frames found in all the ID3 tags in the id3Data
  4740. * @param {Uint8Array} id3Data - The ID3 data containing one or more ID3 tags
  4741. * @return {ID3 frame[]} - Array of ID3 frame objects
  4742. */
  4743. ;
  4744. ID3.getID3Frames = function getID3Frames(id3Data) {
  4745. var offset = 0;
  4746. var frames = [];
  4747. while (ID3.isHeader(id3Data, offset)) {
  4748. var size = ID3._readSize(id3Data, offset + 6); // skip past ID3 header
  4749. offset += 10;
  4750. var end = offset + size; // loop through frames in the ID3 tag
  4751. while (offset + 8 < end) {
  4752. var frameData = ID3._getFrameData(id3Data.subarray(offset));
  4753. var frame = ID3._decodeFrame(frameData);
  4754. if (frame) {
  4755. frames.push(frame);
  4756. } // skip frame header and frame data
  4757. offset += frameData.size + 10;
  4758. }
  4759. if (ID3.isFooter(id3Data, offset)) {
  4760. offset += 10;
  4761. }
  4762. }
  4763. return frames;
  4764. };
  4765. ID3._decodeFrame = function _decodeFrame(frame) {
  4766. if (frame.type === 'PRIV') {
  4767. return ID3._decodePrivFrame(frame);
  4768. } else if (frame.type[0] === 'W') {
  4769. return ID3._decodeURLFrame(frame);
  4770. }
  4771. return ID3._decodeTextFrame(frame);
  4772. };
  4773. ID3._readTimeStamp = function _readTimeStamp(timeStampFrame) {
  4774. if (timeStampFrame.data.byteLength === 8) {
  4775. var data = new Uint8Array(timeStampFrame.data); // timestamp is 33 bit expressed as a big-endian eight-octet number,
  4776. // with the upper 31 bits set to zero.
  4777. var pts33Bit = data[3] & 0x1;
  4778. var timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];
  4779. timestamp /= 45;
  4780. if (pts33Bit) {
  4781. timestamp += 47721858.84;
  4782. } // 2^32 / 90
  4783. return Math.round(timestamp);
  4784. }
  4785. return undefined;
  4786. };
  4787. ID3._decodePrivFrame = function _decodePrivFrame(frame) {
  4788. /*
  4789. Format: <text string>\0<binary data>
  4790. */
  4791. if (frame.size < 2) {
  4792. return undefined;
  4793. }
  4794. var owner = ID3._utf8ArrayToStr(frame.data, true);
  4795. var privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
  4796. return {
  4797. key: frame.type,
  4798. info: owner,
  4799. data: privateData.buffer
  4800. };
  4801. };
  4802. ID3._decodeTextFrame = function _decodeTextFrame(frame) {
  4803. if (frame.size < 2) {
  4804. return undefined;
  4805. }
  4806. if (frame.type === 'TXXX') {
  4807. /*
  4808. Format:
  4809. [0] = {Text Encoding}
  4810. [1-?] = {Description}\0{Value}
  4811. */
  4812. var index = 1;
  4813. var description = ID3._utf8ArrayToStr(frame.data.subarray(index), true);
  4814. index += description.length + 1;
  4815. var value = ID3._utf8ArrayToStr(frame.data.subarray(index));
  4816. return {
  4817. key: frame.type,
  4818. info: description,
  4819. data: value
  4820. };
  4821. } else {
  4822. /*
  4823. Format:
  4824. [0] = {Text Encoding}
  4825. [1-?] = {Value}
  4826. */
  4827. var text = ID3._utf8ArrayToStr(frame.data.subarray(1));
  4828. return {
  4829. key: frame.type,
  4830. data: text
  4831. };
  4832. }
  4833. };
  4834. ID3._decodeURLFrame = function _decodeURLFrame(frame) {
  4835. if (frame.type === 'WXXX') {
  4836. /*
  4837. Format:
  4838. [0] = {Text Encoding}
  4839. [1-?] = {Description}\0{URL}
  4840. */
  4841. if (frame.size < 2) {
  4842. return undefined;
  4843. }
  4844. var index = 1;
  4845. var description = ID3._utf8ArrayToStr(frame.data.subarray(index), true);
  4846. index += description.length + 1;
  4847. var value = ID3._utf8ArrayToStr(frame.data.subarray(index));
  4848. return {
  4849. key: frame.type,
  4850. info: description,
  4851. data: value
  4852. };
  4853. } else {
  4854. /*
  4855. Format:
  4856. [0-?] = {URL}
  4857. */
  4858. var url = ID3._utf8ArrayToStr(frame.data);
  4859. return {
  4860. key: frame.type,
  4861. data: url
  4862. };
  4863. }
  4864. } // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197
  4865. // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
  4866. /* utf.js - UTF-8 <=> UTF-16 convertion
  4867. *
  4868. * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
  4869. * Version: 1.0
  4870. * LastModified: Dec 25 1999
  4871. * This library is free. You can redistribute it and/or modify it.
  4872. */
  4873. ;
  4874. ID3._utf8ArrayToStr = function _utf8ArrayToStr(array, exitOnNull) {
  4875. if (exitOnNull === void 0) {
  4876. exitOnNull = false;
  4877. }
  4878. var decoder = getTextDecoder();
  4879. if (decoder) {
  4880. var decoded = decoder.decode(array);
  4881. if (exitOnNull) {
  4882. // grab up to the first null
  4883. var idx = decoded.indexOf('\0');
  4884. return idx !== -1 ? decoded.substring(0, idx) : decoded;
  4885. } // remove any null characters
  4886. return decoded.replace(/\0/g, '');
  4887. }
  4888. var len = array.length;
  4889. var c;
  4890. var char2;
  4891. var char3;
  4892. var out = '';
  4893. var i = 0;
  4894. while (i < len) {
  4895. c = array[i++];
  4896. if (c === 0x00 && exitOnNull) {
  4897. return out;
  4898. } else if (c === 0x00 || c === 0x03) {
  4899. // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it
  4900. continue;
  4901. }
  4902. switch (c >> 4) {
  4903. case 0:
  4904. case 1:
  4905. case 2:
  4906. case 3:
  4907. case 4:
  4908. case 5:
  4909. case 6:
  4910. case 7:
  4911. // 0xxxxxxx
  4912. out += String.fromCharCode(c);
  4913. break;
  4914. case 12:
  4915. case 13:
  4916. // 110x xxxx 10xx xxxx
  4917. char2 = array[i++];
  4918. out += String.fromCharCode((c & 0x1F) << 6 | char2 & 0x3F);
  4919. break;
  4920. case 14:
  4921. // 1110 xxxx 10xx xxxx 10xx xxxx
  4922. char2 = array[i++];
  4923. char3 = array[i++];
  4924. out += String.fromCharCode((c & 0x0F) << 12 | (char2 & 0x3F) << 6 | (char3 & 0x3F) << 0);
  4925. break;
  4926. default:
  4927. }
  4928. }
  4929. return out;
  4930. };
  4931. return ID3;
  4932. }();
  4933. var decoder;
  4934. function getTextDecoder() {
  4935. var global = Object(_utils_get_self_scope__WEBPACK_IMPORTED_MODULE_0__["getSelfScope"])(); // safeguard for code that might run both on worker and main thread
  4936. if (!decoder && typeof global.TextDecoder !== 'undefined') {
  4937. decoder = new global.TextDecoder('utf-8');
  4938. }
  4939. return decoder;
  4940. }
  4941. var utf8ArrayToStr = ID3._utf8ArrayToStr;
  4942. /* harmony default export */ __webpack_exports__["default"] = (ID3);
  4943. /***/ }),
  4944. /***/ "./src/demux/mp4demuxer.js":
  4945. /*!*********************************!*\
  4946. !*** ./src/demux/mp4demuxer.js ***!
  4947. \*********************************/
  4948. /*! exports provided: default */
  4949. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  4950. "use strict";
  4951. __webpack_require__.r(__webpack_exports__);
  4952. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  4953. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.js");
  4954. /**
  4955. * MP4 demuxer
  4956. */
  4957. var UINT32_MAX = Math.pow(2, 32) - 1;
  4958. var MP4Demuxer = /*#__PURE__*/function () {
  4959. function MP4Demuxer(observer, remuxer) {
  4960. this.observer = observer;
  4961. this.remuxer = remuxer;
  4962. }
  4963. var _proto = MP4Demuxer.prototype;
  4964. _proto.resetTimeStamp = function resetTimeStamp(initPTS) {
  4965. this.initPTS = initPTS;
  4966. };
  4967. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
  4968. // jshint unused:false
  4969. if (initSegment && initSegment.byteLength) {
  4970. var initData = this.initData = MP4Demuxer.parseInitSegment(initSegment); // default audio codec if nothing specified
  4971. // TODO : extract that from initsegment
  4972. if (audioCodec == null) {
  4973. audioCodec = 'mp4a.40.5';
  4974. }
  4975. if (videoCodec == null) {
  4976. videoCodec = 'avc1.42e01e';
  4977. }
  4978. var tracks = {};
  4979. if (initData.audio && initData.video) {
  4980. tracks.audiovideo = {
  4981. container: 'video/mp4',
  4982. codec: audioCodec + ',' + videoCodec,
  4983. initSegment: duration ? initSegment : null
  4984. };
  4985. } else {
  4986. if (initData.audio) {
  4987. tracks.audio = {
  4988. container: 'audio/mp4',
  4989. codec: audioCodec,
  4990. initSegment: duration ? initSegment : null
  4991. };
  4992. }
  4993. if (initData.video) {
  4994. tracks.video = {
  4995. container: 'video/mp4',
  4996. codec: videoCodec,
  4997. initSegment: duration ? initSegment : null
  4998. };
  4999. }
  5000. }
  5001. this.observer.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["default"].FRAG_PARSING_INIT_SEGMENT, {
  5002. tracks: tracks
  5003. });
  5004. } else {
  5005. if (audioCodec) {
  5006. this.audioCodec = audioCodec;
  5007. }
  5008. if (videoCodec) {
  5009. this.videoCodec = videoCodec;
  5010. }
  5011. }
  5012. };
  5013. MP4Demuxer.probe = function probe(data) {
  5014. // ensure we find a moof box in the first 16 kB
  5015. return MP4Demuxer.findBox({
  5016. data: data,
  5017. start: 0,
  5018. end: Math.min(data.length, 16384)
  5019. }, ['moof']).length > 0;
  5020. };
  5021. MP4Demuxer.bin2str = function bin2str(buffer) {
  5022. return String.fromCharCode.apply(null, buffer);
  5023. };
  5024. MP4Demuxer.readUint16 = function readUint16(buffer, offset) {
  5025. if (buffer.data) {
  5026. offset += buffer.start;
  5027. buffer = buffer.data;
  5028. }
  5029. var val = buffer[offset] << 8 | buffer[offset + 1];
  5030. return val < 0 ? 65536 + val : val;
  5031. };
  5032. MP4Demuxer.readUint32 = function readUint32(buffer, offset) {
  5033. if (buffer.data) {
  5034. offset += buffer.start;
  5035. buffer = buffer.data;
  5036. }
  5037. var val = buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];
  5038. return val < 0 ? 4294967296 + val : val;
  5039. };
  5040. MP4Demuxer.writeUint32 = function writeUint32(buffer, offset, value) {
  5041. if (buffer.data) {
  5042. offset += buffer.start;
  5043. buffer = buffer.data;
  5044. }
  5045. buffer[offset] = value >> 24;
  5046. buffer[offset + 1] = value >> 16 & 0xff;
  5047. buffer[offset + 2] = value >> 8 & 0xff;
  5048. buffer[offset + 3] = value & 0xff;
  5049. } // Find the data for a box specified by its path
  5050. ;
  5051. MP4Demuxer.findBox = function findBox(data, path) {
  5052. var results = [],
  5053. i,
  5054. size,
  5055. type,
  5056. end,
  5057. subresults,
  5058. start,
  5059. endbox;
  5060. if (data.data) {
  5061. start = data.start;
  5062. end = data.end;
  5063. data = data.data;
  5064. } else {
  5065. start = 0;
  5066. end = data.byteLength;
  5067. }
  5068. if (!path.length) {
  5069. // short-circuit the search for empty paths
  5070. return null;
  5071. }
  5072. for (i = start; i < end;) {
  5073. size = MP4Demuxer.readUint32(data, i);
  5074. type = MP4Demuxer.bin2str(data.subarray(i + 4, i + 8));
  5075. endbox = size > 1 ? i + size : end;
  5076. if (type === path[0]) {
  5077. if (path.length === 1) {
  5078. // this is the end of the path and we've found the box we were
  5079. // looking for
  5080. results.push({
  5081. data: data,
  5082. start: i + 8,
  5083. end: endbox
  5084. });
  5085. } else {
  5086. // recursively search for the next box along the path
  5087. subresults = MP4Demuxer.findBox({
  5088. data: data,
  5089. start: i + 8,
  5090. end: endbox
  5091. }, path.slice(1));
  5092. if (subresults.length) {
  5093. results = results.concat(subresults);
  5094. }
  5095. }
  5096. }
  5097. i = endbox;
  5098. } // we've finished searching all of data
  5099. return results;
  5100. };
  5101. MP4Demuxer.parseSegmentIndex = function parseSegmentIndex(initSegment) {
  5102. var moov = MP4Demuxer.findBox(initSegment, ['moov'])[0];
  5103. var moovEndOffset = moov ? moov.end : null; // we need this in case we need to chop of garbage of the end of current data
  5104. var index = 0;
  5105. var sidx = MP4Demuxer.findBox(initSegment, ['sidx']);
  5106. var references;
  5107. if (!sidx || !sidx[0]) {
  5108. return null;
  5109. }
  5110. references = [];
  5111. sidx = sidx[0];
  5112. var version = sidx.data[0]; // set initial offset, we skip the reference ID (not needed)
  5113. index = version === 0 ? 8 : 16;
  5114. var timescale = MP4Demuxer.readUint32(sidx, index);
  5115. index += 4; // TODO: parse earliestPresentationTime and firstOffset
  5116. // usually zero in our case
  5117. var earliestPresentationTime = 0;
  5118. var firstOffset = 0;
  5119. if (version === 0) {
  5120. index += 8;
  5121. } else {
  5122. index += 16;
  5123. } // skip reserved
  5124. index += 2;
  5125. var startByte = sidx.end + firstOffset;
  5126. var referencesCount = MP4Demuxer.readUint16(sidx, index);
  5127. index += 2;
  5128. for (var i = 0; i < referencesCount; i++) {
  5129. var referenceIndex = index;
  5130. var referenceInfo = MP4Demuxer.readUint32(sidx, referenceIndex);
  5131. referenceIndex += 4;
  5132. var referenceSize = referenceInfo & 0x7FFFFFFF;
  5133. var referenceType = (referenceInfo & 0x80000000) >>> 31;
  5134. if (referenceType === 1) {
  5135. console.warn('SIDX has hierarchical references (not supported)');
  5136. return;
  5137. }
  5138. var subsegmentDuration = MP4Demuxer.readUint32(sidx, referenceIndex);
  5139. referenceIndex += 4;
  5140. references.push({
  5141. referenceSize: referenceSize,
  5142. subsegmentDuration: subsegmentDuration,
  5143. // unscaled
  5144. info: {
  5145. duration: subsegmentDuration / timescale,
  5146. start: startByte,
  5147. end: startByte + referenceSize - 1
  5148. }
  5149. });
  5150. startByte += referenceSize; // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits
  5151. // for |sapDelta|.
  5152. referenceIndex += 4; // skip to next ref
  5153. index = referenceIndex;
  5154. }
  5155. return {
  5156. earliestPresentationTime: earliestPresentationTime,
  5157. timescale: timescale,
  5158. version: version,
  5159. referencesCount: referencesCount,
  5160. references: references,
  5161. moovEndOffset: moovEndOffset
  5162. };
  5163. }
  5164. /**
  5165. * Parses an MP4 initialization segment and extracts stream type and
  5166. * timescale values for any declared tracks. Timescale values indicate the
  5167. * number of clock ticks per second to assume for time-based values
  5168. * elsewhere in the MP4.
  5169. *
  5170. * To determine the start time of an MP4, you need two pieces of
  5171. * information: the timescale unit and the earliest base media decode
  5172. * time. Multiple timescales can be specified within an MP4 but the
  5173. * base media decode time is always expressed in the timescale from
  5174. * the media header box for the track:
  5175. * ```
  5176. * moov > trak > mdia > mdhd.timescale
  5177. * moov > trak > mdia > hdlr
  5178. * ```
  5179. * @param init {Uint8Array} the bytes of the init segment
  5180. * @return {object} a hash of track type to timescale values or null if
  5181. * the init segment is malformed.
  5182. */
  5183. ;
  5184. MP4Demuxer.parseInitSegment = function parseInitSegment(initSegment) {
  5185. var result = [];
  5186. var traks = MP4Demuxer.findBox(initSegment, ['moov', 'trak']);
  5187. traks.forEach(function (trak) {
  5188. var tkhd = MP4Demuxer.findBox(trak, ['tkhd'])[0];
  5189. if (tkhd) {
  5190. var version = tkhd.data[tkhd.start];
  5191. var index = version === 0 ? 12 : 20;
  5192. var trackId = MP4Demuxer.readUint32(tkhd, index);
  5193. var mdhd = MP4Demuxer.findBox(trak, ['mdia', 'mdhd'])[0];
  5194. if (mdhd) {
  5195. version = mdhd.data[mdhd.start];
  5196. index = version === 0 ? 12 : 20;
  5197. var timescale = MP4Demuxer.readUint32(mdhd, index);
  5198. var hdlr = MP4Demuxer.findBox(trak, ['mdia', 'hdlr'])[0];
  5199. if (hdlr) {
  5200. var hdlrType = MP4Demuxer.bin2str(hdlr.data.subarray(hdlr.start + 8, hdlr.start + 12));
  5201. var type = {
  5202. 'soun': 'audio',
  5203. 'vide': 'video'
  5204. }[hdlrType];
  5205. if (type) {
  5206. // extract codec info. TODO : parse codec details to be able to build MIME type
  5207. var codecBox = MP4Demuxer.findBox(trak, ['mdia', 'minf', 'stbl', 'stsd']);
  5208. if (codecBox.length) {
  5209. codecBox = codecBox[0];
  5210. var codecType = MP4Demuxer.bin2str(codecBox.data.subarray(codecBox.start + 12, codecBox.start + 16));
  5211. _utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log("MP4Demuxer:" + type + ":" + codecType + " found");
  5212. }
  5213. result[trackId] = {
  5214. timescale: timescale,
  5215. type: type
  5216. };
  5217. result[type] = {
  5218. timescale: timescale,
  5219. id: trackId
  5220. };
  5221. }
  5222. }
  5223. }
  5224. }
  5225. });
  5226. return result;
  5227. }
  5228. /**
  5229. * Determine the base media decode start time, in seconds, for an MP4
  5230. * fragment. If multiple fragments are specified, the earliest time is
  5231. * returned.
  5232. *
  5233. * The base media decode time can be parsed from track fragment
  5234. * metadata:
  5235. * ```
  5236. * moof > traf > tfdt.baseMediaDecodeTime
  5237. * ```
  5238. * It requires the timescale value from the mdhd to interpret.
  5239. *
  5240. * @param timescale {object} a hash of track ids to timescale values.
  5241. * @return {number} the earliest base media decode start time for the
  5242. * fragment, in seconds
  5243. */
  5244. ;
  5245. MP4Demuxer.getStartDTS = function getStartDTS(initData, fragment) {
  5246. var trafs, baseTimes, result; // we need info from two childrend of each track fragment box
  5247. trafs = MP4Demuxer.findBox(fragment, ['moof', 'traf']); // determine the start times for each track
  5248. baseTimes = [].concat.apply([], trafs.map(function (traf) {
  5249. return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) {
  5250. var id, scale, baseTime; // get the track id from the tfhd
  5251. id = MP4Demuxer.readUint32(tfhd, 4); // assume a 90kHz clock if no timescale was specified
  5252. scale = initData[id].timescale || 90e3; // get the base media decode time from the tfdt
  5253. baseTime = MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) {
  5254. var version, result;
  5255. version = tfdt.data[tfdt.start];
  5256. result = MP4Demuxer.readUint32(tfdt, 4);
  5257. if (version === 1) {
  5258. result *= Math.pow(2, 32);
  5259. result += MP4Demuxer.readUint32(tfdt, 8);
  5260. }
  5261. return result;
  5262. })[0]; // convert base time to seconds
  5263. return baseTime / scale;
  5264. });
  5265. })); // return the minimum
  5266. result = Math.min.apply(null, baseTimes);
  5267. return isFinite(result) ? result : 0;
  5268. };
  5269. MP4Demuxer.offsetStartDTS = function offsetStartDTS(initData, fragment, timeOffset) {
  5270. MP4Demuxer.findBox(fragment, ['moof', 'traf']).map(function (traf) {
  5271. return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) {
  5272. // get the track id from the tfhd
  5273. var id = MP4Demuxer.readUint32(tfhd, 4); // assume a 90kHz clock if no timescale was specified
  5274. var timescale = initData[id].timescale || 90e3; // get the base media decode time from the tfdt
  5275. MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) {
  5276. var version = tfdt.data[tfdt.start];
  5277. var baseMediaDecodeTime = MP4Demuxer.readUint32(tfdt, 4);
  5278. if (version === 0) {
  5279. MP4Demuxer.writeUint32(tfdt, 4, baseMediaDecodeTime - timeOffset * timescale);
  5280. } else {
  5281. baseMediaDecodeTime *= Math.pow(2, 32);
  5282. baseMediaDecodeTime += MP4Demuxer.readUint32(tfdt, 8);
  5283. baseMediaDecodeTime -= timeOffset * timescale;
  5284. baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);
  5285. var upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
  5286. var lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
  5287. MP4Demuxer.writeUint32(tfdt, 4, upper);
  5288. MP4Demuxer.writeUint32(tfdt, 8, lower);
  5289. }
  5290. });
  5291. });
  5292. });
  5293. } // feed incoming data to the front of the parsing pipeline
  5294. ;
  5295. _proto.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {
  5296. var initData = this.initData;
  5297. if (!initData) {
  5298. this.resetInitSegment(data, this.audioCodec, this.videoCodec, false);
  5299. initData = this.initData;
  5300. }
  5301. var startDTS,
  5302. initPTS = this.initPTS;
  5303. if (initPTS === undefined) {
  5304. var _startDTS = MP4Demuxer.getStartDTS(initData, data);
  5305. this.initPTS = initPTS = _startDTS - timeOffset;
  5306. this.observer.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["default"].INIT_PTS_FOUND, {
  5307. initPTS: initPTS
  5308. });
  5309. }
  5310. MP4Demuxer.offsetStartDTS(initData, data, initPTS);
  5311. startDTS = MP4Demuxer.getStartDTS(initData, data);
  5312. this.remuxer.remux(initData.audio, initData.video, null, null, startDTS, contiguous, accurateTimeOffset, data);
  5313. };
  5314. _proto.destroy = function destroy() {};
  5315. return MP4Demuxer;
  5316. }();
  5317. /* harmony default export */ __webpack_exports__["default"] = (MP4Demuxer);
  5318. /***/ }),
  5319. /***/ "./src/errors.ts":
  5320. /*!***********************!*\
  5321. !*** ./src/errors.ts ***!
  5322. \***********************/
  5323. /*! exports provided: ErrorTypes, ErrorDetails */
  5324. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  5325. "use strict";
  5326. __webpack_require__.r(__webpack_exports__);
  5327. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorTypes", function() { return ErrorTypes; });
  5328. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorDetails", function() { return ErrorDetails; });
  5329. var ErrorTypes;
  5330. /**
  5331. * @enum {ErrorDetails}
  5332. * @typedef {string} ErrorDetail
  5333. */
  5334. (function (ErrorTypes) {
  5335. ErrorTypes["NETWORK_ERROR"] = "networkError";
  5336. ErrorTypes["MEDIA_ERROR"] = "mediaError";
  5337. ErrorTypes["KEY_SYSTEM_ERROR"] = "keySystemError";
  5338. ErrorTypes["MUX_ERROR"] = "muxError";
  5339. ErrorTypes["OTHER_ERROR"] = "otherError";
  5340. })(ErrorTypes || (ErrorTypes = {}));
  5341. var ErrorDetails;
  5342. (function (ErrorDetails) {
  5343. ErrorDetails["KEY_SYSTEM_NO_KEYS"] = "keySystemNoKeys";
  5344. ErrorDetails["KEY_SYSTEM_NO_ACCESS"] = "keySystemNoAccess";
  5345. ErrorDetails["KEY_SYSTEM_NO_SESSION"] = "keySystemNoSession";
  5346. ErrorDetails["KEY_SYSTEM_LICENSE_REQUEST_FAILED"] = "keySystemLicenseRequestFailed";
  5347. ErrorDetails["KEY_SYSTEM_NO_INIT_DATA"] = "keySystemNoInitData";
  5348. ErrorDetails["MANIFEST_LOAD_ERROR"] = "manifestLoadError";
  5349. ErrorDetails["MANIFEST_LOAD_TIMEOUT"] = "manifestLoadTimeOut";
  5350. ErrorDetails["MANIFEST_PARSING_ERROR"] = "manifestParsingError";
  5351. ErrorDetails["MANIFEST_INCOMPATIBLE_CODECS_ERROR"] = "manifestIncompatibleCodecsError";
  5352. ErrorDetails["LEVEL_EMPTY_ERROR"] = "levelEmptyError";
  5353. ErrorDetails["LEVEL_LOAD_ERROR"] = "levelLoadError";
  5354. ErrorDetails["LEVEL_LOAD_TIMEOUT"] = "levelLoadTimeOut";
  5355. ErrorDetails["LEVEL_SWITCH_ERROR"] = "levelSwitchError";
  5356. ErrorDetails["AUDIO_TRACK_LOAD_ERROR"] = "audioTrackLoadError";
  5357. ErrorDetails["AUDIO_TRACK_LOAD_TIMEOUT"] = "audioTrackLoadTimeOut";
  5358. ErrorDetails["FRAG_LOAD_ERROR"] = "fragLoadError";
  5359. ErrorDetails["FRAG_LOAD_TIMEOUT"] = "fragLoadTimeOut";
  5360. ErrorDetails["FRAG_DECRYPT_ERROR"] = "fragDecryptError";
  5361. ErrorDetails["FRAG_PARSING_ERROR"] = "fragParsingError";
  5362. ErrorDetails["REMUX_ALLOC_ERROR"] = "remuxAllocError";
  5363. ErrorDetails["KEY_LOAD_ERROR"] = "keyLoadError";
  5364. ErrorDetails["KEY_LOAD_TIMEOUT"] = "keyLoadTimeOut";
  5365. ErrorDetails["BUFFER_ADD_CODEC_ERROR"] = "bufferAddCodecError";
  5366. ErrorDetails["BUFFER_APPEND_ERROR"] = "bufferAppendError";
  5367. ErrorDetails["BUFFER_APPENDING_ERROR"] = "bufferAppendingError";
  5368. ErrorDetails["BUFFER_STALLED_ERROR"] = "bufferStalledError";
  5369. ErrorDetails["BUFFER_FULL_ERROR"] = "bufferFullError";
  5370. ErrorDetails["BUFFER_SEEK_OVER_HOLE"] = "bufferSeekOverHole";
  5371. ErrorDetails["BUFFER_NUDGE_ON_STALL"] = "bufferNudgeOnStall";
  5372. ErrorDetails["INTERNAL_EXCEPTION"] = "internalException";
  5373. })(ErrorDetails || (ErrorDetails = {}));
  5374. /***/ }),
  5375. /***/ "./src/events.js":
  5376. /*!***********************!*\
  5377. !*** ./src/events.js ***!
  5378. \***********************/
  5379. /*! exports provided: default */
  5380. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  5381. "use strict";
  5382. __webpack_require__.r(__webpack_exports__);
  5383. /**
  5384. * @readonly
  5385. * @enum {string}
  5386. */
  5387. var HlsEvents = {
  5388. // fired before MediaSource is attaching to media element - data: { media }
  5389. MEDIA_ATTACHING: 'hlsMediaAttaching',
  5390. // fired when MediaSource has been succesfully attached to media element - data: { }
  5391. MEDIA_ATTACHED: 'hlsMediaAttached',
  5392. // fired before detaching MediaSource from media element - data: { }
  5393. MEDIA_DETACHING: 'hlsMediaDetaching',
  5394. // fired when MediaSource has been detached from media element - data: { }
  5395. MEDIA_DETACHED: 'hlsMediaDetached',
  5396. // fired when we buffer is going to be reset - data: { }
  5397. BUFFER_RESET: 'hlsBufferReset',
  5398. // fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }}
  5399. BUFFER_CODECS: 'hlsBufferCodecs',
  5400. // fired when sourcebuffers have been created - data: { tracks : tracks }
  5401. BUFFER_CREATED: 'hlsBufferCreated',
  5402. // fired when we append a segment to the buffer - data: { segment: segment object }
  5403. BUFFER_APPENDING: 'hlsBufferAppending',
  5404. // 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}
  5405. BUFFER_APPENDED: 'hlsBufferAppended',
  5406. // fired when the stream is finished and we want to notify the media buffer that there will be no more data - data: { }
  5407. BUFFER_EOS: 'hlsBufferEos',
  5408. // fired when the media buffer should be flushed - data { startOffset, endOffset }
  5409. BUFFER_FLUSHING: 'hlsBufferFlushing',
  5410. // fired when the media buffer has been flushed - data: { }
  5411. BUFFER_FLUSHED: 'hlsBufferFlushed',
  5412. // fired to signal that a manifest loading starts - data: { url : manifestURL}
  5413. MANIFEST_LOADING: 'hlsManifestLoading',
  5414. // fired after manifest has been loaded - data: { levels : [available quality levels], audioTracks : [ available audio tracks], url : manifestURL, stats : { trequest, tfirst, tload, mtime}}
  5415. MANIFEST_LOADED: 'hlsManifestLoaded',
  5416. // fired after manifest has been parsed - data: { levels : [available quality levels], firstLevel : index of first quality level appearing in Manifest}
  5417. MANIFEST_PARSED: 'hlsManifestParsed',
  5418. // fired when a level switch is requested - data: { level : id of new level }
  5419. LEVEL_SWITCHING: 'hlsLevelSwitching',
  5420. // fired when a level switch is effective - data: { level : id of new level }
  5421. LEVEL_SWITCHED: 'hlsLevelSwitched',
  5422. // fired when a level playlist loading starts - data: { url : level URL, level : id of level being loaded}
  5423. LEVEL_LOADING: 'hlsLevelLoading',
  5424. // fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : { trequest, tfirst, tload, mtime} }
  5425. LEVEL_LOADED: 'hlsLevelLoaded',
  5426. // 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 }
  5427. LEVEL_UPDATED: 'hlsLevelUpdated',
  5428. // 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 }
  5429. LEVEL_PTS_UPDATED: 'hlsLevelPtsUpdated',
  5430. // fired to notify that levels have changed after removing a level - data: { levels : [available quality levels] }
  5431. LEVELS_UPDATED: 'hlsLevelsUpdated',
  5432. // fired to notify that audio track lists has been updated - data: { audioTracks : audioTracks }
  5433. AUDIO_TRACKS_UPDATED: 'hlsAudioTracksUpdated',
  5434. // fired when an audio track switching is requested - data: { id : audio track id }
  5435. AUDIO_TRACK_SWITCHING: 'hlsAudioTrackSwitching',
  5436. // fired when an audio track switch actually occurs - data: { id : audio track id }
  5437. AUDIO_TRACK_SWITCHED: 'hlsAudioTrackSwitched',
  5438. // fired when an audio track loading starts - data: { url : audio track URL, id : audio track id }
  5439. AUDIO_TRACK_LOADING: 'hlsAudioTrackLoading',
  5440. // fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : { trequest, tfirst, tload, mtime } }
  5441. AUDIO_TRACK_LOADED: 'hlsAudioTrackLoaded',
  5442. // fired to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks }
  5443. SUBTITLE_TRACKS_UPDATED: 'hlsSubtitleTracksUpdated',
  5444. // fired when an subtitle track switch occurs - data: { id : subtitle track id }
  5445. SUBTITLE_TRACK_SWITCH: 'hlsSubtitleTrackSwitch',
  5446. // fired when a subtitle track loading starts - data: { url : subtitle track URL, id : subtitle track id }
  5447. SUBTITLE_TRACK_LOADING: 'hlsSubtitleTrackLoading',
  5448. // fired when a subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : { trequest, tfirst, tload, mtime } }
  5449. SUBTITLE_TRACK_LOADED: 'hlsSubtitleTrackLoaded',
  5450. // fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag }
  5451. SUBTITLE_FRAG_PROCESSED: 'hlsSubtitleFragProcessed',
  5452. // fired when a set of VTTCues to be managed externally has been parsed - data: { type: string, track: string, cues: [ VTTCue ] }
  5453. CUES_PARSED: 'hlsCuesParsed',
  5454. // fired when a text track to be managed externally is found - data: { tracks: [ { label: string, kind: string, default: boolean } ] }
  5455. NON_NATIVE_TEXT_TRACKS_FOUND: 'hlsNonNativeTextTracksFound',
  5456. // fired when the first timestamp is found - data: { id : demuxer id, initPTS: initPTS, frag : fragment object }
  5457. INIT_PTS_FOUND: 'hlsInitPtsFound',
  5458. // fired when a fragment loading starts - data: { frag : fragment object }
  5459. FRAG_LOADING: 'hlsFragLoading',
  5460. // fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded } }
  5461. FRAG_LOAD_PROGRESS: 'hlsFragLoadProgress',
  5462. // Identifier for fragment load aborting for emergency switch down - data: { frag : fragment object }
  5463. FRAG_LOAD_EMERGENCY_ABORTED: 'hlsFragLoadEmergencyAborted',
  5464. // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length } }
  5465. FRAG_LOADED: 'hlsFragLoaded',
  5466. // fired when a fragment has finished decrypting - data: { id : demuxer id, frag: fragment object, payload : fragment payload, stats : { tstart, tdecrypt } }
  5467. FRAG_DECRYPTED: 'hlsFragDecrypted',
  5468. // 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 }
  5469. FRAG_PARSING_INIT_SEGMENT: 'hlsFragParsingInitSegment',
  5470. // fired when parsing sei text is completed - data: { id : demuxer id, frag: fragment object, samples : [ sei samples pes ] }
  5471. FRAG_PARSING_USERDATA: 'hlsFragParsingUserdata',
  5472. // fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] }
  5473. FRAG_PARSING_METADATA: 'hlsFragParsingMetadata',
  5474. // 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}
  5475. FRAG_PARSING_DATA: 'hlsFragParsingData',
  5476. // fired when fragment parsing is completed - data: { id : demuxer id, frag: fragment object }
  5477. FRAG_PARSED: 'hlsFragParsed',
  5478. // 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 } }
  5479. FRAG_BUFFERED: 'hlsFragBuffered',
  5480. // fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object }
  5481. FRAG_CHANGED: 'hlsFragChanged',
  5482. // Identifier for a FPS drop event - data: { curentDropped, currentDecoded, totalDroppedFrames }
  5483. FPS_DROP: 'hlsFpsDrop',
  5484. // triggered when FPS drop triggers auto level capping - data: { level, droppedlevel }
  5485. FPS_DROP_LEVEL_CAPPING: 'hlsFpsDropLevelCapping',
  5486. // 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 }
  5487. ERROR: 'hlsError',
  5488. // 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: { }
  5489. DESTROYING: 'hlsDestroying',
  5490. // fired when a decrypt key loading starts - data: { frag : fragment object }
  5491. KEY_LOADING: 'hlsKeyLoading',
  5492. // fired when a decrypt key loading is completed - data: { frag : fragment object, payload : key payload, stats : { trequest, tfirst, tload, length } }
  5493. KEY_LOADED: 'hlsKeyLoaded',
  5494. // fired upon stream controller state transitions - data: { previousState, nextState }
  5495. STREAM_STATE_TRANSITION: 'hlsStreamStateTransition',
  5496. // fired when the live back buffer is reached defined by the liveBackBufferLength config option - data : { bufferEnd: number }
  5497. LIVE_BACK_BUFFER_REACHED: 'hlsLiveBackBufferReached'
  5498. };
  5499. /* harmony default export */ __webpack_exports__["default"] = (HlsEvents);
  5500. /***/ }),
  5501. /***/ "./src/hls.ts":
  5502. /*!*********************************!*\
  5503. !*** ./src/hls.ts + 50 modules ***!
  5504. \*********************************/
  5505. /*! exports provided: default */
  5506. /*! ModuleConcatenation bailout: Cannot concat with ./src/crypt/decrypter.js because of ./src/demux/demuxer-worker.js */
  5507. /*! ModuleConcatenation bailout: Cannot concat with ./src/demux/demuxer-inline.js because of ./src/demux/demuxer-worker.js */
  5508. /*! ModuleConcatenation bailout: Cannot concat with ./src/demux/id3.js because of ./src/demux/demuxer-worker.js */
  5509. /*! ModuleConcatenation bailout: Cannot concat with ./src/demux/mp4demuxer.js because of ./src/demux/demuxer-worker.js */
  5510. /*! ModuleConcatenation bailout: Cannot concat with ./src/errors.ts because of ./src/demux/demuxer-worker.js */
  5511. /*! ModuleConcatenation bailout: Cannot concat with ./src/events.js because of ./src/demux/demuxer-worker.js */
  5512. /*! ModuleConcatenation bailout: Cannot concat with ./src/polyfills/number.js because of ./src/demux/demuxer-worker.js */
  5513. /*! ModuleConcatenation bailout: Cannot concat with ./src/utils/get-self-scope.js because of ./src/demux/demuxer-worker.js */
  5514. /*! ModuleConcatenation bailout: Cannot concat with ./src/utils/logger.js because of ./src/demux/demuxer-worker.js */
  5515. /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/eventemitter3/index.js (<- Module is not an ECMAScript module) */
  5516. /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/url-toolkit/src/url-toolkit.js (<- Module is not an ECMAScript module) */
  5517. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  5518. "use strict";
  5519. // ESM COMPAT FLAG
  5520. __webpack_require__.r(__webpack_exports__);
  5521. // EXPORTS
  5522. __webpack_require__.d(__webpack_exports__, "default", function() { return /* binding */ hls_Hls; });
  5523. // NAMESPACE OBJECT: ./src/utils/cues.ts
  5524. var cues_namespaceObject = {};
  5525. __webpack_require__.r(cues_namespaceObject);
  5526. __webpack_require__.d(cues_namespaceObject, "newCue", function() { return newCue; });
  5527. // EXTERNAL MODULE: ./node_modules/url-toolkit/src/url-toolkit.js
  5528. var url_toolkit = __webpack_require__("./node_modules/url-toolkit/src/url-toolkit.js");
  5529. // EXTERNAL MODULE: ./src/errors.ts
  5530. var errors = __webpack_require__("./src/errors.ts");
  5531. // EXTERNAL MODULE: ./src/polyfills/number.js
  5532. var number = __webpack_require__("./src/polyfills/number.js");
  5533. // EXTERNAL MODULE: ./src/events.js
  5534. var events = __webpack_require__("./src/events.js");
  5535. // EXTERNAL MODULE: ./src/utils/logger.js
  5536. var logger = __webpack_require__("./src/utils/logger.js");
  5537. // CONCATENATED MODULE: ./src/event-handler.ts
  5538. /*
  5539. *
  5540. * All objects in the event handling chain should inherit from this class
  5541. *
  5542. */
  5543. var FORBIDDEN_EVENT_NAMES = {
  5544. 'hlsEventGeneric': true,
  5545. 'hlsHandlerDestroying': true,
  5546. 'hlsHandlerDestroyed': true
  5547. };
  5548. var event_handler_EventHandler = /*#__PURE__*/function () {
  5549. function EventHandler(hls) {
  5550. this.hls = void 0;
  5551. this.handledEvents = void 0;
  5552. this.useGenericHandler = void 0;
  5553. this.hls = hls;
  5554. this.onEvent = this.onEvent.bind(this);
  5555. for (var _len = arguments.length, events = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  5556. events[_key - 1] = arguments[_key];
  5557. }
  5558. this.handledEvents = events;
  5559. this.useGenericHandler = true;
  5560. this.registerListeners();
  5561. }
  5562. var _proto = EventHandler.prototype;
  5563. _proto.destroy = function destroy() {
  5564. this.onHandlerDestroying();
  5565. this.unregisterListeners();
  5566. this.onHandlerDestroyed();
  5567. };
  5568. _proto.onHandlerDestroying = function onHandlerDestroying() {};
  5569. _proto.onHandlerDestroyed = function onHandlerDestroyed() {};
  5570. _proto.isEventHandler = function isEventHandler() {
  5571. return typeof this.handledEvents === 'object' && this.handledEvents.length && typeof this.onEvent === 'function';
  5572. };
  5573. _proto.registerListeners = function registerListeners() {
  5574. if (this.isEventHandler()) {
  5575. this.handledEvents.forEach(function (event) {
  5576. if (FORBIDDEN_EVENT_NAMES[event]) {
  5577. throw new Error('Forbidden event-name: ' + event);
  5578. }
  5579. this.hls.on(event, this.onEvent);
  5580. }, this);
  5581. }
  5582. };
  5583. _proto.unregisterListeners = function unregisterListeners() {
  5584. if (this.isEventHandler()) {
  5585. this.handledEvents.forEach(function (event) {
  5586. this.hls.off(event, this.onEvent);
  5587. }, this);
  5588. }
  5589. }
  5590. /**
  5591. * arguments: event (string), data (any)
  5592. */
  5593. ;
  5594. _proto.onEvent = function onEvent(event, data) {
  5595. this.onEventGeneric(event, data);
  5596. };
  5597. _proto.onEventGeneric = function onEventGeneric(event, data) {
  5598. var eventToFunction = function eventToFunction(event, data) {
  5599. var funcName = 'on' + event.replace('hls', '');
  5600. if (typeof this[funcName] !== 'function') {
  5601. throw new Error("Event " + event + " has no generic handler in this " + this.constructor.name + " class (tried " + funcName + ")");
  5602. }
  5603. return this[funcName].bind(this, data);
  5604. };
  5605. try {
  5606. eventToFunction.call(this, event, data).call();
  5607. } catch (err) {
  5608. logger["logger"].error("An internal error happened while handling event " + event + ". Error message: \"" + err.message + "\". Here is a stacktrace:", err);
  5609. this.hls.trigger(events["default"].ERROR, {
  5610. type: errors["ErrorTypes"].OTHER_ERROR,
  5611. details: errors["ErrorDetails"].INTERNAL_EXCEPTION,
  5612. fatal: false,
  5613. event: event,
  5614. err: err
  5615. });
  5616. }
  5617. };
  5618. return EventHandler;
  5619. }();
  5620. /* harmony default export */ var event_handler = (event_handler_EventHandler);
  5621. // CONCATENATED MODULE: ./src/types/loader.ts
  5622. /**
  5623. * `type` property values for this loaders' context object
  5624. * @enum
  5625. *
  5626. */
  5627. var PlaylistContextType;
  5628. /**
  5629. * @enum {string}
  5630. */
  5631. (function (PlaylistContextType) {
  5632. PlaylistContextType["MANIFEST"] = "manifest";
  5633. PlaylistContextType["LEVEL"] = "level";
  5634. PlaylistContextType["AUDIO_TRACK"] = "audioTrack";
  5635. PlaylistContextType["SUBTITLE_TRACK"] = "subtitleTrack";
  5636. })(PlaylistContextType || (PlaylistContextType = {}));
  5637. var PlaylistLevelType;
  5638. (function (PlaylistLevelType) {
  5639. PlaylistLevelType["MAIN"] = "main";
  5640. PlaylistLevelType["AUDIO"] = "audio";
  5641. PlaylistLevelType["SUBTITLE"] = "subtitle";
  5642. })(PlaylistLevelType || (PlaylistLevelType = {}));
  5643. // EXTERNAL MODULE: ./src/demux/mp4demuxer.js
  5644. var mp4demuxer = __webpack_require__("./src/demux/mp4demuxer.js");
  5645. // CONCATENATED MODULE: ./src/loader/level-key.ts
  5646. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  5647. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  5648. var level_key_LevelKey = /*#__PURE__*/function () {
  5649. function LevelKey(baseURI, relativeURI) {
  5650. this._uri = null;
  5651. this.baseuri = void 0;
  5652. this.reluri = void 0;
  5653. this.method = null;
  5654. this.key = null;
  5655. this.iv = null;
  5656. this.baseuri = baseURI;
  5657. this.reluri = relativeURI;
  5658. }
  5659. _createClass(LevelKey, [{
  5660. key: "uri",
  5661. get: function get() {
  5662. if (!this._uri && this.reluri) {
  5663. this._uri = Object(url_toolkit["buildAbsoluteURL"])(this.baseuri, this.reluri, {
  5664. alwaysNormalize: true
  5665. });
  5666. }
  5667. return this._uri;
  5668. }
  5669. }]);
  5670. return LevelKey;
  5671. }();
  5672. // CONCATENATED MODULE: ./src/loader/fragment.ts
  5673. function fragment_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  5674. function fragment_createClass(Constructor, protoProps, staticProps) { if (protoProps) fragment_defineProperties(Constructor.prototype, protoProps); if (staticProps) fragment_defineProperties(Constructor, staticProps); return Constructor; }
  5675. var ElementaryStreamTypes;
  5676. (function (ElementaryStreamTypes) {
  5677. ElementaryStreamTypes["AUDIO"] = "audio";
  5678. ElementaryStreamTypes["VIDEO"] = "video";
  5679. })(ElementaryStreamTypes || (ElementaryStreamTypes = {}));
  5680. var fragment_Fragment = /*#__PURE__*/function () {
  5681. function Fragment() {
  5682. var _this$_elementaryStre;
  5683. this._url = null;
  5684. this._byteRange = null;
  5685. this._decryptdata = null;
  5686. this._elementaryStreams = (_this$_elementaryStre = {}, _this$_elementaryStre[ElementaryStreamTypes.AUDIO] = false, _this$_elementaryStre[ElementaryStreamTypes.VIDEO] = false, _this$_elementaryStre);
  5687. this.deltaPTS = 0;
  5688. this.rawProgramDateTime = null;
  5689. this.programDateTime = null;
  5690. this.title = null;
  5691. this.tagList = [];
  5692. this.cc = void 0;
  5693. this.type = void 0;
  5694. this.relurl = void 0;
  5695. this.baseurl = void 0;
  5696. this.duration = void 0;
  5697. this.start = void 0;
  5698. this.sn = 0;
  5699. this.urlId = 0;
  5700. this.level = 0;
  5701. this.levelkey = void 0;
  5702. this.loader = void 0;
  5703. }
  5704. var _proto = Fragment.prototype;
  5705. // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array
  5706. _proto.setByteRange = function setByteRange(value, previousFrag) {
  5707. var params = value.split('@', 2);
  5708. var byteRange = [];
  5709. if (params.length === 1) {
  5710. byteRange[0] = previousFrag ? previousFrag.byteRangeEndOffset : 0;
  5711. } else {
  5712. byteRange[0] = parseInt(params[1]);
  5713. }
  5714. byteRange[1] = parseInt(params[0]) + byteRange[0];
  5715. this._byteRange = byteRange;
  5716. };
  5717. /**
  5718. * @param {ElementaryStreamTypes} type
  5719. */
  5720. _proto.addElementaryStream = function addElementaryStream(type) {
  5721. this._elementaryStreams[type] = true;
  5722. }
  5723. /**
  5724. * @param {ElementaryStreamTypes} type
  5725. */
  5726. ;
  5727. _proto.hasElementaryStream = function hasElementaryStream(type) {
  5728. return this._elementaryStreams[type] === true;
  5729. }
  5730. /**
  5731. * Utility method for parseLevelPlaylist to create an initialization vector for a given segment
  5732. * @param {number} segmentNumber - segment number to generate IV with
  5733. * @returns {Uint8Array}
  5734. */
  5735. ;
  5736. _proto.createInitializationVector = function createInitializationVector(segmentNumber) {
  5737. var uint8View = new Uint8Array(16);
  5738. for (var i = 12; i < 16; i++) {
  5739. uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff;
  5740. }
  5741. return uint8View;
  5742. }
  5743. /**
  5744. * Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data
  5745. * @param levelkey - a playlist's encryption info
  5746. * @param segmentNumber - the fragment's segment number
  5747. * @returns {LevelKey} - an object to be applied as a fragment's decryptdata
  5748. */
  5749. ;
  5750. _proto.setDecryptDataFromLevelKey = function setDecryptDataFromLevelKey(levelkey, segmentNumber) {
  5751. var decryptdata = levelkey;
  5752. if ((levelkey === null || levelkey === void 0 ? void 0 : levelkey.method) && levelkey.uri && !levelkey.iv) {
  5753. decryptdata = new level_key_LevelKey(levelkey.baseuri, levelkey.reluri);
  5754. decryptdata.method = levelkey.method;
  5755. decryptdata.iv = this.createInitializationVector(segmentNumber);
  5756. }
  5757. return decryptdata;
  5758. };
  5759. fragment_createClass(Fragment, [{
  5760. key: "url",
  5761. get: function get() {
  5762. if (!this._url && this.relurl) {
  5763. this._url = Object(url_toolkit["buildAbsoluteURL"])(this.baseurl, this.relurl, {
  5764. alwaysNormalize: true
  5765. });
  5766. }
  5767. return this._url;
  5768. },
  5769. set: function set(value) {
  5770. this._url = value;
  5771. }
  5772. }, {
  5773. key: "byteRange",
  5774. get: function get() {
  5775. if (!this._byteRange) {
  5776. return [];
  5777. }
  5778. return this._byteRange;
  5779. }
  5780. /**
  5781. * @type {number}
  5782. */
  5783. }, {
  5784. key: "byteRangeStartOffset",
  5785. get: function get() {
  5786. return this.byteRange[0];
  5787. }
  5788. }, {
  5789. key: "byteRangeEndOffset",
  5790. get: function get() {
  5791. return this.byteRange[1];
  5792. }
  5793. }, {
  5794. key: "decryptdata",
  5795. get: function get() {
  5796. if (!this.levelkey && !this._decryptdata) {
  5797. return null;
  5798. }
  5799. if (!this._decryptdata && this.levelkey) {
  5800. var sn = this.sn;
  5801. if (typeof sn !== 'number') {
  5802. // We are fetching decryption data for a initialization segment
  5803. // If the segment was encrypted with AES-128
  5804. // It must have an IV defined. We cannot substitute the Segment Number in.
  5805. if (this.levelkey && this.levelkey.method === 'AES-128' && !this.levelkey.iv) {
  5806. logger["logger"].warn("missing IV for initialization segment with method=\"" + this.levelkey.method + "\" - compliance issue");
  5807. }
  5808. /*
  5809. Be converted to a Number.
  5810. 'initSegment' will become NaN.
  5811. NaN, which when converted through ToInt32() -> +0.
  5812. ---
  5813. Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation.
  5814. */
  5815. sn = 0;
  5816. }
  5817. this._decryptdata = this.setDecryptDataFromLevelKey(this.levelkey, sn);
  5818. }
  5819. return this._decryptdata;
  5820. }
  5821. }, {
  5822. key: "endProgramDateTime",
  5823. get: function get() {
  5824. if (this.programDateTime === null) {
  5825. return null;
  5826. }
  5827. if (!Object(number["isFiniteNumber"])(this.programDateTime)) {
  5828. return null;
  5829. }
  5830. var duration = !Object(number["isFiniteNumber"])(this.duration) ? 0 : this.duration;
  5831. return this.programDateTime + duration * 1000;
  5832. }
  5833. }, {
  5834. key: "encrypted",
  5835. get: function get() {
  5836. return !!(this.decryptdata && this.decryptdata.uri !== null && this.decryptdata.key === null);
  5837. }
  5838. }]);
  5839. return Fragment;
  5840. }();
  5841. // CONCATENATED MODULE: ./src/loader/level.js
  5842. function level_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  5843. function level_createClass(Constructor, protoProps, staticProps) { if (protoProps) level_defineProperties(Constructor.prototype, protoProps); if (staticProps) level_defineProperties(Constructor, staticProps); return Constructor; }
  5844. var level_Level = /*#__PURE__*/function () {
  5845. function Level(baseUrl) {
  5846. // Please keep properties in alphabetical order
  5847. this.endCC = 0;
  5848. this.endSN = 0;
  5849. this.fragments = [];
  5850. this.initSegment = null;
  5851. this.live = true;
  5852. this.needSidxRanges = false;
  5853. this.startCC = 0;
  5854. this.startSN = 0;
  5855. this.startTimeOffset = null;
  5856. this.targetduration = 0;
  5857. this.totalduration = 0;
  5858. this.type = null;
  5859. this.url = baseUrl;
  5860. this.version = null;
  5861. }
  5862. level_createClass(Level, [{
  5863. key: "hasProgramDateTime",
  5864. get: function get() {
  5865. return !!(this.fragments[0] && Object(number["isFiniteNumber"])(this.fragments[0].programDateTime));
  5866. }
  5867. }]);
  5868. return Level;
  5869. }();
  5870. // CONCATENATED MODULE: ./src/utils/attr-list.js
  5871. var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/; // eslint-disable-line no-useless-escape
  5872. var ATTR_LIST_REGEX = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape
  5873. // adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
  5874. var AttrList = /*#__PURE__*/function () {
  5875. function AttrList(attrs) {
  5876. if (typeof attrs === 'string') {
  5877. attrs = AttrList.parseAttrList(attrs);
  5878. }
  5879. for (var attr in attrs) {
  5880. if (attrs.hasOwnProperty(attr)) {
  5881. this[attr] = attrs[attr];
  5882. }
  5883. }
  5884. }
  5885. var _proto = AttrList.prototype;
  5886. _proto.decimalInteger = function decimalInteger(attrName) {
  5887. var intValue = parseInt(this[attrName], 10);
  5888. if (intValue > Number.MAX_SAFE_INTEGER) {
  5889. return Infinity;
  5890. }
  5891. return intValue;
  5892. };
  5893. _proto.hexadecimalInteger = function hexadecimalInteger(attrName) {
  5894. if (this[attrName]) {
  5895. var stringValue = (this[attrName] || '0x').slice(2);
  5896. stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;
  5897. var value = new Uint8Array(stringValue.length / 2);
  5898. for (var i = 0; i < stringValue.length / 2; i++) {
  5899. value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
  5900. }
  5901. return value;
  5902. } else {
  5903. return null;
  5904. }
  5905. };
  5906. _proto.hexadecimalIntegerAsNumber = function hexadecimalIntegerAsNumber(attrName) {
  5907. var intValue = parseInt(this[attrName], 16);
  5908. if (intValue > Number.MAX_SAFE_INTEGER) {
  5909. return Infinity;
  5910. }
  5911. return intValue;
  5912. };
  5913. _proto.decimalFloatingPoint = function decimalFloatingPoint(attrName) {
  5914. return parseFloat(this[attrName]);
  5915. };
  5916. _proto.enumeratedString = function enumeratedString(attrName) {
  5917. return this[attrName];
  5918. };
  5919. _proto.decimalResolution = function decimalResolution(attrName) {
  5920. var res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
  5921. if (res === null) {
  5922. return undefined;
  5923. }
  5924. return {
  5925. width: parseInt(res[1], 10),
  5926. height: parseInt(res[2], 10)
  5927. };
  5928. };
  5929. AttrList.parseAttrList = function parseAttrList(input) {
  5930. var match,
  5931. attrs = {};
  5932. ATTR_LIST_REGEX.lastIndex = 0;
  5933. while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
  5934. var value = match[2],
  5935. quote = '"';
  5936. if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) {
  5937. value = value.slice(1, -1);
  5938. }
  5939. attrs[match[1]] = value;
  5940. }
  5941. return attrs;
  5942. };
  5943. return AttrList;
  5944. }();
  5945. /* harmony default export */ var attr_list = (AttrList);
  5946. // CONCATENATED MODULE: ./src/utils/codecs.ts
  5947. // from http://mp4ra.org/codecs.html
  5948. var sampleEntryCodesISO = {
  5949. audio: {
  5950. 'a3ds': true,
  5951. 'ac-3': true,
  5952. 'ac-4': true,
  5953. 'alac': true,
  5954. 'alaw': true,
  5955. 'dra1': true,
  5956. 'dts+': true,
  5957. 'dts-': true,
  5958. 'dtsc': true,
  5959. 'dtse': true,
  5960. 'dtsh': true,
  5961. 'ec-3': true,
  5962. 'enca': true,
  5963. 'g719': true,
  5964. 'g726': true,
  5965. 'm4ae': true,
  5966. 'mha1': true,
  5967. 'mha2': true,
  5968. 'mhm1': true,
  5969. 'mhm2': true,
  5970. 'mlpa': true,
  5971. 'mp4a': true,
  5972. 'raw ': true,
  5973. 'Opus': true,
  5974. 'samr': true,
  5975. 'sawb': true,
  5976. 'sawp': true,
  5977. 'sevc': true,
  5978. 'sqcp': true,
  5979. 'ssmv': true,
  5980. 'twos': true,
  5981. 'ulaw': true
  5982. },
  5983. video: {
  5984. 'avc1': true,
  5985. 'avc2': true,
  5986. 'avc3': true,
  5987. 'avc4': true,
  5988. 'avcp': true,
  5989. 'drac': true,
  5990. 'dvav': true,
  5991. 'dvhe': true,
  5992. 'encv': true,
  5993. 'hev1': true,
  5994. 'hvc1': true,
  5995. 'mjp2': true,
  5996. 'mp4v': true,
  5997. 'mvc1': true,
  5998. 'mvc2': true,
  5999. 'mvc3': true,
  6000. 'mvc4': true,
  6001. 'resv': true,
  6002. 'rv60': true,
  6003. 's263': true,
  6004. 'svc1': true,
  6005. 'svc2': true,
  6006. 'vc-1': true,
  6007. 'vp08': true,
  6008. 'vp09': true
  6009. }
  6010. };
  6011. function isCodecType(codec, type) {
  6012. var typeCodes = sampleEntryCodesISO[type];
  6013. return !!typeCodes && typeCodes[codec.slice(0, 4)] === true;
  6014. }
  6015. function isCodecSupportedInMp4(codec, type) {
  6016. return MediaSource.isTypeSupported((type || 'video') + "/mp4;codecs=\"" + codec + "\"");
  6017. }
  6018. // CONCATENATED MODULE: ./src/loader/m3u8-parser.ts
  6019. /**
  6020. * M3U8 parser
  6021. * @module
  6022. */
  6023. // https://regex101.com is your friend
  6024. var MASTER_PLAYLIST_REGEX = /(?:#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)|#EXT-X-SESSION-DATA:([^\n\r]*)[\r\n]+)/g;
  6025. var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
  6026. var LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source, // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
  6027. /|(?!#)([\S+ ?]+)/.source, // segment URI, group 3 => the URI (note newline is not eaten)
  6028. /|#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y)
  6029. /|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec
  6030. /|#.*/.source // All other non-segment oriented tags will match with all groups empty
  6031. ].join(''), 'g');
  6032. 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?/;
  6033. var MP4_REGEX_SUFFIX = /\.(mp4|m4s|m4v|m4a)$/i;
  6034. var m3u8_parser_M3U8Parser = /*#__PURE__*/function () {
  6035. function M3U8Parser() {}
  6036. M3U8Parser.findGroup = function findGroup(groups, mediaGroupId) {
  6037. for (var i = 0; i < groups.length; i++) {
  6038. var group = groups[i];
  6039. if (group.id === mediaGroupId) {
  6040. return group;
  6041. }
  6042. }
  6043. };
  6044. M3U8Parser.convertAVC1ToAVCOTI = function convertAVC1ToAVCOTI(codec) {
  6045. var avcdata = codec.split('.');
  6046. var result;
  6047. if (avcdata.length > 2) {
  6048. result = avcdata.shift() + '.';
  6049. result += parseInt(avcdata.shift()).toString(16);
  6050. result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4);
  6051. } else {
  6052. result = codec;
  6053. }
  6054. return result;
  6055. };
  6056. M3U8Parser.resolve = function resolve(url, baseUrl) {
  6057. return url_toolkit["buildAbsoluteURL"](baseUrl, url, {
  6058. alwaysNormalize: true
  6059. });
  6060. };
  6061. M3U8Parser.parseMasterPlaylist = function parseMasterPlaylist(string, baseurl) {
  6062. // TODO(typescript-level)
  6063. var levels = [];
  6064. var sessionData = {};
  6065. var hasSessionData = false;
  6066. MASTER_PLAYLIST_REGEX.lastIndex = 0; // TODO(typescript-level)
  6067. function setCodecs(codecs, level) {
  6068. ['video', 'audio'].forEach(function (type) {
  6069. var filtered = codecs.filter(function (codec) {
  6070. return isCodecType(codec, type);
  6071. });
  6072. if (filtered.length) {
  6073. var preferred = filtered.filter(function (codec) {
  6074. return codec.lastIndexOf('avc1', 0) === 0 || codec.lastIndexOf('mp4a', 0) === 0;
  6075. });
  6076. level[type + "Codec"] = preferred.length > 0 ? preferred[0] : filtered[0]; // remove from list
  6077. codecs = codecs.filter(function (codec) {
  6078. return filtered.indexOf(codec) === -1;
  6079. });
  6080. }
  6081. });
  6082. level.unknownCodecs = codecs;
  6083. }
  6084. var result;
  6085. while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
  6086. if (result[1]) {
  6087. // '#EXT-X-STREAM-INF' is found, parse level tag in group 1
  6088. // TODO(typescript-level)
  6089. var level = {};
  6090. var attrs = level.attrs = new attr_list(result[1]);
  6091. level.url = M3U8Parser.resolve(result[2], baseurl);
  6092. var resolution = attrs.decimalResolution('RESOLUTION');
  6093. if (resolution) {
  6094. level.width = resolution.width;
  6095. level.height = resolution.height;
  6096. }
  6097. level.bitrate = attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH');
  6098. level.name = attrs.NAME;
  6099. setCodecs([].concat((attrs.CODECS || '').split(/[ ,]+/)), level);
  6100. if (level.videoCodec && level.videoCodec.indexOf('avc1') !== -1) {
  6101. level.videoCodec = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);
  6102. }
  6103. levels.push(level);
  6104. } else if (result[3]) {
  6105. // '#EXT-X-SESSION-DATA' is found, parse session data in group 3
  6106. var sessionAttrs = new attr_list(result[3]);
  6107. if (sessionAttrs['DATA-ID']) {
  6108. hasSessionData = true;
  6109. sessionData[sessionAttrs['DATA-ID']] = sessionAttrs;
  6110. }
  6111. }
  6112. }
  6113. return {
  6114. levels: levels,
  6115. sessionData: hasSessionData ? sessionData : null
  6116. };
  6117. };
  6118. M3U8Parser.parseMasterPlaylistMedia = function parseMasterPlaylistMedia(string, baseurl, type, audioGroups) {
  6119. if (audioGroups === void 0) {
  6120. audioGroups = [];
  6121. }
  6122. var result;
  6123. var medias = [];
  6124. var id = 0;
  6125. MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
  6126. while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
  6127. var attrs = new attr_list(result[1]);
  6128. if (attrs.TYPE === type) {
  6129. var media = {
  6130. attrs: attrs,
  6131. id: id++,
  6132. groupId: attrs['GROUP-ID'],
  6133. instreamId: attrs['INSTREAM-ID'],
  6134. name: attrs.NAME || attrs.LANGUAGE,
  6135. type: type,
  6136. default: attrs.DEFAULT === 'YES',
  6137. autoselect: attrs.AUTOSELECT === 'YES',
  6138. forced: attrs.FORCED === 'YES',
  6139. lang: attrs.LANGUAGE
  6140. };
  6141. if (attrs.URI) {
  6142. media.url = M3U8Parser.resolve(attrs.URI, baseurl);
  6143. }
  6144. if (audioGroups.length) {
  6145. // If there are audio groups signalled in the manifest, let's look for a matching codec string for this track
  6146. var groupCodec = M3U8Parser.findGroup(audioGroups, media.groupId); // If we don't find the track signalled, lets use the first audio groups codec we have
  6147. // Acting as a best guess
  6148. media.audioCodec = groupCodec ? groupCodec.codec : audioGroups[0].codec;
  6149. }
  6150. medias.push(media);
  6151. }
  6152. }
  6153. return medias;
  6154. };
  6155. M3U8Parser.parseLevelPlaylist = function parseLevelPlaylist(string, baseurl, id, type, levelUrlId) {
  6156. var currentSN = 0;
  6157. var totalduration = 0;
  6158. var level = new level_Level(baseurl);
  6159. var discontinuityCounter = 0;
  6160. var prevFrag = null;
  6161. var frag = new fragment_Fragment();
  6162. var result;
  6163. var i;
  6164. var levelkey;
  6165. var firstPdtIndex = null;
  6166. LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
  6167. while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
  6168. var duration = result[1];
  6169. if (duration) {
  6170. // INF
  6171. frag.duration = parseFloat(duration); // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  6172. var title = (' ' + result[2]).slice(1);
  6173. frag.title = title || null;
  6174. frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);
  6175. } else if (result[3]) {
  6176. // url
  6177. if (Object(number["isFiniteNumber"])(frag.duration)) {
  6178. var sn = currentSN++;
  6179. frag.type = type;
  6180. frag.start = totalduration;
  6181. if (levelkey) {
  6182. frag.levelkey = levelkey;
  6183. }
  6184. frag.sn = sn;
  6185. frag.level = id;
  6186. frag.cc = discontinuityCounter;
  6187. frag.urlId = levelUrlId;
  6188. frag.baseurl = baseurl; // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  6189. frag.relurl = (' ' + result[3]).slice(1);
  6190. assignProgramDateTime(frag, prevFrag);
  6191. level.fragments.push(frag);
  6192. prevFrag = frag;
  6193. totalduration += frag.duration;
  6194. frag = new fragment_Fragment();
  6195. }
  6196. } else if (result[4]) {
  6197. // X-BYTERANGE
  6198. var data = (' ' + result[4]).slice(1);
  6199. if (prevFrag) {
  6200. frag.setByteRange(data, prevFrag);
  6201. } else {
  6202. frag.setByteRange(data);
  6203. }
  6204. } else if (result[5]) {
  6205. // PROGRAM-DATE-TIME
  6206. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  6207. frag.rawProgramDateTime = (' ' + result[5]).slice(1);
  6208. frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);
  6209. if (firstPdtIndex === null) {
  6210. firstPdtIndex = level.fragments.length;
  6211. }
  6212. } else {
  6213. result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
  6214. if (!result) {
  6215. logger["logger"].warn('No matches on slow regex match for level playlist!');
  6216. continue;
  6217. }
  6218. for (i = 1; i < result.length; i++) {
  6219. if (typeof result[i] !== 'undefined') {
  6220. break;
  6221. }
  6222. } // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  6223. var value1 = (' ' + result[i + 1]).slice(1);
  6224. var value2 = (' ' + result[i + 2]).slice(1);
  6225. switch (result[i]) {
  6226. case '#':
  6227. frag.tagList.push(value2 ? [value1, value2] : [value1]);
  6228. break;
  6229. case 'PLAYLIST-TYPE':
  6230. level.type = value1.toUpperCase();
  6231. break;
  6232. case 'MEDIA-SEQUENCE':
  6233. currentSN = level.startSN = parseInt(value1);
  6234. break;
  6235. case 'TARGETDURATION':
  6236. level.targetduration = parseFloat(value1);
  6237. break;
  6238. case 'VERSION':
  6239. level.version = parseInt(value1);
  6240. break;
  6241. case 'EXTM3U':
  6242. break;
  6243. case 'ENDLIST':
  6244. level.live = false;
  6245. break;
  6246. case 'DIS':
  6247. discontinuityCounter++;
  6248. frag.tagList.push(['DIS']);
  6249. break;
  6250. case 'DISCONTINUITY-SEQ':
  6251. discontinuityCounter = parseInt(value1);
  6252. break;
  6253. case 'KEY':
  6254. {
  6255. // https://tools.ietf.org/html/rfc8216#section-4.3.2.4
  6256. var decryptparams = value1;
  6257. var keyAttrs = new attr_list(decryptparams);
  6258. var decryptmethod = keyAttrs.enumeratedString('METHOD');
  6259. var decrypturi = keyAttrs.URI;
  6260. var decryptiv = keyAttrs.hexadecimalInteger('IV'); // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of "identity".
  6261. var decryptkeyformat = keyAttrs.KEYFORMAT || 'identity';
  6262. if (decryptkeyformat === 'com.apple.streamingkeydelivery') {
  6263. logger["logger"].warn('Keyformat com.apple.streamingkeydelivery is not supported');
  6264. continue;
  6265. }
  6266. if (decryptmethod) {
  6267. levelkey = new level_key_LevelKey(baseurl, decrypturi);
  6268. if (decrypturi && ['AES-128', 'SAMPLE-AES', 'SAMPLE-AES-CENC'].indexOf(decryptmethod) >= 0) {
  6269. levelkey.method = decryptmethod;
  6270. levelkey.key = null; // Initialization Vector (IV)
  6271. levelkey.iv = decryptiv;
  6272. }
  6273. }
  6274. break;
  6275. }
  6276. case 'START':
  6277. {
  6278. var startAttrs = new attr_list(value1);
  6279. var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET'); // TIME-OFFSET can be 0
  6280. if (Object(number["isFiniteNumber"])(startTimeOffset)) {
  6281. level.startTimeOffset = startTimeOffset;
  6282. }
  6283. break;
  6284. }
  6285. case 'MAP':
  6286. {
  6287. var mapAttrs = new attr_list(value1);
  6288. frag.relurl = mapAttrs.URI;
  6289. if (mapAttrs.BYTERANGE) {
  6290. frag.setByteRange(mapAttrs.BYTERANGE);
  6291. }
  6292. frag.baseurl = baseurl;
  6293. frag.level = id;
  6294. frag.type = type;
  6295. frag.sn = 'initSegment';
  6296. level.initSegment = frag;
  6297. frag = new fragment_Fragment();
  6298. frag.rawProgramDateTime = level.initSegment.rawProgramDateTime;
  6299. break;
  6300. }
  6301. default:
  6302. logger["logger"].warn("line parsed but not handled: " + result);
  6303. break;
  6304. }
  6305. }
  6306. }
  6307. frag = prevFrag; // logger.log('found ' + level.fragments.length + ' fragments');
  6308. if (frag && !frag.relurl) {
  6309. level.fragments.pop();
  6310. totalduration -= frag.duration;
  6311. }
  6312. level.totalduration = totalduration;
  6313. level.averagetargetduration = totalduration / level.fragments.length;
  6314. level.endSN = currentSN - 1;
  6315. level.startCC = level.fragments[0] ? level.fragments[0].cc : 0;
  6316. level.endCC = discontinuityCounter;
  6317. if (!level.initSegment && level.fragments.length) {
  6318. // this is a bit lurky but HLS really has no other way to tell us
  6319. // if the fragments are TS or MP4, except if we download them :/
  6320. // but this is to be able to handle SIDX.
  6321. if (level.fragments.every(function (frag) {
  6322. return MP4_REGEX_SUFFIX.test(frag.relurl);
  6323. })) {
  6324. logger["logger"].warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX');
  6325. frag = new fragment_Fragment();
  6326. frag.relurl = level.fragments[0].relurl;
  6327. frag.baseurl = baseurl;
  6328. frag.level = id;
  6329. frag.type = type;
  6330. frag.sn = 'initSegment';
  6331. level.initSegment = frag;
  6332. level.needSidxRanges = true;
  6333. }
  6334. }
  6335. /**
  6336. * Backfill any missing PDT values
  6337. "If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after
  6338. one or more Media Segment URIs, the client SHOULD extrapolate
  6339. backward from that tag (using EXTINF durations and/or media
  6340. timestamps) to associate dates with those segments."
  6341. * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs
  6342. * computed.
  6343. */
  6344. if (firstPdtIndex) {
  6345. backfillProgramDateTimes(level.fragments, firstPdtIndex);
  6346. }
  6347. return level;
  6348. };
  6349. return M3U8Parser;
  6350. }();
  6351. function backfillProgramDateTimes(fragments, startIndex) {
  6352. var fragPrev = fragments[startIndex];
  6353. for (var i = startIndex - 1; i >= 0; i--) {
  6354. var frag = fragments[i];
  6355. frag.programDateTime = fragPrev.programDateTime - frag.duration * 1000;
  6356. fragPrev = frag;
  6357. }
  6358. }
  6359. function assignProgramDateTime(frag, prevFrag) {
  6360. if (frag.rawProgramDateTime) {
  6361. frag.programDateTime = Date.parse(frag.rawProgramDateTime);
  6362. } else if (prevFrag === null || prevFrag === void 0 ? void 0 : prevFrag.programDateTime) {
  6363. frag.programDateTime = prevFrag.endProgramDateTime;
  6364. }
  6365. if (!Object(number["isFiniteNumber"])(frag.programDateTime)) {
  6366. frag.programDateTime = null;
  6367. frag.rawProgramDateTime = null;
  6368. }
  6369. }
  6370. // CONCATENATED MODULE: ./src/loader/playlist-loader.ts
  6371. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  6372. /**
  6373. * PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models.
  6374. *
  6375. * Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks.
  6376. *
  6377. * Uses loader(s) set in config to do actual internal loading of resource tasks.
  6378. *
  6379. * @module
  6380. *
  6381. */
  6382. var _window = window,
  6383. performance = _window.performance;
  6384. /**
  6385. * @constructor
  6386. */
  6387. var playlist_loader_PlaylistLoader = /*#__PURE__*/function (_EventHandler) {
  6388. _inheritsLoose(PlaylistLoader, _EventHandler);
  6389. /**
  6390. * @constructs
  6391. * @param {Hls} hls
  6392. */
  6393. function PlaylistLoader(hls) {
  6394. var _this;
  6395. _this = _EventHandler.call(this, hls, events["default"].MANIFEST_LOADING, events["default"].LEVEL_LOADING, events["default"].AUDIO_TRACK_LOADING, events["default"].SUBTITLE_TRACK_LOADING) || this;
  6396. _this.loaders = {};
  6397. return _this;
  6398. }
  6399. /**
  6400. * @param {PlaylistContextType} type
  6401. * @returns {boolean}
  6402. */
  6403. PlaylistLoader.canHaveQualityLevels = function canHaveQualityLevels(type) {
  6404. return type !== PlaylistContextType.AUDIO_TRACK && type !== PlaylistContextType.SUBTITLE_TRACK;
  6405. }
  6406. /**
  6407. * Map context.type to LevelType
  6408. * @param {PlaylistLoaderContext} context
  6409. * @returns {LevelType}
  6410. */
  6411. ;
  6412. PlaylistLoader.mapContextToLevelType = function mapContextToLevelType(context) {
  6413. var type = context.type;
  6414. switch (type) {
  6415. case PlaylistContextType.AUDIO_TRACK:
  6416. return PlaylistLevelType.AUDIO;
  6417. case PlaylistContextType.SUBTITLE_TRACK:
  6418. return PlaylistLevelType.SUBTITLE;
  6419. default:
  6420. return PlaylistLevelType.MAIN;
  6421. }
  6422. };
  6423. PlaylistLoader.getResponseUrl = function getResponseUrl(response, context) {
  6424. var url = response.url; // responseURL not supported on some browsers (it is used to detect URL redirection)
  6425. // data-uri mode also not supported (but no need to detect redirection)
  6426. if (url === undefined || url.indexOf('data:') === 0) {
  6427. // fallback to initial URL
  6428. url = context.url;
  6429. }
  6430. return url;
  6431. }
  6432. /**
  6433. * Returns defaults or configured loader-type overloads (pLoader and loader config params)
  6434. * Default loader is XHRLoader (see utils)
  6435. * @param {PlaylistLoaderContext} context
  6436. * @returns {Loader} or other compatible configured overload
  6437. */
  6438. ;
  6439. var _proto = PlaylistLoader.prototype;
  6440. _proto.createInternalLoader = function createInternalLoader(context) {
  6441. var config = this.hls.config;
  6442. var PLoader = config.pLoader;
  6443. var Loader = config.loader; // TODO(typescript-config): Verify once config is typed that InternalLoader always returns a Loader
  6444. var InternalLoader = PLoader || Loader;
  6445. var loader = new InternalLoader(config); // TODO - Do we really need to assign the instance or if the dep has been lost
  6446. context.loader = loader;
  6447. this.loaders[context.type] = loader;
  6448. return loader;
  6449. };
  6450. _proto.getInternalLoader = function getInternalLoader(context) {
  6451. return this.loaders[context.type];
  6452. };
  6453. _proto.resetInternalLoader = function resetInternalLoader(contextType) {
  6454. if (this.loaders[contextType]) {
  6455. delete this.loaders[contextType];
  6456. }
  6457. }
  6458. /**
  6459. * Call `destroy` on all internal loader instances mapped (one per context type)
  6460. */
  6461. ;
  6462. _proto.destroyInternalLoaders = function destroyInternalLoaders() {
  6463. for (var contextType in this.loaders) {
  6464. var loader = this.loaders[contextType];
  6465. if (loader) {
  6466. loader.destroy();
  6467. }
  6468. this.resetInternalLoader(contextType);
  6469. }
  6470. };
  6471. _proto.destroy = function destroy() {
  6472. this.destroyInternalLoaders();
  6473. _EventHandler.prototype.destroy.call(this);
  6474. };
  6475. _proto.onManifestLoading = function onManifestLoading(data) {
  6476. this.load({
  6477. url: data.url,
  6478. type: PlaylistContextType.MANIFEST,
  6479. level: 0,
  6480. id: null,
  6481. responseType: 'text'
  6482. });
  6483. };
  6484. _proto.onLevelLoading = function onLevelLoading(data) {
  6485. this.load({
  6486. url: data.url,
  6487. type: PlaylistContextType.LEVEL,
  6488. level: data.level,
  6489. id: data.id,
  6490. responseType: 'text'
  6491. });
  6492. };
  6493. _proto.onAudioTrackLoading = function onAudioTrackLoading(data) {
  6494. this.load({
  6495. url: data.url,
  6496. type: PlaylistContextType.AUDIO_TRACK,
  6497. level: null,
  6498. id: data.id,
  6499. responseType: 'text'
  6500. });
  6501. };
  6502. _proto.onSubtitleTrackLoading = function onSubtitleTrackLoading(data) {
  6503. this.load({
  6504. url: data.url,
  6505. type: PlaylistContextType.SUBTITLE_TRACK,
  6506. level: null,
  6507. id: data.id,
  6508. responseType: 'text'
  6509. });
  6510. };
  6511. _proto.load = function load(context) {
  6512. var config = this.hls.config;
  6513. logger["logger"].debug("Loading playlist of type " + context.type + ", level: " + context.level + ", id: " + context.id); // Check if a loader for this context already exists
  6514. var loader = this.getInternalLoader(context);
  6515. if (loader) {
  6516. var loaderContext = loader.context;
  6517. if (loaderContext && loaderContext.url === context.url) {
  6518. // same URL can't overlap
  6519. logger["logger"].trace('playlist request ongoing');
  6520. return false;
  6521. } else {
  6522. logger["logger"].warn("aborting previous loader for type: " + context.type);
  6523. loader.abort();
  6524. }
  6525. }
  6526. var maxRetry;
  6527. var timeout;
  6528. var retryDelay;
  6529. var maxRetryDelay; // apply different configs for retries depending on
  6530. // context (manifest, level, audio/subs playlist)
  6531. switch (context.type) {
  6532. case PlaylistContextType.MANIFEST:
  6533. maxRetry = config.manifestLoadingMaxRetry;
  6534. timeout = config.manifestLoadingTimeOut;
  6535. retryDelay = config.manifestLoadingRetryDelay;
  6536. maxRetryDelay = config.manifestLoadingMaxRetryTimeout;
  6537. break;
  6538. case PlaylistContextType.LEVEL:
  6539. // Disable internal loader retry logic, since we are managing retries in Level Controller
  6540. maxRetry = 0;
  6541. maxRetryDelay = 0;
  6542. retryDelay = 0;
  6543. timeout = config.levelLoadingTimeOut; // TODO Introduce retry settings for audio-track and subtitle-track, it should not use level retry config
  6544. break;
  6545. default:
  6546. maxRetry = config.levelLoadingMaxRetry;
  6547. timeout = config.levelLoadingTimeOut;
  6548. retryDelay = config.levelLoadingRetryDelay;
  6549. maxRetryDelay = config.levelLoadingMaxRetryTimeout;
  6550. break;
  6551. }
  6552. loader = this.createInternalLoader(context);
  6553. var loaderConfig = {
  6554. timeout: timeout,
  6555. maxRetry: maxRetry,
  6556. retryDelay: retryDelay,
  6557. maxRetryDelay: maxRetryDelay
  6558. };
  6559. var loaderCallbacks = {
  6560. onSuccess: this.loadsuccess.bind(this),
  6561. onError: this.loaderror.bind(this),
  6562. onTimeout: this.loadtimeout.bind(this)
  6563. };
  6564. logger["logger"].debug("Calling internal loader delegate for URL: " + context.url);
  6565. loader.load(context, loaderConfig, loaderCallbacks);
  6566. return true;
  6567. };
  6568. _proto.loadsuccess = function loadsuccess(response, stats, context, networkDetails) {
  6569. if (networkDetails === void 0) {
  6570. networkDetails = null;
  6571. }
  6572. if (context.isSidxRequest) {
  6573. this._handleSidxRequest(response, context);
  6574. this._handlePlaylistLoaded(response, stats, context, networkDetails);
  6575. return;
  6576. }
  6577. this.resetInternalLoader(context.type);
  6578. if (typeof response.data !== 'string') {
  6579. throw new Error('expected responseType of "text" for PlaylistLoader');
  6580. }
  6581. var string = response.data;
  6582. stats.tload = performance.now(); // stats.mtime = new Date(target.getResponseHeader('Last-Modified'));
  6583. // Validate if it is an M3U8 at all
  6584. if (string.indexOf('#EXTM3U') !== 0) {
  6585. this._handleManifestParsingError(response, context, 'no EXTM3U delimiter', networkDetails);
  6586. return;
  6587. } // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present)
  6588. if (string.indexOf('#EXTINF:') > 0 || string.indexOf('#EXT-X-TARGETDURATION:') > 0) {
  6589. this._handleTrackOrLevelPlaylist(response, stats, context, networkDetails);
  6590. } else {
  6591. this._handleMasterPlaylist(response, stats, context, networkDetails);
  6592. }
  6593. };
  6594. _proto.loaderror = function loaderror(response, context, networkDetails) {
  6595. if (networkDetails === void 0) {
  6596. networkDetails = null;
  6597. }
  6598. this._handleNetworkError(context, networkDetails, false, response);
  6599. };
  6600. _proto.loadtimeout = function loadtimeout(stats, context, networkDetails) {
  6601. if (networkDetails === void 0) {
  6602. networkDetails = null;
  6603. }
  6604. this._handleNetworkError(context, networkDetails, true);
  6605. } // TODO(typescript-config): networkDetails can currently be a XHR or Fetch impl,
  6606. // but with custom loaders it could be generic investigate this further when config is typed
  6607. ;
  6608. _proto._handleMasterPlaylist = function _handleMasterPlaylist(response, stats, context, networkDetails) {
  6609. var hls = this.hls;
  6610. var string = response.data;
  6611. var url = PlaylistLoader.getResponseUrl(response, context);
  6612. var _M3U8Parser$parseMast = m3u8_parser_M3U8Parser.parseMasterPlaylist(string, url),
  6613. levels = _M3U8Parser$parseMast.levels,
  6614. sessionData = _M3U8Parser$parseMast.sessionData;
  6615. if (!levels.length) {
  6616. this._handleManifestParsingError(response, context, 'no level found in manifest', networkDetails);
  6617. return;
  6618. } // multi level playlist, parse level info
  6619. var audioGroups = levels.map(function (level) {
  6620. return {
  6621. id: level.attrs.AUDIO,
  6622. codec: level.audioCodec
  6623. };
  6624. });
  6625. var audioTracks = m3u8_parser_M3U8Parser.parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups);
  6626. var subtitles = m3u8_parser_M3U8Parser.parseMasterPlaylistMedia(string, url, 'SUBTITLES');
  6627. var captions = m3u8_parser_M3U8Parser.parseMasterPlaylistMedia(string, url, 'CLOSED-CAPTIONS');
  6628. if (audioTracks.length) {
  6629. // check if we have found an audio track embedded in main playlist (audio track without URI attribute)
  6630. var embeddedAudioFound = false;
  6631. audioTracks.forEach(function (audioTrack) {
  6632. if (!audioTrack.url) {
  6633. embeddedAudioFound = true;
  6634. }
  6635. }); // if no embedded audio track defined, but audio codec signaled in quality level,
  6636. // we need to signal this main audio track this could happen with playlists with
  6637. // alt audio rendition in which quality levels (main)
  6638. // contains both audio+video. but with mixed audio track not signaled
  6639. if (embeddedAudioFound === false && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
  6640. logger["logger"].log('audio codec signaled in quality level, but no embedded audio track signaled, create one');
  6641. audioTracks.unshift({
  6642. type: 'main',
  6643. name: 'main',
  6644. default: false,
  6645. autoselect: false,
  6646. forced: false,
  6647. id: -1,
  6648. attrs: {},
  6649. url: ''
  6650. });
  6651. }
  6652. }
  6653. hls.trigger(events["default"].MANIFEST_LOADED, {
  6654. levels: levels,
  6655. audioTracks: audioTracks,
  6656. subtitles: subtitles,
  6657. captions: captions,
  6658. url: url,
  6659. stats: stats,
  6660. networkDetails: networkDetails,
  6661. sessionData: sessionData
  6662. });
  6663. };
  6664. _proto._handleTrackOrLevelPlaylist = function _handleTrackOrLevelPlaylist(response, stats, context, networkDetails) {
  6665. var hls = this.hls;
  6666. var id = context.id,
  6667. level = context.level,
  6668. type = context.type;
  6669. var url = PlaylistLoader.getResponseUrl(response, context); // if the values are null, they will result in the else conditional
  6670. var levelUrlId = Object(number["isFiniteNumber"])(id) ? id : 0;
  6671. var levelId = Object(number["isFiniteNumber"])(level) ? level : levelUrlId;
  6672. var levelType = PlaylistLoader.mapContextToLevelType(context);
  6673. var levelDetails = m3u8_parser_M3U8Parser.parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId); // set stats on level structure
  6674. // TODO(jstackhouse): why? mixing concerns, is it just treated as value bag?
  6675. levelDetails.tload = stats.tload;
  6676. if (!levelDetails.fragments.length) {
  6677. hls.trigger(events["default"].ERROR, {
  6678. type: errors["ErrorTypes"].NETWORK_ERROR,
  6679. details: errors["ErrorDetails"].LEVEL_EMPTY_ERROR,
  6680. fatal: false,
  6681. url: url,
  6682. reason: 'no fragments found in level',
  6683. level: typeof context.level === 'number' ? context.level : undefined
  6684. });
  6685. return;
  6686. } // We have done our first request (Manifest-type) and receive
  6687. // not a master playlist but a chunk-list (track/level)
  6688. // We fire the manifest-loaded event anyway with the parsed level-details
  6689. // by creating a single-level structure for it.
  6690. if (type === PlaylistContextType.MANIFEST) {
  6691. var singleLevel = {
  6692. url: url,
  6693. details: levelDetails
  6694. };
  6695. hls.trigger(events["default"].MANIFEST_LOADED, {
  6696. levels: [singleLevel],
  6697. audioTracks: [],
  6698. url: url,
  6699. stats: stats,
  6700. networkDetails: networkDetails,
  6701. sessionData: null
  6702. });
  6703. } // save parsing time
  6704. stats.tparsed = performance.now(); // in case we need SIDX ranges
  6705. // return early after calling load for
  6706. // the SIDX box.
  6707. if (levelDetails.needSidxRanges) {
  6708. var sidxUrl = levelDetails.initSegment.url;
  6709. this.load({
  6710. url: sidxUrl,
  6711. isSidxRequest: true,
  6712. type: type,
  6713. level: level,
  6714. levelDetails: levelDetails,
  6715. id: id,
  6716. rangeStart: 0,
  6717. rangeEnd: 2048,
  6718. responseType: 'arraybuffer'
  6719. });
  6720. return;
  6721. } // extend the context with the new levelDetails property
  6722. context.levelDetails = levelDetails;
  6723. this._handlePlaylistLoaded(response, stats, context, networkDetails);
  6724. };
  6725. _proto._handleSidxRequest = function _handleSidxRequest(response, context) {
  6726. if (typeof response.data === 'string') {
  6727. throw new Error('sidx request must be made with responseType of array buffer');
  6728. }
  6729. var sidxInfo = mp4demuxer["default"].parseSegmentIndex(new Uint8Array(response.data)); // if provided fragment does not contain sidx, early return
  6730. if (!sidxInfo) {
  6731. return;
  6732. }
  6733. var sidxReferences = sidxInfo.references;
  6734. var levelDetails = context.levelDetails;
  6735. sidxReferences.forEach(function (segmentRef, index) {
  6736. var segRefInfo = segmentRef.info;
  6737. if (!levelDetails) {
  6738. return;
  6739. }
  6740. var frag = levelDetails.fragments[index];
  6741. if (frag.byteRange.length === 0) {
  6742. frag.setByteRange(String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start));
  6743. }
  6744. });
  6745. if (levelDetails) {
  6746. levelDetails.initSegment.setByteRange(String(sidxInfo.moovEndOffset) + '@0');
  6747. }
  6748. };
  6749. _proto._handleManifestParsingError = function _handleManifestParsingError(response, context, reason, networkDetails) {
  6750. this.hls.trigger(events["default"].ERROR, {
  6751. type: errors["ErrorTypes"].NETWORK_ERROR,
  6752. details: errors["ErrorDetails"].MANIFEST_PARSING_ERROR,
  6753. fatal: true,
  6754. url: response.url,
  6755. reason: reason,
  6756. networkDetails: networkDetails
  6757. });
  6758. };
  6759. _proto._handleNetworkError = function _handleNetworkError(context, networkDetails, timeout, response) {
  6760. if (timeout === void 0) {
  6761. timeout = false;
  6762. }
  6763. if (response === void 0) {
  6764. response = null;
  6765. }
  6766. logger["logger"].info("A network error occured while loading a " + context.type + "-type playlist");
  6767. var details;
  6768. var fatal;
  6769. var loader = this.getInternalLoader(context);
  6770. switch (context.type) {
  6771. case PlaylistContextType.MANIFEST:
  6772. details = timeout ? errors["ErrorDetails"].MANIFEST_LOAD_TIMEOUT : errors["ErrorDetails"].MANIFEST_LOAD_ERROR;
  6773. fatal = true;
  6774. break;
  6775. case PlaylistContextType.LEVEL:
  6776. details = timeout ? errors["ErrorDetails"].LEVEL_LOAD_TIMEOUT : errors["ErrorDetails"].LEVEL_LOAD_ERROR;
  6777. fatal = false;
  6778. break;
  6779. case PlaylistContextType.AUDIO_TRACK:
  6780. details = timeout ? errors["ErrorDetails"].AUDIO_TRACK_LOAD_TIMEOUT : errors["ErrorDetails"].AUDIO_TRACK_LOAD_ERROR;
  6781. fatal = false;
  6782. break;
  6783. default:
  6784. // details = ...?
  6785. fatal = false;
  6786. }
  6787. if (loader) {
  6788. loader.abort();
  6789. this.resetInternalLoader(context.type);
  6790. } // TODO(typescript-events): when error events are handled, type this
  6791. var errorData = {
  6792. type: errors["ErrorTypes"].NETWORK_ERROR,
  6793. details: details,
  6794. fatal: fatal,
  6795. url: context.url,
  6796. loader: loader,
  6797. context: context,
  6798. networkDetails: networkDetails
  6799. };
  6800. if (response) {
  6801. errorData.response = response;
  6802. }
  6803. this.hls.trigger(events["default"].ERROR, errorData);
  6804. };
  6805. _proto._handlePlaylistLoaded = function _handlePlaylistLoaded(response, stats, context, networkDetails) {
  6806. var type = context.type,
  6807. level = context.level,
  6808. id = context.id,
  6809. levelDetails = context.levelDetails;
  6810. if (!levelDetails || !levelDetails.targetduration) {
  6811. this._handleManifestParsingError(response, context, 'invalid target duration', networkDetails);
  6812. return;
  6813. }
  6814. var canHaveLevels = PlaylistLoader.canHaveQualityLevels(context.type);
  6815. if (canHaveLevels) {
  6816. this.hls.trigger(events["default"].LEVEL_LOADED, {
  6817. details: levelDetails,
  6818. level: level || 0,
  6819. id: id || 0,
  6820. stats: stats,
  6821. networkDetails: networkDetails
  6822. });
  6823. } else {
  6824. switch (type) {
  6825. case PlaylistContextType.AUDIO_TRACK:
  6826. this.hls.trigger(events["default"].AUDIO_TRACK_LOADED, {
  6827. details: levelDetails,
  6828. id: id,
  6829. stats: stats,
  6830. networkDetails: networkDetails
  6831. });
  6832. break;
  6833. case PlaylistContextType.SUBTITLE_TRACK:
  6834. this.hls.trigger(events["default"].SUBTITLE_TRACK_LOADED, {
  6835. details: levelDetails,
  6836. id: id,
  6837. stats: stats,
  6838. networkDetails: networkDetails
  6839. });
  6840. break;
  6841. }
  6842. }
  6843. };
  6844. return PlaylistLoader;
  6845. }(event_handler);
  6846. /* harmony default export */ var playlist_loader = (playlist_loader_PlaylistLoader);
  6847. // CONCATENATED MODULE: ./src/loader/fragment-loader.js
  6848. function fragment_loader_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  6849. /*
  6850. * Fragment Loader
  6851. */
  6852. var fragment_loader_FragmentLoader = /*#__PURE__*/function (_EventHandler) {
  6853. fragment_loader_inheritsLoose(FragmentLoader, _EventHandler);
  6854. function FragmentLoader(hls) {
  6855. var _this;
  6856. _this = _EventHandler.call(this, hls, events["default"].FRAG_LOADING) || this;
  6857. _this.loaders = {};
  6858. return _this;
  6859. }
  6860. var _proto = FragmentLoader.prototype;
  6861. _proto.destroy = function destroy() {
  6862. var loaders = this.loaders;
  6863. for (var loaderName in loaders) {
  6864. var loader = loaders[loaderName];
  6865. if (loader) {
  6866. loader.destroy();
  6867. }
  6868. }
  6869. this.loaders = {};
  6870. _EventHandler.prototype.destroy.call(this);
  6871. };
  6872. _proto.onFragLoading = function onFragLoading(data) {
  6873. var frag = data.frag,
  6874. type = frag.type,
  6875. loaders = this.loaders,
  6876. config = this.hls.config,
  6877. FragmentILoader = config.fLoader,
  6878. DefaultILoader = config.loader; // reset fragment state
  6879. frag.loaded = 0;
  6880. var loader = loaders[type];
  6881. if (loader) {
  6882. logger["logger"].warn("abort previous fragment loader for type: " + type);
  6883. loader.abort();
  6884. }
  6885. loader = loaders[type] = frag.loader = config.fLoader ? new FragmentILoader(config) : new DefaultILoader(config);
  6886. var loaderContext, loaderConfig, loaderCallbacks;
  6887. loaderContext = {
  6888. url: frag.url,
  6889. frag: frag,
  6890. responseType: 'arraybuffer',
  6891. progressData: false
  6892. };
  6893. var start = frag.byteRangeStartOffset,
  6894. end = frag.byteRangeEndOffset;
  6895. if (Object(number["isFiniteNumber"])(start) && Object(number["isFiniteNumber"])(end)) {
  6896. loaderContext.rangeStart = start;
  6897. loaderContext.rangeEnd = end;
  6898. }
  6899. loaderConfig = {
  6900. timeout: config.fragLoadingTimeOut,
  6901. maxRetry: 0,
  6902. retryDelay: 0,
  6903. maxRetryDelay: config.fragLoadingMaxRetryTimeout
  6904. };
  6905. loaderCallbacks = {
  6906. onSuccess: this.loadsuccess.bind(this),
  6907. onError: this.loaderror.bind(this),
  6908. onTimeout: this.loadtimeout.bind(this),
  6909. onProgress: this.loadprogress.bind(this)
  6910. };
  6911. loader.load(loaderContext, loaderConfig, loaderCallbacks);
  6912. };
  6913. _proto.loadsuccess = function loadsuccess(response, stats, context, networkDetails) {
  6914. if (networkDetails === void 0) {
  6915. networkDetails = null;
  6916. }
  6917. var payload = response.data,
  6918. frag = context.frag; // detach fragment loader on load success
  6919. frag.loader = undefined;
  6920. this.loaders[frag.type] = undefined;
  6921. this.hls.trigger(events["default"].FRAG_LOADED, {
  6922. payload: payload,
  6923. frag: frag,
  6924. stats: stats,
  6925. networkDetails: networkDetails
  6926. });
  6927. };
  6928. _proto.loaderror = function loaderror(response, context, networkDetails) {
  6929. if (networkDetails === void 0) {
  6930. networkDetails = null;
  6931. }
  6932. var frag = context.frag;
  6933. var loader = frag.loader;
  6934. if (loader) {
  6935. loader.abort();
  6936. }
  6937. this.loaders[frag.type] = undefined;
  6938. this.hls.trigger(events["default"].ERROR, {
  6939. type: errors["ErrorTypes"].NETWORK_ERROR,
  6940. details: errors["ErrorDetails"].FRAG_LOAD_ERROR,
  6941. fatal: false,
  6942. frag: context.frag,
  6943. response: response,
  6944. networkDetails: networkDetails
  6945. });
  6946. };
  6947. _proto.loadtimeout = function loadtimeout(stats, context, networkDetails) {
  6948. if (networkDetails === void 0) {
  6949. networkDetails = null;
  6950. }
  6951. var frag = context.frag;
  6952. var loader = frag.loader;
  6953. if (loader) {
  6954. loader.abort();
  6955. }
  6956. this.loaders[frag.type] = undefined;
  6957. this.hls.trigger(events["default"].ERROR, {
  6958. type: errors["ErrorTypes"].NETWORK_ERROR,
  6959. details: errors["ErrorDetails"].FRAG_LOAD_TIMEOUT,
  6960. fatal: false,
  6961. frag: context.frag,
  6962. networkDetails: networkDetails
  6963. });
  6964. } // data will be used for progressive parsing
  6965. ;
  6966. _proto.loadprogress = function loadprogress(stats, context, data, networkDetails) {
  6967. if (networkDetails === void 0) {
  6968. networkDetails = null;
  6969. }
  6970. // jshint ignore:line
  6971. var frag = context.frag;
  6972. frag.loaded = stats.loaded;
  6973. this.hls.trigger(events["default"].FRAG_LOAD_PROGRESS, {
  6974. frag: frag,
  6975. stats: stats,
  6976. networkDetails: networkDetails
  6977. });
  6978. };
  6979. return FragmentLoader;
  6980. }(event_handler);
  6981. /* harmony default export */ var fragment_loader = (fragment_loader_FragmentLoader);
  6982. // CONCATENATED MODULE: ./src/loader/key-loader.ts
  6983. function key_loader_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  6984. /*
  6985. * Decrypt key Loader
  6986. */
  6987. var key_loader_KeyLoader = /*#__PURE__*/function (_EventHandler) {
  6988. key_loader_inheritsLoose(KeyLoader, _EventHandler);
  6989. function KeyLoader(hls) {
  6990. var _this;
  6991. _this = _EventHandler.call(this, hls, events["default"].KEY_LOADING) || this;
  6992. _this.loaders = {};
  6993. _this.decryptkey = null;
  6994. _this.decrypturl = null;
  6995. return _this;
  6996. }
  6997. var _proto = KeyLoader.prototype;
  6998. _proto.destroy = function destroy() {
  6999. for (var loaderName in this.loaders) {
  7000. var loader = this.loaders[loaderName];
  7001. if (loader) {
  7002. loader.destroy();
  7003. }
  7004. }
  7005. this.loaders = {};
  7006. _EventHandler.prototype.destroy.call(this);
  7007. };
  7008. _proto.onKeyLoading = function onKeyLoading(data) {
  7009. var frag = data.frag;
  7010. var type = frag.type;
  7011. var loader = this.loaders[type];
  7012. if (!frag.decryptdata) {
  7013. logger["logger"].warn('Missing decryption data on fragment in onKeyLoading');
  7014. return;
  7015. } // Load the key if the uri is different from previous one, or if the decrypt key has not yet been retrieved
  7016. var uri = frag.decryptdata.uri;
  7017. if (uri !== this.decrypturl || this.decryptkey === null) {
  7018. var config = this.hls.config;
  7019. if (loader) {
  7020. logger["logger"].warn("abort previous key loader for type:" + type);
  7021. loader.abort();
  7022. }
  7023. if (!uri) {
  7024. logger["logger"].warn('key uri is falsy');
  7025. return;
  7026. }
  7027. frag.loader = this.loaders[type] = new config.loader(config);
  7028. this.decrypturl = uri;
  7029. this.decryptkey = null;
  7030. var loaderContext = {
  7031. url: uri,
  7032. frag: frag,
  7033. responseType: 'arraybuffer'
  7034. }; // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,
  7035. // key-loader will trigger an error and rely on stream-controller to handle retry logic.
  7036. // this will also align retry logic with fragment-loader
  7037. var loaderConfig = {
  7038. timeout: config.fragLoadingTimeOut,
  7039. maxRetry: 0,
  7040. retryDelay: config.fragLoadingRetryDelay,
  7041. maxRetryDelay: config.fragLoadingMaxRetryTimeout
  7042. };
  7043. var loaderCallbacks = {
  7044. onSuccess: this.loadsuccess.bind(this),
  7045. onError: this.loaderror.bind(this),
  7046. onTimeout: this.loadtimeout.bind(this)
  7047. };
  7048. frag.loader.load(loaderContext, loaderConfig, loaderCallbacks);
  7049. } else if (this.decryptkey) {
  7050. // Return the key if it's already been loaded
  7051. frag.decryptdata.key = this.decryptkey;
  7052. this.hls.trigger(events["default"].KEY_LOADED, {
  7053. frag: frag
  7054. });
  7055. }
  7056. };
  7057. _proto.loadsuccess = function loadsuccess(response, stats, context) {
  7058. var frag = context.frag;
  7059. if (!frag.decryptdata) {
  7060. logger["logger"].error('after key load, decryptdata unset');
  7061. return;
  7062. }
  7063. this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data); // detach fragment loader on load success
  7064. frag.loader = undefined;
  7065. delete this.loaders[frag.type];
  7066. this.hls.trigger(events["default"].KEY_LOADED, {
  7067. frag: frag
  7068. });
  7069. };
  7070. _proto.loaderror = function loaderror(response, context) {
  7071. var frag = context.frag;
  7072. var loader = frag.loader;
  7073. if (loader) {
  7074. loader.abort();
  7075. }
  7076. delete this.loaders[frag.type];
  7077. this.hls.trigger(events["default"].ERROR, {
  7078. type: errors["ErrorTypes"].NETWORK_ERROR,
  7079. details: errors["ErrorDetails"].KEY_LOAD_ERROR,
  7080. fatal: false,
  7081. frag: frag,
  7082. response: response
  7083. });
  7084. };
  7085. _proto.loadtimeout = function loadtimeout(stats, context) {
  7086. var frag = context.frag;
  7087. var loader = frag.loader;
  7088. if (loader) {
  7089. loader.abort();
  7090. }
  7091. delete this.loaders[frag.type];
  7092. this.hls.trigger(events["default"].ERROR, {
  7093. type: errors["ErrorTypes"].NETWORK_ERROR,
  7094. details: errors["ErrorDetails"].KEY_LOAD_TIMEOUT,
  7095. fatal: false,
  7096. frag: frag
  7097. });
  7098. };
  7099. return KeyLoader;
  7100. }(event_handler);
  7101. /* harmony default export */ var key_loader = (key_loader_KeyLoader);
  7102. // CONCATENATED MODULE: ./src/controller/fragment-tracker.js
  7103. function fragment_tracker_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  7104. var FragmentState = {
  7105. NOT_LOADED: 'NOT_LOADED',
  7106. APPENDING: 'APPENDING',
  7107. PARTIAL: 'PARTIAL',
  7108. OK: 'OK'
  7109. };
  7110. var fragment_tracker_FragmentTracker = /*#__PURE__*/function (_EventHandler) {
  7111. fragment_tracker_inheritsLoose(FragmentTracker, _EventHandler);
  7112. function FragmentTracker(hls) {
  7113. var _this;
  7114. _this = _EventHandler.call(this, hls, events["default"].BUFFER_APPENDED, events["default"].FRAG_BUFFERED, events["default"].FRAG_LOADED) || this;
  7115. _this.bufferPadding = 0.2;
  7116. _this.fragments = Object.create(null);
  7117. _this.timeRanges = Object.create(null);
  7118. _this.config = hls.config;
  7119. return _this;
  7120. }
  7121. var _proto = FragmentTracker.prototype;
  7122. _proto.destroy = function destroy() {
  7123. this.fragments = Object.create(null);
  7124. this.timeRanges = Object.create(null);
  7125. this.config = null;
  7126. event_handler.prototype.destroy.call(this);
  7127. _EventHandler.prototype.destroy.call(this);
  7128. }
  7129. /**
  7130. * Return a Fragment that match the position and levelType.
  7131. * If not found any Fragment, return null
  7132. * @param {number} position
  7133. * @param {LevelType} levelType
  7134. * @returns {Fragment|null}
  7135. */
  7136. ;
  7137. _proto.getBufferedFrag = function getBufferedFrag(position, levelType) {
  7138. var fragments = this.fragments;
  7139. var bufferedFrags = Object.keys(fragments).filter(function (key) {
  7140. var fragmentEntity = fragments[key];
  7141. if (fragmentEntity.body.type !== levelType) {
  7142. return false;
  7143. }
  7144. if (!fragmentEntity.buffered) {
  7145. return false;
  7146. }
  7147. var frag = fragmentEntity.body;
  7148. return frag.startPTS <= position && position <= frag.endPTS;
  7149. });
  7150. if (bufferedFrags.length === 0) {
  7151. return null;
  7152. } else {
  7153. // https://github.com/video-dev/hls.js/pull/1545#discussion_r166229566
  7154. var bufferedFragKey = bufferedFrags.pop();
  7155. return fragments[bufferedFragKey].body;
  7156. }
  7157. }
  7158. /**
  7159. * Partial fragments effected by coded frame eviction will be removed
  7160. * The browser will unload parts of the buffer to free up memory for new buffer data
  7161. * Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)
  7162. * @param {String} elementaryStream The elementaryStream of media this is (eg. video/audio)
  7163. * @param {TimeRanges} timeRange TimeRange object from a sourceBuffer
  7164. */
  7165. ;
  7166. _proto.detectEvictedFragments = function detectEvictedFragments(elementaryStream, timeRange) {
  7167. var _this2 = this;
  7168. // Check if any flagged fragments have been unloaded
  7169. Object.keys(this.fragments).forEach(function (key) {
  7170. var fragmentEntity = _this2.fragments[key];
  7171. if (!fragmentEntity || !fragmentEntity.buffered) {
  7172. return;
  7173. }
  7174. var esData = fragmentEntity.range[elementaryStream];
  7175. if (!esData) {
  7176. return;
  7177. }
  7178. var fragmentTimes = esData.time;
  7179. for (var i = 0; i < fragmentTimes.length; i++) {
  7180. var time = fragmentTimes[i];
  7181. if (!_this2.isTimeBuffered(time.startPTS, time.endPTS, timeRange)) {
  7182. // Unregister partial fragment as it needs to load again to be reused
  7183. _this2.removeFragment(fragmentEntity.body);
  7184. break;
  7185. }
  7186. }
  7187. });
  7188. }
  7189. /**
  7190. * Checks if the fragment passed in is loaded in the buffer properly
  7191. * Partially loaded fragments will be registered as a partial fragment
  7192. * @param {Object} fragment Check the fragment against all sourceBuffers loaded
  7193. */
  7194. ;
  7195. _proto.detectPartialFragments = function detectPartialFragments(fragment) {
  7196. var _this3 = this;
  7197. var fragKey = this.getFragmentKey(fragment);
  7198. var fragmentEntity = this.fragments[fragKey];
  7199. if (fragmentEntity) {
  7200. fragmentEntity.buffered = true;
  7201. Object.keys(this.timeRanges).forEach(function (elementaryStream) {
  7202. if (fragment.hasElementaryStream(elementaryStream)) {
  7203. var timeRange = _this3.timeRanges[elementaryStream]; // Check for malformed fragments
  7204. // Gaps need to be calculated for each elementaryStream
  7205. fragmentEntity.range[elementaryStream] = _this3.getBufferedTimes(fragment.startPTS, fragment.endPTS, timeRange);
  7206. }
  7207. });
  7208. }
  7209. };
  7210. _proto.getBufferedTimes = function getBufferedTimes(startPTS, endPTS, timeRange) {
  7211. var fragmentTimes = [];
  7212. var startTime, endTime;
  7213. var fragmentPartial = false;
  7214. for (var i = 0; i < timeRange.length; i++) {
  7215. startTime = timeRange.start(i) - this.bufferPadding;
  7216. endTime = timeRange.end(i) + this.bufferPadding;
  7217. if (startPTS >= startTime && endPTS <= endTime) {
  7218. // Fragment is entirely contained in buffer
  7219. // No need to check the other timeRange times since it's completely playable
  7220. fragmentTimes.push({
  7221. startPTS: Math.max(startPTS, timeRange.start(i)),
  7222. endPTS: Math.min(endPTS, timeRange.end(i))
  7223. });
  7224. break;
  7225. } else if (startPTS < endTime && endPTS > startTime) {
  7226. // Check for intersection with buffer
  7227. // Get playable sections of the fragment
  7228. fragmentTimes.push({
  7229. startPTS: Math.max(startPTS, timeRange.start(i)),
  7230. endPTS: Math.min(endPTS, timeRange.end(i))
  7231. });
  7232. fragmentPartial = true;
  7233. } else if (endPTS <= startTime) {
  7234. // No need to check the rest of the timeRange as it is in order
  7235. break;
  7236. }
  7237. }
  7238. return {
  7239. time: fragmentTimes,
  7240. partial: fragmentPartial
  7241. };
  7242. };
  7243. _proto.getFragmentKey = function getFragmentKey(fragment) {
  7244. return fragment.type + "_" + fragment.level + "_" + fragment.urlId + "_" + fragment.sn;
  7245. }
  7246. /**
  7247. * Gets the partial fragment for a certain time
  7248. * @param {Number} time
  7249. * @returns {Object} fragment Returns a partial fragment at a time or null if there is no partial fragment
  7250. */
  7251. ;
  7252. _proto.getPartialFragment = function getPartialFragment(time) {
  7253. var _this4 = this;
  7254. var timePadding, startTime, endTime;
  7255. var bestFragment = null;
  7256. var bestOverlap = 0;
  7257. Object.keys(this.fragments).forEach(function (key) {
  7258. var fragmentEntity = _this4.fragments[key];
  7259. if (_this4.isPartial(fragmentEntity)) {
  7260. startTime = fragmentEntity.body.startPTS - _this4.bufferPadding;
  7261. endTime = fragmentEntity.body.endPTS + _this4.bufferPadding;
  7262. if (time >= startTime && time <= endTime) {
  7263. // Use the fragment that has the most padding from start and end time
  7264. timePadding = Math.min(time - startTime, endTime - time);
  7265. if (bestOverlap <= timePadding) {
  7266. bestFragment = fragmentEntity.body;
  7267. bestOverlap = timePadding;
  7268. }
  7269. }
  7270. }
  7271. });
  7272. return bestFragment;
  7273. }
  7274. /**
  7275. * @param {Object} fragment The fragment to check
  7276. * @returns {String} Returns the fragment state when a fragment never loaded or if it partially loaded
  7277. */
  7278. ;
  7279. _proto.getState = function getState(fragment) {
  7280. var fragKey = this.getFragmentKey(fragment);
  7281. var fragmentEntity = this.fragments[fragKey];
  7282. var state = FragmentState.NOT_LOADED;
  7283. if (fragmentEntity !== undefined) {
  7284. if (!fragmentEntity.buffered) {
  7285. state = FragmentState.APPENDING;
  7286. } else if (this.isPartial(fragmentEntity) === true) {
  7287. state = FragmentState.PARTIAL;
  7288. } else {
  7289. state = FragmentState.OK;
  7290. }
  7291. }
  7292. return state;
  7293. };
  7294. _proto.isPartial = function isPartial(fragmentEntity) {
  7295. return fragmentEntity.buffered === true && (fragmentEntity.range.video !== undefined && fragmentEntity.range.video.partial === true || fragmentEntity.range.audio !== undefined && fragmentEntity.range.audio.partial === true);
  7296. };
  7297. _proto.isTimeBuffered = function isTimeBuffered(startPTS, endPTS, timeRange) {
  7298. var startTime, endTime;
  7299. for (var i = 0; i < timeRange.length; i++) {
  7300. startTime = timeRange.start(i) - this.bufferPadding;
  7301. endTime = timeRange.end(i) + this.bufferPadding;
  7302. if (startPTS >= startTime && endPTS <= endTime) {
  7303. return true;
  7304. }
  7305. if (endPTS <= startTime) {
  7306. // No need to check the rest of the timeRange as it is in order
  7307. return false;
  7308. }
  7309. }
  7310. return false;
  7311. }
  7312. /**
  7313. * Fires when a fragment loading is completed
  7314. */
  7315. ;
  7316. _proto.onFragLoaded = function onFragLoaded(e) {
  7317. var fragment = e.frag; // don't track initsegment (for which sn is not a number)
  7318. // don't track frags used for bitrateTest, they're irrelevant.
  7319. if (!Object(number["isFiniteNumber"])(fragment.sn) || fragment.bitrateTest) {
  7320. return;
  7321. }
  7322. this.fragments[this.getFragmentKey(fragment)] = {
  7323. body: fragment,
  7324. range: Object.create(null),
  7325. buffered: false
  7326. };
  7327. }
  7328. /**
  7329. * Fires when the buffer is updated
  7330. */
  7331. ;
  7332. _proto.onBufferAppended = function onBufferAppended(e) {
  7333. var _this5 = this;
  7334. // Store the latest timeRanges loaded in the buffer
  7335. this.timeRanges = e.timeRanges;
  7336. Object.keys(this.timeRanges).forEach(function (elementaryStream) {
  7337. var timeRange = _this5.timeRanges[elementaryStream];
  7338. _this5.detectEvictedFragments(elementaryStream, timeRange);
  7339. });
  7340. }
  7341. /**
  7342. * Fires after a fragment has been loaded into the source buffer
  7343. */
  7344. ;
  7345. _proto.onFragBuffered = function onFragBuffered(e) {
  7346. this.detectPartialFragments(e.frag);
  7347. }
  7348. /**
  7349. * Return true if fragment tracker has the fragment.
  7350. * @param {Object} fragment
  7351. * @returns {boolean}
  7352. */
  7353. ;
  7354. _proto.hasFragment = function hasFragment(fragment) {
  7355. var fragKey = this.getFragmentKey(fragment);
  7356. return this.fragments[fragKey] !== undefined;
  7357. }
  7358. /**
  7359. * Remove a fragment from fragment tracker until it is loaded again
  7360. * @param {Object} fragment The fragment to remove
  7361. */
  7362. ;
  7363. _proto.removeFragment = function removeFragment(fragment) {
  7364. var fragKey = this.getFragmentKey(fragment);
  7365. delete this.fragments[fragKey];
  7366. }
  7367. /**
  7368. * Remove all fragments from fragment tracker.
  7369. */
  7370. ;
  7371. _proto.removeAllFragments = function removeAllFragments() {
  7372. this.fragments = Object.create(null);
  7373. };
  7374. return FragmentTracker;
  7375. }(event_handler);
  7376. // CONCATENATED MODULE: ./src/utils/binary-search.ts
  7377. var BinarySearch = {
  7378. /**
  7379. * Searches for an item in an array which matches a certain condition.
  7380. * This requires the condition to only match one item in the array,
  7381. * and for the array to be ordered.
  7382. *
  7383. * @param {Array<T>} list The array to search.
  7384. * @param {BinarySearchComparison<T>} comparisonFn
  7385. * Called and provided a candidate item as the first argument.
  7386. * Should return:
  7387. * > -1 if the item should be located at a lower index than the provided item.
  7388. * > 1 if the item should be located at a higher index than the provided item.
  7389. * > 0 if the item is the item you're looking for.
  7390. *
  7391. * @return {T | null} The object if it is found or null otherwise.
  7392. */
  7393. search: function search(list, comparisonFn) {
  7394. var minIndex = 0;
  7395. var maxIndex = list.length - 1;
  7396. var currentIndex = null;
  7397. var currentElement = null;
  7398. while (minIndex <= maxIndex) {
  7399. currentIndex = (minIndex + maxIndex) / 2 | 0;
  7400. currentElement = list[currentIndex];
  7401. var comparisonResult = comparisonFn(currentElement);
  7402. if (comparisonResult > 0) {
  7403. minIndex = currentIndex + 1;
  7404. } else if (comparisonResult < 0) {
  7405. maxIndex = currentIndex - 1;
  7406. } else {
  7407. return currentElement;
  7408. }
  7409. }
  7410. return null;
  7411. }
  7412. };
  7413. /* harmony default export */ var binary_search = (BinarySearch);
  7414. // CONCATENATED MODULE: ./src/utils/buffer-helper.ts
  7415. /**
  7416. * @module BufferHelper
  7417. *
  7418. * Providing methods dealing with buffer length retrieval for example.
  7419. *
  7420. * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.
  7421. *
  7422. * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered
  7423. */
  7424. var BufferHelper = /*#__PURE__*/function () {
  7425. function BufferHelper() {}
  7426. /**
  7427. * Return true if `media`'s buffered include `position`
  7428. * @param {Bufferable} media
  7429. * @param {number} position
  7430. * @returns {boolean}
  7431. */
  7432. BufferHelper.isBuffered = function isBuffered(media, position) {
  7433. try {
  7434. if (media) {
  7435. var buffered = media.buffered;
  7436. for (var i = 0; i < buffered.length; i++) {
  7437. if (position >= buffered.start(i) && position <= buffered.end(i)) {
  7438. return true;
  7439. }
  7440. }
  7441. }
  7442. } catch (error) {// this is to catch
  7443. // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
  7444. // This SourceBuffer has been removed from the parent media source
  7445. }
  7446. return false;
  7447. };
  7448. BufferHelper.bufferInfo = function bufferInfo(media, pos, maxHoleDuration) {
  7449. try {
  7450. if (media) {
  7451. var vbuffered = media.buffered;
  7452. var buffered = [];
  7453. var i;
  7454. for (i = 0; i < vbuffered.length; i++) {
  7455. buffered.push({
  7456. start: vbuffered.start(i),
  7457. end: vbuffered.end(i)
  7458. });
  7459. }
  7460. return this.bufferedInfo(buffered, pos, maxHoleDuration);
  7461. }
  7462. } catch (error) {// this is to catch
  7463. // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
  7464. // This SourceBuffer has been removed from the parent media source
  7465. }
  7466. return {
  7467. len: 0,
  7468. start: pos,
  7469. end: pos,
  7470. nextStart: undefined
  7471. };
  7472. };
  7473. BufferHelper.bufferedInfo = function bufferedInfo(buffered, pos, maxHoleDuration) {
  7474. // sort on buffer.start/smaller end (IE does not always return sorted buffered range)
  7475. buffered.sort(function (a, b) {
  7476. var diff = a.start - b.start;
  7477. if (diff) {
  7478. return diff;
  7479. } else {
  7480. return b.end - a.end;
  7481. }
  7482. });
  7483. var buffered2 = [];
  7484. if (maxHoleDuration) {
  7485. // there might be some small holes between buffer time range
  7486. // consider that holes smaller than maxHoleDuration are irrelevant and build another
  7487. // buffer time range representations that discards those holes
  7488. for (var i = 0; i < buffered.length; i++) {
  7489. var buf2len = buffered2.length;
  7490. if (buf2len) {
  7491. var buf2end = buffered2[buf2len - 1].end; // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)
  7492. if (buffered[i].start - buf2end < maxHoleDuration) {
  7493. // merge overlapping time ranges
  7494. // update lastRange.end only if smaller than item.end
  7495. // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)
  7496. // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])
  7497. if (buffered[i].end > buf2end) {
  7498. buffered2[buf2len - 1].end = buffered[i].end;
  7499. }
  7500. } else {
  7501. // big hole
  7502. buffered2.push(buffered[i]);
  7503. }
  7504. } else {
  7505. // first value
  7506. buffered2.push(buffered[i]);
  7507. }
  7508. }
  7509. } else {
  7510. buffered2 = buffered;
  7511. }
  7512. var bufferLen = 0; // bufferStartNext can possibly be undefined based on the conditional logic below
  7513. var bufferStartNext; // bufferStart and bufferEnd are buffer boundaries around current video position
  7514. var bufferStart = pos;
  7515. var bufferEnd = pos;
  7516. for (var _i = 0; _i < buffered2.length; _i++) {
  7517. var start = buffered2[_i].start,
  7518. end = buffered2[_i].end; // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));
  7519. if (pos + maxHoleDuration >= start && pos < end) {
  7520. // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
  7521. bufferStart = start;
  7522. bufferEnd = end;
  7523. bufferLen = bufferEnd - pos;
  7524. } else if (pos + maxHoleDuration < start) {
  7525. bufferStartNext = start;
  7526. break;
  7527. }
  7528. }
  7529. return {
  7530. len: bufferLen,
  7531. start: bufferStart,
  7532. end: bufferEnd,
  7533. nextStart: bufferStartNext
  7534. };
  7535. };
  7536. return BufferHelper;
  7537. }();
  7538. // EXTERNAL MODULE: ./node_modules/eventemitter3/index.js
  7539. var eventemitter3 = __webpack_require__("./node_modules/eventemitter3/index.js");
  7540. // EXTERNAL MODULE: ./node_modules/webworkify-webpack/index.js
  7541. var webworkify_webpack = __webpack_require__("./node_modules/webworkify-webpack/index.js");
  7542. // EXTERNAL MODULE: ./src/demux/demuxer-inline.js + 12 modules
  7543. var demuxer_inline = __webpack_require__("./src/demux/demuxer-inline.js");
  7544. // CONCATENATED MODULE: ./src/utils/mediasource-helper.ts
  7545. /**
  7546. * MediaSource helper
  7547. */
  7548. function getMediaSource() {
  7549. return window.MediaSource || window.WebKitMediaSource;
  7550. }
  7551. // EXTERNAL MODULE: ./src/utils/get-self-scope.js
  7552. var get_self_scope = __webpack_require__("./src/utils/get-self-scope.js");
  7553. // CONCATENATED MODULE: ./src/observer.ts
  7554. function observer_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  7555. /**
  7556. * Simple adapter sub-class of Nodejs-like EventEmitter.
  7557. */
  7558. var Observer = /*#__PURE__*/function (_EventEmitter) {
  7559. observer_inheritsLoose(Observer, _EventEmitter);
  7560. function Observer() {
  7561. return _EventEmitter.apply(this, arguments) || this;
  7562. }
  7563. var _proto = Observer.prototype;
  7564. /**
  7565. * We simply want to pass along the event-name itself
  7566. * in every call to a handler, which is the purpose of our `trigger` method
  7567. * extending the standard API.
  7568. */
  7569. _proto.trigger = function trigger(event) {
  7570. for (var _len = arguments.length, data = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  7571. data[_key - 1] = arguments[_key];
  7572. }
  7573. this.emit.apply(this, [event, event].concat(data));
  7574. };
  7575. return Observer;
  7576. }(eventemitter3["EventEmitter"]);
  7577. // CONCATENATED MODULE: ./src/demux/demuxer.js
  7578. // see https://stackoverflow.com/a/11237259/589493
  7579. var global = Object(get_self_scope["getSelfScope"])(); // safeguard for code that might run both on worker and main thread
  7580. var demuxer_MediaSource = getMediaSource() || {
  7581. isTypeSupported: function isTypeSupported() {
  7582. return false;
  7583. }
  7584. };
  7585. var demuxer_Demuxer = /*#__PURE__*/function () {
  7586. function Demuxer(hls, id) {
  7587. var _this = this;
  7588. this.hls = hls;
  7589. this.id = id;
  7590. var observer = this.observer = new Observer();
  7591. var config = hls.config;
  7592. var forwardMessage = function forwardMessage(ev, data) {
  7593. data = data || {};
  7594. data.frag = _this.frag;
  7595. data.id = _this.id;
  7596. hls.trigger(ev, data);
  7597. }; // forward events to main thread
  7598. observer.on(events["default"].FRAG_DECRYPTED, forwardMessage);
  7599. observer.on(events["default"].FRAG_PARSING_INIT_SEGMENT, forwardMessage);
  7600. observer.on(events["default"].FRAG_PARSING_DATA, forwardMessage);
  7601. observer.on(events["default"].FRAG_PARSED, forwardMessage);
  7602. observer.on(events["default"].ERROR, forwardMessage);
  7603. observer.on(events["default"].FRAG_PARSING_METADATA, forwardMessage);
  7604. observer.on(events["default"].FRAG_PARSING_USERDATA, forwardMessage);
  7605. observer.on(events["default"].INIT_PTS_FOUND, forwardMessage);
  7606. var typeSupported = {
  7607. mp4: demuxer_MediaSource.isTypeSupported('video/mp4'),
  7608. mpeg: demuxer_MediaSource.isTypeSupported('audio/mpeg'),
  7609. mp3: demuxer_MediaSource.isTypeSupported('audio/mp4; codecs="mp3"')
  7610. }; // navigator.vendor is not always available in Web Worker
  7611. // refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator
  7612. var vendor = navigator.vendor;
  7613. if (config.enableWorker && typeof Worker !== 'undefined') {
  7614. logger["logger"].log('demuxing in webworker');
  7615. var w;
  7616. try {
  7617. w = this.w = webworkify_webpack(/*require.resolve*/(/*! ../demux/demuxer-worker.js */ "./src/demux/demuxer-worker.js"));
  7618. this.onwmsg = this.onWorkerMessage.bind(this);
  7619. w.addEventListener('message', this.onwmsg);
  7620. w.onerror = function (event) {
  7621. hls.trigger(events["default"].ERROR, {
  7622. type: errors["ErrorTypes"].OTHER_ERROR,
  7623. details: errors["ErrorDetails"].INTERNAL_EXCEPTION,
  7624. fatal: true,
  7625. event: 'demuxerWorker',
  7626. err: {
  7627. message: event.message + ' (' + event.filename + ':' + event.lineno + ')'
  7628. }
  7629. });
  7630. };
  7631. w.postMessage({
  7632. cmd: 'init',
  7633. typeSupported: typeSupported,
  7634. vendor: vendor,
  7635. id: id,
  7636. config: JSON.stringify(config)
  7637. });
  7638. } catch (err) {
  7639. logger["logger"].warn('Error in worker:', err);
  7640. logger["logger"].error('Error while initializing DemuxerWorker, fallback on DemuxerInline');
  7641. if (w) {
  7642. // revoke the Object URL that was used to create demuxer worker, so as not to leak it
  7643. global.URL.revokeObjectURL(w.objectURL);
  7644. }
  7645. this.demuxer = new demuxer_inline["default"](observer, typeSupported, config, vendor);
  7646. this.w = undefined;
  7647. }
  7648. } else {
  7649. this.demuxer = new demuxer_inline["default"](observer, typeSupported, config, vendor);
  7650. }
  7651. }
  7652. var _proto = Demuxer.prototype;
  7653. _proto.destroy = function destroy() {
  7654. var w = this.w;
  7655. if (w) {
  7656. w.removeEventListener('message', this.onwmsg);
  7657. w.terminate();
  7658. this.w = null;
  7659. } else {
  7660. var demuxer = this.demuxer;
  7661. if (demuxer) {
  7662. demuxer.destroy();
  7663. this.demuxer = null;
  7664. }
  7665. }
  7666. var observer = this.observer;
  7667. if (observer) {
  7668. observer.removeAllListeners();
  7669. this.observer = null;
  7670. }
  7671. };
  7672. _proto.push = function push(data, initSegment, audioCodec, videoCodec, frag, duration, accurateTimeOffset, defaultInitPTS) {
  7673. var w = this.w;
  7674. var timeOffset = Object(number["isFiniteNumber"])(frag.startPTS) ? frag.startPTS : frag.start;
  7675. var decryptdata = frag.decryptdata;
  7676. var lastFrag = this.frag;
  7677. var discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
  7678. var trackSwitch = !(lastFrag && frag.level === lastFrag.level);
  7679. var nextSN = lastFrag && frag.sn === lastFrag.sn + 1;
  7680. var contiguous = !trackSwitch && nextSN;
  7681. if (discontinuity) {
  7682. logger["logger"].log(this.id + ":discontinuity detected");
  7683. }
  7684. if (trackSwitch) {
  7685. logger["logger"].log(this.id + ":switch detected");
  7686. }
  7687. this.frag = frag;
  7688. if (w) {
  7689. // post fragment payload as transferable objects for ArrayBuffer (no copy)
  7690. w.postMessage({
  7691. cmd: 'demux',
  7692. data: data,
  7693. decryptdata: decryptdata,
  7694. initSegment: initSegment,
  7695. audioCodec: audioCodec,
  7696. videoCodec: videoCodec,
  7697. timeOffset: timeOffset,
  7698. discontinuity: discontinuity,
  7699. trackSwitch: trackSwitch,
  7700. contiguous: contiguous,
  7701. duration: duration,
  7702. accurateTimeOffset: accurateTimeOffset,
  7703. defaultInitPTS: defaultInitPTS
  7704. }, data instanceof ArrayBuffer ? [data] : []);
  7705. } else {
  7706. var demuxer = this.demuxer;
  7707. if (demuxer) {
  7708. demuxer.push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
  7709. }
  7710. }
  7711. };
  7712. _proto.onWorkerMessage = function onWorkerMessage(ev) {
  7713. var data = ev.data,
  7714. hls = this.hls;
  7715. switch (data.event) {
  7716. case 'init':
  7717. // revoke the Object URL that was used to create demuxer worker, so as not to leak it
  7718. global.URL.revokeObjectURL(this.w.objectURL);
  7719. break;
  7720. // special case for FRAG_PARSING_DATA: data1 and data2 are transferable objects
  7721. case events["default"].FRAG_PARSING_DATA:
  7722. data.data.data1 = new Uint8Array(data.data1);
  7723. if (data.data2) {
  7724. data.data.data2 = new Uint8Array(data.data2);
  7725. }
  7726. /* falls through */
  7727. default:
  7728. data.data = data.data || {};
  7729. data.data.frag = this.frag;
  7730. data.data.id = this.id;
  7731. hls.trigger(data.event, data.data);
  7732. break;
  7733. }
  7734. };
  7735. return Demuxer;
  7736. }();
  7737. /* harmony default export */ var demux_demuxer = (demuxer_Demuxer);
  7738. // CONCATENATED MODULE: ./src/controller/level-helper.js
  7739. /**
  7740. * @module LevelHelper
  7741. *
  7742. * Providing methods dealing with playlist sliding and drift
  7743. *
  7744. * TODO: Create an actual `Level` class/model that deals with all this logic in an object-oriented-manner.
  7745. *
  7746. * */
  7747. function addGroupId(level, type, id) {
  7748. switch (type) {
  7749. case 'audio':
  7750. if (!level.audioGroupIds) {
  7751. level.audioGroupIds = [];
  7752. }
  7753. level.audioGroupIds.push(id);
  7754. break;
  7755. case 'text':
  7756. if (!level.textGroupIds) {
  7757. level.textGroupIds = [];
  7758. }
  7759. level.textGroupIds.push(id);
  7760. break;
  7761. }
  7762. }
  7763. function updatePTS(fragments, fromIdx, toIdx) {
  7764. var fragFrom = fragments[fromIdx],
  7765. fragTo = fragments[toIdx],
  7766. fragToPTS = fragTo.startPTS; // if we know startPTS[toIdx]
  7767. if (Object(number["isFiniteNumber"])(fragToPTS)) {
  7768. // update fragment duration.
  7769. // it helps to fix drifts between playlist reported duration and fragment real duration
  7770. if (toIdx > fromIdx) {
  7771. fragFrom.duration = fragToPTS - fragFrom.start;
  7772. if (fragFrom.duration < 0) {
  7773. logger["logger"].warn("negative duration computed for frag " + fragFrom.sn + ",level " + fragFrom.level + ", there should be some duration drift between playlist and fragment!");
  7774. }
  7775. } else {
  7776. fragTo.duration = fragFrom.start - fragToPTS;
  7777. if (fragTo.duration < 0) {
  7778. logger["logger"].warn("negative duration computed for frag " + fragTo.sn + ",level " + fragTo.level + ", there should be some duration drift between playlist and fragment!");
  7779. }
  7780. }
  7781. } else {
  7782. // we dont know startPTS[toIdx]
  7783. if (toIdx > fromIdx) {
  7784. var contiguous = fragFrom.cc === fragTo.cc;
  7785. fragTo.start = fragFrom.start + (contiguous && fragFrom.minEndPTS ? fragFrom.minEndPTS - fragFrom.start : fragFrom.duration);
  7786. } else {
  7787. fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);
  7788. }
  7789. }
  7790. }
  7791. function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
  7792. // update frag PTS/DTS
  7793. var maxStartPTS = startPTS;
  7794. var minEndPTS = endPTS;
  7795. if (Object(number["isFiniteNumber"])(frag.startPTS)) {
  7796. // delta PTS between audio and video
  7797. var deltaPTS = Math.abs(frag.startPTS - startPTS);
  7798. if (!Object(number["isFiniteNumber"])(frag.deltaPTS)) {
  7799. frag.deltaPTS = deltaPTS;
  7800. } else {
  7801. frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
  7802. }
  7803. maxStartPTS = Math.max(startPTS, frag.startPTS);
  7804. startPTS = Math.min(startPTS, frag.startPTS);
  7805. minEndPTS = Math.min(endPTS, frag.endPTS);
  7806. endPTS = Math.max(endPTS, frag.endPTS);
  7807. startDTS = Math.min(startDTS, frag.startDTS);
  7808. endDTS = Math.max(endDTS, frag.endDTS);
  7809. }
  7810. var drift = startPTS - frag.start;
  7811. frag.start = frag.startPTS = startPTS;
  7812. frag.maxStartPTS = maxStartPTS;
  7813. frag.endPTS = endPTS;
  7814. frag.minEndPTS = minEndPTS;
  7815. frag.startDTS = startDTS;
  7816. frag.endDTS = endDTS;
  7817. frag.duration = endPTS - startPTS;
  7818. var sn = frag.sn; // exit if sn out of range
  7819. if (!details || sn < details.startSN || sn > details.endSN) {
  7820. return 0;
  7821. }
  7822. var fragIdx, fragments, i;
  7823. fragIdx = sn - details.startSN;
  7824. fragments = details.fragments; // update frag reference in fragments array
  7825. // rationale is that fragments array might not contain this frag object.
  7826. // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()
  7827. // if we don't update frag, we won't be able to propagate PTS info on the playlist
  7828. // resulting in invalid sliding computation
  7829. fragments[fragIdx] = frag; // adjust fragment PTS/duration from seqnum-1 to frag 0
  7830. for (i = fragIdx; i > 0; i--) {
  7831. updatePTS(fragments, i, i - 1);
  7832. } // adjust fragment PTS/duration from seqnum to last frag
  7833. for (i = fragIdx; i < fragments.length - 1; i++) {
  7834. updatePTS(fragments, i, i + 1);
  7835. }
  7836. details.PTSKnown = true;
  7837. return drift;
  7838. }
  7839. function mergeDetails(oldDetails, newDetails) {
  7840. // potentially retrieve cached initsegment
  7841. if (newDetails.initSegment && oldDetails.initSegment) {
  7842. newDetails.initSegment = oldDetails.initSegment;
  7843. } // check if old/new playlists have fragments in common
  7844. // loop through overlapping SN and update startPTS , cc, and duration if any found
  7845. var ccOffset = 0;
  7846. var PTSFrag;
  7847. mapFragmentIntersection(oldDetails, newDetails, function (oldFrag, newFrag) {
  7848. ccOffset = oldFrag.cc - newFrag.cc;
  7849. if (Object(number["isFiniteNumber"])(oldFrag.startPTS)) {
  7850. newFrag.start = newFrag.startPTS = oldFrag.startPTS;
  7851. newFrag.endPTS = oldFrag.endPTS;
  7852. newFrag.duration = oldFrag.duration;
  7853. newFrag.backtracked = oldFrag.backtracked;
  7854. newFrag.dropped = oldFrag.dropped;
  7855. PTSFrag = newFrag;
  7856. } // PTS is known when there are overlapping segments
  7857. newDetails.PTSKnown = true;
  7858. });
  7859. if (!newDetails.PTSKnown) {
  7860. return;
  7861. }
  7862. if (ccOffset) {
  7863. logger["logger"].log('discontinuity sliding from playlist, take drift into account');
  7864. var newFragments = newDetails.fragments;
  7865. for (var i = 0; i < newFragments.length; i++) {
  7866. newFragments[i].cc += ccOffset;
  7867. }
  7868. } // if at least one fragment contains PTS info, recompute PTS information for all fragments
  7869. if (PTSFrag) {
  7870. updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
  7871. } else {
  7872. // ensure that delta is within oldFragments range
  7873. // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])
  7874. // in that case we also need to adjust start offset of all fragments
  7875. adjustSliding(oldDetails, newDetails);
  7876. } // if we are here, it means we have fragments overlapping between
  7877. // old and new level. reliable PTS info is thus relying on old level
  7878. newDetails.PTSKnown = oldDetails.PTSKnown;
  7879. }
  7880. function mergeSubtitlePlaylists(oldPlaylist, newPlaylist, referenceStart) {
  7881. if (referenceStart === void 0) {
  7882. referenceStart = 0;
  7883. }
  7884. var lastIndex = -1;
  7885. mapFragmentIntersection(oldPlaylist, newPlaylist, function (oldFrag, newFrag, index) {
  7886. newFrag.start = oldFrag.start;
  7887. lastIndex = index;
  7888. });
  7889. var frags = newPlaylist.fragments;
  7890. if (lastIndex < 0) {
  7891. frags.forEach(function (frag) {
  7892. frag.start += referenceStart;
  7893. });
  7894. return;
  7895. }
  7896. for (var i = lastIndex + 1; i < frags.length; i++) {
  7897. frags[i].start = frags[i - 1].start + frags[i - 1].duration;
  7898. }
  7899. }
  7900. function mapFragmentIntersection(oldPlaylist, newPlaylist, intersectionFn) {
  7901. if (!oldPlaylist || !newPlaylist) {
  7902. return;
  7903. }
  7904. var start = Math.max(oldPlaylist.startSN, newPlaylist.startSN) - newPlaylist.startSN;
  7905. var end = Math.min(oldPlaylist.endSN, newPlaylist.endSN) - newPlaylist.startSN;
  7906. var delta = newPlaylist.startSN - oldPlaylist.startSN;
  7907. for (var i = start; i <= end; i++) {
  7908. var oldFrag = oldPlaylist.fragments[delta + i];
  7909. var newFrag = newPlaylist.fragments[i];
  7910. if (!oldFrag || !newFrag) {
  7911. break;
  7912. }
  7913. intersectionFn(oldFrag, newFrag, i);
  7914. }
  7915. }
  7916. function adjustSliding(oldPlaylist, newPlaylist) {
  7917. var delta = newPlaylist.startSN - oldPlaylist.startSN;
  7918. var oldFragments = oldPlaylist.fragments;
  7919. var newFragments = newPlaylist.fragments;
  7920. if (delta < 0 || delta > oldFragments.length) {
  7921. return;
  7922. }
  7923. for (var i = 0; i < newFragments.length; i++) {
  7924. newFragments[i].start += oldFragments[delta].start;
  7925. }
  7926. }
  7927. function computeReloadInterval(currentPlaylist, newPlaylist, lastRequestTime) {
  7928. var reloadInterval = 1000 * (newPlaylist.averagetargetduration ? newPlaylist.averagetargetduration : newPlaylist.targetduration);
  7929. var minReloadInterval = reloadInterval / 2;
  7930. if (currentPlaylist && newPlaylist.endSN === currentPlaylist.endSN) {
  7931. // follow HLS Spec, If the client reloads a Playlist file and finds that it has not
  7932. // changed then it MUST wait for a period of one-half the target
  7933. // duration before retrying.
  7934. reloadInterval = minReloadInterval;
  7935. }
  7936. if (lastRequestTime) {
  7937. reloadInterval = Math.max(minReloadInterval, reloadInterval - (window.performance.now() - lastRequestTime));
  7938. } // in any case, don't reload more than half of target duration
  7939. return Math.round(reloadInterval);
  7940. }
  7941. // CONCATENATED MODULE: ./src/utils/time-ranges.ts
  7942. /**
  7943. * TimeRanges to string helper
  7944. */
  7945. var TimeRanges = {
  7946. toString: function toString(r) {
  7947. var log = '';
  7948. var len = r.length;
  7949. for (var i = 0; i < len; i++) {
  7950. log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']';
  7951. }
  7952. return log;
  7953. }
  7954. };
  7955. /* harmony default export */ var time_ranges = (TimeRanges);
  7956. // CONCATENATED MODULE: ./src/utils/discontinuities.js
  7957. function findFirstFragWithCC(fragments, cc) {
  7958. var firstFrag = null;
  7959. for (var i = 0; i < fragments.length; i += 1) {
  7960. var currentFrag = fragments[i];
  7961. if (currentFrag && currentFrag.cc === cc) {
  7962. firstFrag = currentFrag;
  7963. break;
  7964. }
  7965. }
  7966. return firstFrag;
  7967. }
  7968. function findFragWithCC(fragments, CC) {
  7969. return binary_search.search(fragments, function (candidate) {
  7970. if (candidate.cc < CC) {
  7971. return 1;
  7972. } else if (candidate.cc > CC) {
  7973. return -1;
  7974. } else {
  7975. return 0;
  7976. }
  7977. });
  7978. }
  7979. function shouldAlignOnDiscontinuities(lastFrag, lastLevel, details) {
  7980. var shouldAlign = false;
  7981. if (lastLevel && lastLevel.details && details) {
  7982. if (details.endCC > details.startCC || lastFrag && lastFrag.cc < details.startCC) {
  7983. shouldAlign = true;
  7984. }
  7985. }
  7986. return shouldAlign;
  7987. } // Find the first frag in the previous level which matches the CC of the first frag of the new level
  7988. function findDiscontinuousReferenceFrag(prevDetails, curDetails) {
  7989. var prevFrags = prevDetails.fragments;
  7990. var curFrags = curDetails.fragments;
  7991. if (!curFrags.length || !prevFrags.length) {
  7992. logger["logger"].log('No fragments to align');
  7993. return;
  7994. }
  7995. var prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);
  7996. if (!prevStartFrag || prevStartFrag && !prevStartFrag.startPTS) {
  7997. logger["logger"].log('No frag in previous level to align on');
  7998. return;
  7999. }
  8000. return prevStartFrag;
  8001. }
  8002. function adjustPts(sliding, details) {
  8003. details.fragments.forEach(function (frag) {
  8004. if (frag) {
  8005. var start = frag.start + sliding;
  8006. frag.start = frag.startPTS = start;
  8007. frag.endPTS = start + frag.duration;
  8008. }
  8009. });
  8010. details.PTSKnown = true;
  8011. }
  8012. /**
  8013. * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a
  8014. * contiguous stream with the last fragments.
  8015. * The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to
  8016. * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time
  8017. * and an extra download.
  8018. * @param lastFrag
  8019. * @param lastLevel
  8020. * @param details
  8021. */
  8022. function alignStream(lastFrag, lastLevel, details) {
  8023. alignDiscontinuities(lastFrag, details, lastLevel);
  8024. if (!details.PTSKnown && lastLevel) {
  8025. // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.
  8026. // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same
  8027. // discontinuity sequence.
  8028. alignPDT(details, lastLevel.details);
  8029. }
  8030. }
  8031. /**
  8032. * Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same
  8033. * discontinuity sequence.
  8034. * @param lastLevel - The details of the last loaded level
  8035. * @param details - The details of the new level
  8036. */
  8037. function alignDiscontinuities(lastFrag, details, lastLevel) {
  8038. if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) {
  8039. var referenceFrag = findDiscontinuousReferenceFrag(lastLevel.details, details);
  8040. if (referenceFrag) {
  8041. logger["logger"].log('Adjusting PTS using last level due to CC increase within current level');
  8042. adjustPts(referenceFrag.start, details);
  8043. }
  8044. }
  8045. }
  8046. /**
  8047. * Computes the PTS of a new level's fragments using the difference in Program Date Time from the last level.
  8048. * @param details - The details of the new level
  8049. * @param lastDetails - The details of the last loaded level
  8050. */
  8051. function alignPDT(details, lastDetails) {
  8052. if (lastDetails && lastDetails.fragments.length) {
  8053. if (!details.hasProgramDateTime || !lastDetails.hasProgramDateTime) {
  8054. return;
  8055. } // if last level sliding is 1000 and its first frag PROGRAM-DATE-TIME is 2017-08-20 1:10:00 AM
  8056. // and if new details first frag PROGRAM DATE-TIME is 2017-08-20 1:10:08 AM
  8057. // then we can deduce that playlist B sliding is 1000+8 = 1008s
  8058. var lastPDT = lastDetails.fragments[0].programDateTime;
  8059. var newPDT = details.fragments[0].programDateTime; // date diff is in ms. frag.start is in seconds
  8060. var sliding = (newPDT - lastPDT) / 1000 + lastDetails.fragments[0].start;
  8061. if (Object(number["isFiniteNumber"])(sliding)) {
  8062. logger["logger"].log("adjusting PTS using programDateTime delta, sliding:" + sliding.toFixed(3));
  8063. adjustPts(sliding, details);
  8064. }
  8065. }
  8066. }
  8067. // CONCATENATED MODULE: ./src/controller/fragment-finders.ts
  8068. /**
  8069. * Returns first fragment whose endPdt value exceeds the given PDT.
  8070. * @param {Array<Fragment>} fragments - The array of candidate fragments
  8071. * @param {number|null} [PDTValue = null] - The PDT value which must be exceeded
  8072. * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  8073. * @returns {*|null} fragment - The best matching fragment
  8074. */
  8075. function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
  8076. if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !Object(number["isFiniteNumber"])(PDTValue)) {
  8077. return null;
  8078. } // if less than start
  8079. var startPDT = fragments[0].programDateTime;
  8080. if (PDTValue < (startPDT || 0)) {
  8081. return null;
  8082. }
  8083. var endPDT = fragments[fragments.length - 1].endProgramDateTime;
  8084. if (PDTValue >= (endPDT || 0)) {
  8085. return null;
  8086. }
  8087. maxFragLookUpTolerance = maxFragLookUpTolerance || 0;
  8088. for (var seg = 0; seg < fragments.length; ++seg) {
  8089. var frag = fragments[seg];
  8090. if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
  8091. return frag;
  8092. }
  8093. }
  8094. return null;
  8095. }
  8096. /**
  8097. * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.
  8098. * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus
  8099. * breaking any traps which would cause the same fragment to be continuously selected within a small range.
  8100. * @param {*} fragPrevious - The last frag successfully appended
  8101. * @param {Array<Fragment>} fragments - The array of candidate fragments
  8102. * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within
  8103. * @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  8104. * @returns {*} foundFrag - The best matching fragment
  8105. */
  8106. function findFragmentByPTS(fragPrevious, fragments, bufferEnd, maxFragLookUpTolerance) {
  8107. if (bufferEnd === void 0) {
  8108. bufferEnd = 0;
  8109. }
  8110. if (maxFragLookUpTolerance === void 0) {
  8111. maxFragLookUpTolerance = 0;
  8112. }
  8113. var fragNext = null;
  8114. if (fragPrevious) {
  8115. fragNext = fragments[fragPrevious.sn - fragments[0].sn + 1];
  8116. } else if (bufferEnd === 0 && fragments[0].start === 0) {
  8117. fragNext = fragments[0];
  8118. } // Prefer the next fragment if it's within tolerance
  8119. if (fragNext && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0) {
  8120. return fragNext;
  8121. } // We might be seeking past the tolerance so find the best match
  8122. var foundFragment = binary_search.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
  8123. if (foundFragment) {
  8124. return foundFragment;
  8125. } // If no match was found return the next fragment after fragPrevious, or null
  8126. return fragNext;
  8127. }
  8128. /**
  8129. * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.
  8130. * @param {*} candidate - The fragment to test
  8131. * @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within
  8132. * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous
  8133. * @returns {number} - 0 if it matches, 1 if too low, -1 if too high
  8134. */
  8135. function fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, candidate) {
  8136. if (bufferEnd === void 0) {
  8137. bufferEnd = 0;
  8138. }
  8139. if (maxFragLookUpTolerance === void 0) {
  8140. maxFragLookUpTolerance = 0;
  8141. }
  8142. // offset should be within fragment boundary - config.maxFragLookUpTolerance
  8143. // this is to cope with situations like
  8144. // bufferEnd = 9.991
  8145. // frag[Ø] : [0,10]
  8146. // frag[1] : [10,20]
  8147. // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
  8148. // frag start frag start+duration
  8149. // |-----------------------------|
  8150. // <---> <--->
  8151. // ...--------><-----------------------------><---------....
  8152. // previous frag matching fragment next frag
  8153. // return -1 return 0 return 1
  8154. // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
  8155. // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
  8156. var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
  8157. if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
  8158. return 1;
  8159. } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
  8160. // if maxFragLookUpTolerance will have negative value then don't return -1 for first element
  8161. return -1;
  8162. }
  8163. return 0;
  8164. }
  8165. /**
  8166. * The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.
  8167. * This function tests the candidate's program date time values, as represented in Unix time
  8168. * @param {*} candidate - The fragment to test
  8169. * @param {number} [pdtBufferEnd = 0] - The Unix time representing the end of the current buffered range
  8170. * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous
  8171. * @returns {boolean} True if contiguous, false otherwise
  8172. */
  8173. function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
  8174. var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000; // endProgramDateTime can be null, default to zero
  8175. var endProgramDateTime = candidate.endProgramDateTime || 0;
  8176. return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
  8177. }
  8178. // CONCATENATED MODULE: ./src/controller/gap-controller.js
  8179. var STALL_MINIMUM_DURATION_MS = 250;
  8180. var MAX_START_GAP_JUMP = 2.0;
  8181. var SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;
  8182. var SKIP_BUFFER_RANGE_START = 0.05;
  8183. var gap_controller_GapController = /*#__PURE__*/function () {
  8184. function GapController(config, media, fragmentTracker, hls) {
  8185. this.config = config;
  8186. this.media = media;
  8187. this.fragmentTracker = fragmentTracker;
  8188. this.hls = hls;
  8189. this.nudgeRetry = 0;
  8190. this.stallReported = false;
  8191. this.stalled = null;
  8192. this.moved = false;
  8193. this.seeking = false;
  8194. }
  8195. /**
  8196. * Checks if the playhead is stuck within a gap, and if so, attempts to free it.
  8197. * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).
  8198. *
  8199. * @param {number} lastCurrentTime Previously read playhead position
  8200. */
  8201. var _proto = GapController.prototype;
  8202. _proto.poll = function poll(lastCurrentTime) {
  8203. var config = this.config,
  8204. media = this.media,
  8205. stalled = this.stalled;
  8206. var currentTime = media.currentTime,
  8207. seeking = media.seeking;
  8208. var seeked = this.seeking && !seeking;
  8209. var beginSeek = !this.seeking && seeking;
  8210. this.seeking = seeking; // The playhead is moving, no-op
  8211. if (currentTime !== lastCurrentTime) {
  8212. this.moved = true;
  8213. if (stalled !== null) {
  8214. // The playhead is now moving, but was previously stalled
  8215. if (this.stallReported) {
  8216. var _stalledDuration = self.performance.now() - stalled;
  8217. logger["logger"].warn("playback not stuck anymore @" + currentTime + ", after " + Math.round(_stalledDuration) + "ms");
  8218. this.stallReported = false;
  8219. }
  8220. this.stalled = null;
  8221. this.nudgeRetry = 0;
  8222. }
  8223. return;
  8224. } // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek
  8225. if (beginSeek || seeked) {
  8226. this.stalled = null;
  8227. } // The playhead should not be moving
  8228. if (media.paused || media.ended || media.playbackRate === 0 || !media.buffered.length) {
  8229. return;
  8230. }
  8231. var bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  8232. var isBuffered = bufferInfo.len > 0;
  8233. var nextStart = bufferInfo.nextStart || 0; // There is no playable buffer (waiting for buffer append)
  8234. if (!isBuffered && !nextStart) {
  8235. return;
  8236. }
  8237. if (seeking) {
  8238. // Waiting for seeking in a buffered range to complete
  8239. var hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP; // Next buffered range is too far ahead to jump to while still seeking
  8240. var noBufferGap = !nextStart || nextStart - currentTime > MAX_START_GAP_JUMP && !this.fragmentTracker.getPartialFragment(currentTime);
  8241. if (hasEnoughBuffer || noBufferGap) {
  8242. return;
  8243. } // Reset moved state when seeking to a point in or before a gap
  8244. this.moved = false;
  8245. } // Skip start gaps if we haven't played, but the last poll detected the start of a stall
  8246. // The addition poll gives the browser a chance to jump the gap for us
  8247. if (!this.moved && this.stalled) {
  8248. // Jump start gaps within jump threshold
  8249. var startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime;
  8250. if (startJump > 0 && startJump <= MAX_START_GAP_JUMP) {
  8251. this._trySkipBufferHole(null);
  8252. return;
  8253. }
  8254. } // Start tracking stall time
  8255. var tnow = self.performance.now();
  8256. if (stalled === null) {
  8257. this.stalled = tnow;
  8258. return;
  8259. }
  8260. var stalledDuration = tnow - stalled;
  8261. if (!seeking && stalledDuration >= STALL_MINIMUM_DURATION_MS) {
  8262. // Report stalling after trying to fix
  8263. this._reportStall(bufferInfo.len);
  8264. }
  8265. var bufferedWithHoles = BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);
  8266. this._tryFixBufferStall(bufferedWithHoles, stalledDuration);
  8267. }
  8268. /**
  8269. * Detects and attempts to fix known buffer stalling issues.
  8270. * @param bufferInfo - The properties of the current buffer.
  8271. * @param stalledDurationMs - The amount of time Hls.js has been stalling for.
  8272. * @private
  8273. */
  8274. ;
  8275. _proto._tryFixBufferStall = function _tryFixBufferStall(bufferInfo, stalledDurationMs) {
  8276. var config = this.config,
  8277. fragmentTracker = this.fragmentTracker,
  8278. media = this.media;
  8279. var currentTime = media.currentTime;
  8280. var partial = fragmentTracker.getPartialFragment(currentTime);
  8281. if (partial) {
  8282. // Try to skip over the buffer hole caused by a partial fragment
  8283. // This method isn't limited by the size of the gap between buffered ranges
  8284. var targetTime = this._trySkipBufferHole(partial); // we return here in this case, meaning
  8285. // the branch below only executes when we don't handle a partial fragment
  8286. if (targetTime) {
  8287. return;
  8288. }
  8289. } // if we haven't had to skip over a buffer hole of a partial fragment
  8290. // we may just have to "nudge" the playlist as the browser decoding/rendering engine
  8291. // needs to cross some sort of threshold covering all source-buffers content
  8292. // to start playing properly.
  8293. if (bufferInfo.len > config.maxBufferHole && stalledDurationMs > config.highBufferWatchdogPeriod * 1000) {
  8294. logger["logger"].warn('Trying to nudge playhead over buffer-hole'); // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds
  8295. // We only try to jump the hole if it's under the configured size
  8296. // Reset stalled so to rearm watchdog timer
  8297. this.stalled = null;
  8298. this._tryNudgeBuffer();
  8299. }
  8300. }
  8301. /**
  8302. * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.
  8303. * @param bufferLen - The playhead distance from the end of the current buffer segment.
  8304. * @private
  8305. */
  8306. ;
  8307. _proto._reportStall = function _reportStall(bufferLen) {
  8308. var hls = this.hls,
  8309. media = this.media,
  8310. stallReported = this.stallReported;
  8311. if (!stallReported) {
  8312. // Report stalled error once
  8313. this.stallReported = true;
  8314. logger["logger"].warn("Playback stalling at @" + media.currentTime + " due to low buffer (buffer=" + bufferLen + ")");
  8315. hls.trigger(events["default"].ERROR, {
  8316. type: errors["ErrorTypes"].MEDIA_ERROR,
  8317. details: errors["ErrorDetails"].BUFFER_STALLED_ERROR,
  8318. fatal: false,
  8319. buffer: bufferLen
  8320. });
  8321. }
  8322. }
  8323. /**
  8324. * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
  8325. * @param partial - The partial fragment found at the current time (where playback is stalling).
  8326. * @private
  8327. */
  8328. ;
  8329. _proto._trySkipBufferHole = function _trySkipBufferHole(partial) {
  8330. var config = this.config,
  8331. hls = this.hls,
  8332. media = this.media;
  8333. var currentTime = media.currentTime;
  8334. var lastEndTime = 0; // Check if currentTime is between unbuffered regions of partial fragments
  8335. for (var i = 0; i < media.buffered.length; i++) {
  8336. var startTime = media.buffered.start(i);
  8337. if (currentTime + config.maxBufferHole >= lastEndTime && currentTime < startTime) {
  8338. var targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, media.currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);
  8339. logger["logger"].warn("skipping hole, adjusting currentTime from " + currentTime + " to " + targetTime);
  8340. this.moved = true;
  8341. this.stalled = null;
  8342. media.currentTime = targetTime;
  8343. if (partial) {
  8344. hls.trigger(events["default"].ERROR, {
  8345. type: errors["ErrorTypes"].MEDIA_ERROR,
  8346. details: errors["ErrorDetails"].BUFFER_SEEK_OVER_HOLE,
  8347. fatal: false,
  8348. reason: "fragment loaded with buffer holes, seeking from " + currentTime + " to " + targetTime,
  8349. frag: partial
  8350. });
  8351. }
  8352. return targetTime;
  8353. }
  8354. lastEndTime = media.buffered.end(i);
  8355. }
  8356. return 0;
  8357. }
  8358. /**
  8359. * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
  8360. * @private
  8361. */
  8362. ;
  8363. _proto._tryNudgeBuffer = function _tryNudgeBuffer() {
  8364. var config = this.config,
  8365. hls = this.hls,
  8366. media = this.media;
  8367. var currentTime = media.currentTime;
  8368. var nudgeRetry = (this.nudgeRetry || 0) + 1;
  8369. this.nudgeRetry = nudgeRetry;
  8370. if (nudgeRetry < config.nudgeMaxRetry) {
  8371. var targetTime = currentTime + nudgeRetry * config.nudgeOffset; // playback stalled in buffered area ... let's nudge currentTime to try to overcome this
  8372. logger["logger"].warn("Nudging 'currentTime' from " + currentTime + " to " + targetTime);
  8373. media.currentTime = targetTime;
  8374. hls.trigger(events["default"].ERROR, {
  8375. type: errors["ErrorTypes"].MEDIA_ERROR,
  8376. details: errors["ErrorDetails"].BUFFER_NUDGE_ON_STALL,
  8377. fatal: false
  8378. });
  8379. } else {
  8380. logger["logger"].error("Playhead still not moving while enough data buffered @" + currentTime + " after " + config.nudgeMaxRetry + " nudges");
  8381. hls.trigger(events["default"].ERROR, {
  8382. type: errors["ErrorTypes"].MEDIA_ERROR,
  8383. details: errors["ErrorDetails"].BUFFER_STALLED_ERROR,
  8384. fatal: true
  8385. });
  8386. }
  8387. };
  8388. return GapController;
  8389. }();
  8390. // CONCATENATED MODULE: ./src/task-loop.ts
  8391. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  8392. function task_loop_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  8393. /**
  8394. * Sub-class specialization of EventHandler base class.
  8395. *
  8396. * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,
  8397. * scheduled asynchroneously, avoiding recursive calls in the same tick.
  8398. *
  8399. * The task itself is implemented in `doTick`. It can be requested and called for single execution
  8400. * using the `tick` method.
  8401. *
  8402. * It will be assured that the task execution method (`tick`) only gets called once per main loop "tick",
  8403. * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.
  8404. *
  8405. * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,
  8406. * and cancelled with `clearNextTick`.
  8407. *
  8408. * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).
  8409. *
  8410. * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.
  8411. *
  8412. * Further explanations:
  8413. *
  8414. * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously
  8415. * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.
  8416. *
  8417. * When the task execution (`tick` method) is called in re-entrant way this is detected and
  8418. * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further
  8419. * task processing on the next main loop iteration (also known as "next tick" in the Node/JS runtime lingo).
  8420. */
  8421. var TaskLoop = /*#__PURE__*/function (_EventHandler) {
  8422. task_loop_inheritsLoose(TaskLoop, _EventHandler);
  8423. function TaskLoop(hls) {
  8424. var _this;
  8425. for (var _len = arguments.length, events = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  8426. events[_key - 1] = arguments[_key];
  8427. }
  8428. _this = _EventHandler.call.apply(_EventHandler, [this, hls].concat(events)) || this;
  8429. _this._boundTick = void 0;
  8430. _this._tickTimer = null;
  8431. _this._tickInterval = null;
  8432. _this._tickCallCount = 0;
  8433. _this._boundTick = _this.tick.bind(_assertThisInitialized(_this));
  8434. return _this;
  8435. }
  8436. /**
  8437. * @override
  8438. */
  8439. var _proto = TaskLoop.prototype;
  8440. _proto.onHandlerDestroying = function onHandlerDestroying() {
  8441. // clear all timers before unregistering from event bus
  8442. this.clearNextTick();
  8443. this.clearInterval();
  8444. }
  8445. /**
  8446. * @returns {boolean}
  8447. */
  8448. ;
  8449. _proto.hasInterval = function hasInterval() {
  8450. return !!this._tickInterval;
  8451. }
  8452. /**
  8453. * @returns {boolean}
  8454. */
  8455. ;
  8456. _proto.hasNextTick = function hasNextTick() {
  8457. return !!this._tickTimer;
  8458. }
  8459. /**
  8460. * @param {number} millis Interval time (ms)
  8461. * @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect)
  8462. */
  8463. ;
  8464. _proto.setInterval = function setInterval(millis) {
  8465. if (!this._tickInterval) {
  8466. this._tickInterval = self.setInterval(this._boundTick, millis);
  8467. return true;
  8468. }
  8469. return false;
  8470. }
  8471. /**
  8472. * @returns {boolean} True when interval was cleared, false when none was set (no effect)
  8473. */
  8474. ;
  8475. _proto.clearInterval = function clearInterval() {
  8476. if (this._tickInterval) {
  8477. self.clearInterval(this._tickInterval);
  8478. this._tickInterval = null;
  8479. return true;
  8480. }
  8481. return false;
  8482. }
  8483. /**
  8484. * @returns {boolean} True when timeout was cleared, false when none was set (no effect)
  8485. */
  8486. ;
  8487. _proto.clearNextTick = function clearNextTick() {
  8488. if (this._tickTimer) {
  8489. self.clearTimeout(this._tickTimer);
  8490. this._tickTimer = null;
  8491. return true;
  8492. }
  8493. return false;
  8494. }
  8495. /**
  8496. * Will call the subclass doTick implementation in this main loop tick
  8497. * or in the next one (via setTimeout(,0)) in case it has already been called
  8498. * in this tick (in case this is a re-entrant call).
  8499. */
  8500. ;
  8501. _proto.tick = function tick() {
  8502. this._tickCallCount++;
  8503. if (this._tickCallCount === 1) {
  8504. this.doTick(); // re-entrant call to tick from previous doTick call stack
  8505. // -> schedule a call on the next main loop iteration to process this task processing request
  8506. if (this._tickCallCount > 1) {
  8507. // make sure only one timer exists at any time at max
  8508. this.clearNextTick();
  8509. this._tickTimer = self.setTimeout(this._boundTick, 0);
  8510. }
  8511. this._tickCallCount = 0;
  8512. }
  8513. }
  8514. /**
  8515. * For subclass to implement task logic
  8516. * @abstract
  8517. */
  8518. ;
  8519. _proto.doTick = function doTick() {};
  8520. return TaskLoop;
  8521. }(event_handler);
  8522. // CONCATENATED MODULE: ./src/controller/base-stream-controller.js
  8523. function base_stream_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  8524. var State = {
  8525. STOPPED: 'STOPPED',
  8526. STARTING: 'STARTING',
  8527. IDLE: 'IDLE',
  8528. PAUSED: 'PAUSED',
  8529. KEY_LOADING: 'KEY_LOADING',
  8530. FRAG_LOADING: 'FRAG_LOADING',
  8531. FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
  8532. WAITING_TRACK: 'WAITING_TRACK',
  8533. PARSING: 'PARSING',
  8534. PARSED: 'PARSED',
  8535. BUFFER_FLUSHING: 'BUFFER_FLUSHING',
  8536. ENDED: 'ENDED',
  8537. ERROR: 'ERROR',
  8538. WAITING_INIT_PTS: 'WAITING_INIT_PTS',
  8539. WAITING_LEVEL: 'WAITING_LEVEL'
  8540. };
  8541. var base_stream_controller_BaseStreamController = /*#__PURE__*/function (_TaskLoop) {
  8542. base_stream_controller_inheritsLoose(BaseStreamController, _TaskLoop);
  8543. function BaseStreamController() {
  8544. return _TaskLoop.apply(this, arguments) || this;
  8545. }
  8546. var _proto = BaseStreamController.prototype;
  8547. _proto.doTick = function doTick() {};
  8548. _proto.startLoad = function startLoad() {};
  8549. _proto.stopLoad = function stopLoad() {
  8550. var frag = this.fragCurrent;
  8551. if (frag) {
  8552. if (frag.loader) {
  8553. frag.loader.abort();
  8554. }
  8555. this.fragmentTracker.removeFragment(frag);
  8556. }
  8557. if (this.demuxer) {
  8558. this.demuxer.destroy();
  8559. this.demuxer = null;
  8560. }
  8561. this.fragCurrent = null;
  8562. this.fragPrevious = null;
  8563. this.clearInterval();
  8564. this.clearNextTick();
  8565. this.state = State.STOPPED;
  8566. };
  8567. _proto._streamEnded = function _streamEnded(bufferInfo, levelDetails) {
  8568. var fragCurrent = this.fragCurrent,
  8569. fragmentTracker = this.fragmentTracker; // we just got done loading the final fragment and there is no other buffered range after ...
  8570. // rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between
  8571. // so we should not switch to ENDED in that case, to be able to buffer them
  8572. // dont switch to ENDED if we need to backtrack last fragment
  8573. if (!levelDetails.live && fragCurrent && !fragCurrent.backtracked && fragCurrent.sn === levelDetails.endSN && !bufferInfo.nextStart) {
  8574. var fragState = fragmentTracker.getState(fragCurrent);
  8575. return fragState === FragmentState.PARTIAL || fragState === FragmentState.OK;
  8576. }
  8577. return false;
  8578. };
  8579. _proto.onMediaSeeking = function onMediaSeeking() {
  8580. var config = this.config,
  8581. media = this.media,
  8582. mediaBuffer = this.mediaBuffer,
  8583. state = this.state;
  8584. var currentTime = media ? media.currentTime : null;
  8585. var bufferInfo = BufferHelper.bufferInfo(mediaBuffer || media, currentTime, this.config.maxBufferHole);
  8586. logger["logger"].log("media seeking to " + (Object(number["isFiniteNumber"])(currentTime) ? currentTime.toFixed(3) : currentTime));
  8587. if (state === State.FRAG_LOADING) {
  8588. var fragCurrent = this.fragCurrent; // check if we are seeking to a unbuffered area AND if frag loading is in progress
  8589. if (bufferInfo.len === 0 && fragCurrent) {
  8590. var tolerance = config.maxFragLookUpTolerance;
  8591. var fragStartOffset = fragCurrent.start - tolerance;
  8592. var fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance; // check if we seek position will be out of currently loaded frag range : if out cancel frag load, if in, don't do anything
  8593. if (currentTime < fragStartOffset || currentTime > fragEndOffset) {
  8594. if (fragCurrent.loader) {
  8595. logger["logger"].log('seeking outside of buffer while fragment load in progress, cancel fragment load');
  8596. fragCurrent.loader.abort();
  8597. }
  8598. this.fragCurrent = null;
  8599. this.fragPrevious = null; // switch to IDLE state to load new fragment
  8600. this.state = State.IDLE;
  8601. } else {
  8602. logger["logger"].log('seeking outside of buffer but within currently loaded fragment range');
  8603. }
  8604. }
  8605. } else if (state === State.ENDED) {
  8606. // if seeking to unbuffered area, clean up fragPrevious
  8607. if (bufferInfo.len === 0) {
  8608. this.fragPrevious = null;
  8609. this.fragCurrent = null;
  8610. } // switch to IDLE state to check for potential new fragment
  8611. this.state = State.IDLE;
  8612. }
  8613. if (media) {
  8614. this.lastCurrentTime = currentTime;
  8615. } // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
  8616. if (!this.loadedmetadata) {
  8617. this.nextLoadPosition = this.startPosition = currentTime;
  8618. } // tick to speed up processing
  8619. this.tick();
  8620. };
  8621. _proto.onMediaEnded = function onMediaEnded() {
  8622. // reset startPosition and lastCurrentTime to restart playback @ stream beginning
  8623. this.startPosition = this.lastCurrentTime = 0;
  8624. };
  8625. _proto.onHandlerDestroying = function onHandlerDestroying() {
  8626. this.stopLoad();
  8627. _TaskLoop.prototype.onHandlerDestroying.call(this);
  8628. };
  8629. _proto.onHandlerDestroyed = function onHandlerDestroyed() {
  8630. this.state = State.STOPPED;
  8631. this.fragmentTracker = null;
  8632. };
  8633. _proto.computeLivePosition = function computeLivePosition(sliding, levelDetails) {
  8634. var targetLatency = this.config.liveSyncDuration !== undefined ? this.config.liveSyncDuration : this.config.liveSyncDurationCount * levelDetails.targetduration;
  8635. return sliding + Math.max(0, levelDetails.totalduration - targetLatency);
  8636. };
  8637. return BaseStreamController;
  8638. }(TaskLoop);
  8639. // CONCATENATED MODULE: ./src/controller/stream-controller.js
  8640. function stream_controller_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  8641. function stream_controller_createClass(Constructor, protoProps, staticProps) { if (protoProps) stream_controller_defineProperties(Constructor.prototype, protoProps); if (staticProps) stream_controller_defineProperties(Constructor, staticProps); return Constructor; }
  8642. function stream_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  8643. /*
  8644. * Stream Controller
  8645. */
  8646. var TICK_INTERVAL = 100; // how often to tick in ms
  8647. var stream_controller_StreamController = /*#__PURE__*/function (_BaseStreamController) {
  8648. stream_controller_inheritsLoose(StreamController, _BaseStreamController);
  8649. function StreamController(hls, fragmentTracker) {
  8650. var _this;
  8651. _this = _BaseStreamController.call(this, hls, events["default"].MEDIA_ATTACHED, events["default"].MEDIA_DETACHING, events["default"].MANIFEST_LOADING, events["default"].MANIFEST_PARSED, events["default"].LEVEL_LOADED, events["default"].LEVELS_UPDATED, events["default"].KEY_LOADED, events["default"].FRAG_LOADED, events["default"].FRAG_LOAD_EMERGENCY_ABORTED, events["default"].FRAG_PARSING_INIT_SEGMENT, events["default"].FRAG_PARSING_DATA, events["default"].FRAG_PARSED, events["default"].ERROR, events["default"].AUDIO_TRACK_SWITCHING, events["default"].AUDIO_TRACK_SWITCHED, events["default"].BUFFER_CREATED, events["default"].BUFFER_APPENDED, events["default"].BUFFER_FLUSHED) || this;
  8652. _this.fragmentTracker = fragmentTracker;
  8653. _this.config = hls.config;
  8654. _this.audioCodecSwap = false;
  8655. _this._state = State.STOPPED;
  8656. _this.stallReported = false;
  8657. _this.gapController = null;
  8658. _this.altAudio = false;
  8659. _this.audioOnly = false;
  8660. _this.bitrateTest = false;
  8661. return _this;
  8662. }
  8663. var _proto = StreamController.prototype;
  8664. _proto.startLoad = function startLoad(startPosition) {
  8665. if (this.levels) {
  8666. var lastCurrentTime = this.lastCurrentTime,
  8667. hls = this.hls;
  8668. this.stopLoad();
  8669. this.setInterval(TICK_INTERVAL);
  8670. this.level = -1;
  8671. this.fragLoadError = 0;
  8672. if (!this.startFragRequested) {
  8673. // determine load level
  8674. var startLevel = hls.startLevel;
  8675. if (startLevel === -1) {
  8676. if (hls.config.testBandwidth) {
  8677. // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
  8678. startLevel = 0;
  8679. this.bitrateTest = true;
  8680. } else {
  8681. startLevel = hls.nextAutoLevel;
  8682. }
  8683. } // set new level to playlist loader : this will trigger start level load
  8684. // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
  8685. this.level = hls.nextLoadLevel = startLevel;
  8686. this.loadedmetadata = false;
  8687. } // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime
  8688. if (lastCurrentTime > 0 && startPosition === -1) {
  8689. logger["logger"].log("override startPosition with lastCurrentTime @" + lastCurrentTime.toFixed(3));
  8690. startPosition = lastCurrentTime;
  8691. }
  8692. this.state = State.IDLE;
  8693. this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
  8694. this.tick();
  8695. } else {
  8696. this.forceStartLoad = true;
  8697. this.state = State.STOPPED;
  8698. }
  8699. };
  8700. _proto.stopLoad = function stopLoad() {
  8701. this.forceStartLoad = false;
  8702. _BaseStreamController.prototype.stopLoad.call(this);
  8703. };
  8704. _proto.doTick = function doTick() {
  8705. switch (this.state) {
  8706. case State.BUFFER_FLUSHING:
  8707. // in buffer flushing state, reset fragLoadError counter
  8708. this.fragLoadError = 0;
  8709. break;
  8710. case State.IDLE:
  8711. this._doTickIdle();
  8712. break;
  8713. case State.WAITING_LEVEL:
  8714. var level = this.levels[this.level]; // check if playlist is already loaded
  8715. if (level && level.details) {
  8716. this.state = State.IDLE;
  8717. }
  8718. break;
  8719. case State.FRAG_LOADING_WAITING_RETRY:
  8720. var now = window.performance.now();
  8721. var retryDate = this.retryDate; // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  8722. if (!retryDate || now >= retryDate || this.media && this.media.seeking) {
  8723. logger["logger"].log('mediaController: retryDate reached, switch back to IDLE state');
  8724. this.state = State.IDLE;
  8725. }
  8726. break;
  8727. case State.ERROR:
  8728. case State.STOPPED:
  8729. case State.FRAG_LOADING:
  8730. case State.PARSING:
  8731. case State.PARSED:
  8732. case State.ENDED:
  8733. break;
  8734. default:
  8735. break;
  8736. } // check buffer
  8737. this._checkBuffer(); // check/update current fragment
  8738. this._checkFragmentChanged();
  8739. } // Ironically the "idle" state is the on we do the most logic in it seems ....
  8740. // NOTE: Maybe we could rather schedule a check for buffer length after half of the currently
  8741. // played segment, or on pause/play/seek instead of naively checking every 100ms?
  8742. ;
  8743. _proto._doTickIdle = function _doTickIdle() {
  8744. var hls = this.hls,
  8745. config = hls.config,
  8746. media = this.media; // if start level not parsed yet OR
  8747. // if video not attached AND start fragment already requested OR start frag prefetch disable
  8748. // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment
  8749. if (this.levelLastLoaded === undefined || !media && (this.startFragRequested || !config.startFragPrefetch)) {
  8750. return;
  8751. } // If the "main" level is audio-only but we are loading an alternate track in the same group, do not load anything
  8752. if (this.altAudio && this.audioOnly) {
  8753. // Clear audio demuxer state so when switching back to main audio we're not still appending where we left off
  8754. this.demuxer.frag = null;
  8755. return;
  8756. } // if we have not yet loaded any fragment, start loading from start position
  8757. var pos;
  8758. if (this.loadedmetadata) {
  8759. pos = media.currentTime;
  8760. } else {
  8761. pos = this.nextLoadPosition;
  8762. } // determine next load level
  8763. var level = hls.nextLoadLevel,
  8764. levelInfo = this.levels[level];
  8765. if (!levelInfo) {
  8766. return;
  8767. }
  8768. var levelBitrate = levelInfo.bitrate,
  8769. maxBufLen; // compute max Buffer Length that we could get from this load level, based on level bitrate.
  8770. if (levelBitrate) {
  8771. maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
  8772. } else {
  8773. maxBufLen = config.maxBufferLength;
  8774. }
  8775. maxBufLen = Math.min(maxBufLen, config.maxMaxBufferLength); // determine next candidate fragment to be loaded, based on current position and end of buffer position
  8776. // ensure up to `config.maxMaxBufferLength` of buffer upfront
  8777. var maxBufferHole = pos < config.maxBufferHole ? Math.max(MAX_START_GAP_JUMP, config.maxBufferHole) : config.maxBufferHole;
  8778. var bufferInfo = BufferHelper.bufferInfo(this.mediaBuffer ? this.mediaBuffer : media, pos, maxBufferHole);
  8779. var bufferLen = bufferInfo.len; // Stay idle if we are still with buffer margins
  8780. if (bufferLen >= maxBufLen) {
  8781. return;
  8782. } // if buffer length is less than maxBufLen try to load a new fragment ...
  8783. logger["logger"].trace("buffer length of " + bufferLen.toFixed(3) + " is below max of " + maxBufLen.toFixed(3) + ". checking for more payload ..."); // set next load level : this will trigger a playlist load if needed
  8784. this.level = hls.nextLoadLevel = level;
  8785. var levelDetails = levelInfo.details; // if level info not retrieved yet, switch state and wait for level retrieval
  8786. // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
  8787. // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
  8788. if (!levelDetails || levelDetails.live && this.levelLastLoaded !== level) {
  8789. this.state = State.WAITING_LEVEL;
  8790. return;
  8791. }
  8792. if (this._streamEnded(bufferInfo, levelDetails)) {
  8793. var data = {};
  8794. if (this.altAudio) {
  8795. data.type = 'video';
  8796. }
  8797. this.hls.trigger(events["default"].BUFFER_EOS, data);
  8798. this.state = State.ENDED;
  8799. return;
  8800. } // if we have the levelDetails for the selected variant, lets continue enrichen our stream (load keys/fragments or trigger EOS, etc..)
  8801. this._fetchPayloadOrEos(pos, bufferInfo, levelDetails);
  8802. };
  8803. _proto._fetchPayloadOrEos = function _fetchPayloadOrEos(pos, bufferInfo, levelDetails) {
  8804. var fragPrevious = this.fragPrevious,
  8805. level = this.level,
  8806. fragments = levelDetails.fragments,
  8807. fragLen = fragments.length; // empty playlist
  8808. if (fragLen === 0) {
  8809. return;
  8810. } // find fragment index, contiguous with end of buffer position
  8811. var start = fragments[0].start,
  8812. end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,
  8813. bufferEnd = bufferInfo.end,
  8814. frag;
  8815. if (levelDetails.initSegment && !levelDetails.initSegment.data) {
  8816. frag = levelDetails.initSegment;
  8817. } else {
  8818. // in case of live playlist we need to ensure that requested position is not located before playlist start
  8819. if (levelDetails.live) {
  8820. var initialLiveManifestSize = this.config.initialLiveManifestSize;
  8821. if (fragLen < initialLiveManifestSize) {
  8822. logger["logger"].warn("Can not start playback of a level, reason: not enough fragments " + fragLen + " < " + initialLiveManifestSize);
  8823. return;
  8824. }
  8825. frag = this._ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments); // if it explicitely returns null don't load any fragment and exit function now
  8826. if (frag === null) {
  8827. return;
  8828. }
  8829. } else {
  8830. // VoD playlist: if bufferEnd before start of playlist, load first fragment
  8831. if (bufferEnd < start) {
  8832. frag = fragments[0];
  8833. }
  8834. }
  8835. }
  8836. if (!frag) {
  8837. frag = this._findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails);
  8838. }
  8839. if (frag) {
  8840. if (frag.encrypted) {
  8841. this._loadKey(frag, levelDetails);
  8842. } else {
  8843. this._loadFragment(frag, levelDetails, pos, bufferEnd);
  8844. }
  8845. }
  8846. };
  8847. _proto._ensureFragmentAtLivePoint = function _ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments) {
  8848. var config = this.hls.config,
  8849. media = this.media;
  8850. var frag; // check if requested position is within seekable boundaries :
  8851. // logger.log(`start/pos/bufEnd/seeking:${start.toFixed(3)}/${pos.toFixed(3)}/${bufferEnd.toFixed(3)}/${this.media.seeking}`);
  8852. var maxLatency = Infinity;
  8853. if (config.liveMaxLatencyDuration !== undefined) {
  8854. maxLatency = config.liveMaxLatencyDuration;
  8855. } else if (Object(number["isFiniteNumber"])(config.liveMaxLatencyDurationCount)) {
  8856. maxLatency = config.liveMaxLatencyDurationCount * levelDetails.targetduration;
  8857. }
  8858. if (bufferEnd < Math.max(start - config.maxFragLookUpTolerance, end - maxLatency)) {
  8859. var liveSyncPosition = this.liveSyncPosition = this.computeLivePosition(start, levelDetails);
  8860. bufferEnd = liveSyncPosition;
  8861. if (media && !media.paused && media.readyState && media.duration > liveSyncPosition && liveSyncPosition > media.currentTime) {
  8862. logger["logger"].log("buffer end: " + bufferEnd.toFixed(3) + " is located too far from the end of live sliding playlist, reset currentTime to : " + liveSyncPosition.toFixed(3));
  8863. media.currentTime = liveSyncPosition;
  8864. }
  8865. this.nextLoadPosition = liveSyncPosition;
  8866. } // if end of buffer greater than live edge, don't load any fragment
  8867. // this could happen if live playlist intermittently slides in the past.
  8868. // level 1 loaded [182580161,182580167]
  8869. // level 1 loaded [182580162,182580169]
  8870. // Loading 182580168 of [182580162 ,182580169],level 1 ..
  8871. // Loading 182580169 of [182580162 ,182580169],level 1 ..
  8872. // level 1 loaded [182580162,182580168] <============= here we should have bufferEnd > end. in that case break to avoid reloading 182580168
  8873. // level 1 loaded [182580164,182580171]
  8874. //
  8875. // don't return null in case media not loaded yet (readystate === 0)
  8876. if (levelDetails.PTSKnown && bufferEnd > end && media && media.readyState) {
  8877. return null;
  8878. }
  8879. if (this.startFragRequested && !levelDetails.PTSKnown) {
  8880. /* we are switching level on live playlist, but we don't have any PTS info for that quality level ...
  8881. try to load frag matching with next SN.
  8882. even if SN are not synchronized between playlists, loading this frag will help us
  8883. compute playlist sliding and find the right one after in case it was not the right consecutive one */
  8884. if (fragPrevious) {
  8885. if (levelDetails.hasProgramDateTime) {
  8886. // Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE)
  8887. logger["logger"].log("live playlist, switching playlist, load frag with same PDT: " + fragPrevious.programDateTime);
  8888. frag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, config.maxFragLookUpTolerance);
  8889. } else {
  8890. // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
  8891. var targetSN = fragPrevious.sn + 1;
  8892. if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
  8893. var fragNext = fragments[targetSN - levelDetails.startSN];
  8894. if (fragPrevious.cc === fragNext.cc) {
  8895. frag = fragNext;
  8896. logger["logger"].log("live playlist, switching playlist, load frag with next SN: " + frag.sn);
  8897. }
  8898. } // next frag SN not available (or not with same continuity counter)
  8899. // look for a frag sharing the same CC
  8900. if (!frag) {
  8901. frag = binary_search.search(fragments, function (frag) {
  8902. return fragPrevious.cc - frag.cc;
  8903. });
  8904. if (frag) {
  8905. logger["logger"].log("live playlist, switching playlist, load frag with same CC: " + frag.sn);
  8906. }
  8907. }
  8908. }
  8909. }
  8910. }
  8911. return frag;
  8912. };
  8913. _proto._findFragment = function _findFragment(start, fragPreviousLoad, fragmentIndexRange, fragments, bufferEnd, end, levelDetails) {
  8914. var config = this.hls.config;
  8915. var fragNextLoad;
  8916. if (bufferEnd < end) {
  8917. var lookupTolerance = bufferEnd > end - config.maxFragLookUpTolerance ? 0 : config.maxFragLookUpTolerance; // Remove the tolerance if it would put the bufferEnd past the actual end of stream
  8918. // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
  8919. fragNextLoad = findFragmentByPTS(fragPreviousLoad, fragments, bufferEnd, lookupTolerance);
  8920. } else {
  8921. // reach end of playlist
  8922. fragNextLoad = fragments[fragmentIndexRange - 1];
  8923. }
  8924. if (fragNextLoad) {
  8925. var curSNIdx = fragNextLoad.sn - levelDetails.startSN;
  8926. var sameLevel = fragPreviousLoad && fragNextLoad.level === fragPreviousLoad.level;
  8927. var prevSnFrag = fragments[curSNIdx - 1];
  8928. var nextSnFrag = fragments[curSNIdx + 1]; // logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);
  8929. if (fragPreviousLoad && fragNextLoad.sn === fragPreviousLoad.sn) {
  8930. if (sameLevel && !fragNextLoad.backtracked) {
  8931. if (fragNextLoad.sn < levelDetails.endSN) {
  8932. var deltaPTS = fragPreviousLoad.deltaPTS; // if there is a significant delta between audio and video, larger than max allowed hole,
  8933. // and if previous remuxed fragment did not start with a keyframe. (fragPrevious.dropped)
  8934. // let's try to load previous fragment again to get last keyframe
  8935. // then we will reload again current fragment (that way we should be able to fill the buffer hole ...)
  8936. if (deltaPTS && deltaPTS > config.maxBufferHole && fragPreviousLoad.dropped && curSNIdx) {
  8937. fragNextLoad = prevSnFrag;
  8938. logger["logger"].warn('Previous fragment was dropped with large PTS gap between audio and video. Maybe fragment is not starting with a keyframe? Loading previous one to try to overcome this');
  8939. } else {
  8940. fragNextLoad = nextSnFrag;
  8941. if (this.fragmentTracker.getState(fragNextLoad) !== FragmentState.OK) {
  8942. logger["logger"].log("Re-loading fragment with SN: " + fragNextLoad.sn);
  8943. }
  8944. }
  8945. } else {
  8946. fragNextLoad = null;
  8947. }
  8948. } else if (fragNextLoad.backtracked) {
  8949. // Only backtrack a max of 1 consecutive fragment to prevent sliding back too far when little or no frags start with keyframes
  8950. if (nextSnFrag && nextSnFrag.backtracked) {
  8951. logger["logger"].warn("Already backtracked from fragment " + nextSnFrag.sn + ", will not backtrack to fragment " + fragNextLoad.sn + ". Loading fragment " + nextSnFrag.sn);
  8952. fragNextLoad = nextSnFrag;
  8953. } else {
  8954. // If a fragment has dropped frames and it's in a same level/sequence, load the previous fragment to try and find the keyframe
  8955. // 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
  8956. logger["logger"].warn('Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe');
  8957. fragNextLoad.dropped = 0;
  8958. if (prevSnFrag) {
  8959. fragNextLoad = prevSnFrag;
  8960. fragNextLoad.backtracked = true;
  8961. } else if (curSNIdx) {
  8962. // can't backtrack on very first fragment
  8963. fragNextLoad = null;
  8964. }
  8965. }
  8966. }
  8967. }
  8968. }
  8969. return fragNextLoad;
  8970. };
  8971. _proto._loadKey = function _loadKey(frag, levelDetails) {
  8972. logger["logger"].log("Loading key for " + frag.sn + " of [" + levelDetails.startSN + "-" + levelDetails.endSN + "], level " + this.level);
  8973. this.state = State.KEY_LOADING;
  8974. this.hls.trigger(events["default"].KEY_LOADING, {
  8975. frag: frag
  8976. });
  8977. };
  8978. _proto._loadFragment = function _loadFragment(frag, levelDetails, pos, bufferEnd) {
  8979. // Check if fragment is not loaded
  8980. var fragState = this.fragmentTracker.getState(frag);
  8981. this.fragCurrent = frag;
  8982. if (frag.sn !== 'initSegment') {
  8983. this.startFragRequested = true;
  8984. } // Don't update nextLoadPosition for fragments which are not buffered
  8985. if (Object(number["isFiniteNumber"])(frag.sn) && !frag.bitrateTest) {
  8986. this.nextLoadPosition = frag.start + frag.duration;
  8987. } // Allow backtracked fragments to load
  8988. if (frag.backtracked || fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
  8989. frag.autoLevel = this.hls.autoLevelEnabled;
  8990. frag.bitrateTest = this.bitrateTest;
  8991. logger["logger"].log("Loading " + frag.sn + " of [" + levelDetails.startSN + "-" + levelDetails.endSN + "], level " + this.level + ", " + (this.loadedmetadata ? 'currentTime' : 'nextLoadPosition') + ": " + parseFloat(pos.toFixed(3)) + ", bufferEnd: " + parseFloat(bufferEnd.toFixed(3)));
  8992. this.hls.trigger(events["default"].FRAG_LOADING, {
  8993. frag: frag
  8994. }); // lazy demuxer init, as this could take some time ... do it during frag loading
  8995. if (!this.demuxer) {
  8996. this.demuxer = new demux_demuxer(this.hls, 'main');
  8997. }
  8998. this.state = State.FRAG_LOADING;
  8999. } else if (fragState === FragmentState.APPENDING) {
  9000. // Lower the buffer size and try again
  9001. if (this._reduceMaxBufferLength(frag.duration)) {
  9002. this.fragmentTracker.removeFragment(frag);
  9003. }
  9004. }
  9005. };
  9006. _proto.getBufferedFrag = function getBufferedFrag(position) {
  9007. return this.fragmentTracker.getBufferedFrag(position, PlaylistLevelType.MAIN);
  9008. };
  9009. _proto.followingBufferedFrag = function followingBufferedFrag(frag) {
  9010. if (frag) {
  9011. // try to get range of next fragment (500ms after this range)
  9012. return this.getBufferedFrag(frag.endPTS + 0.5);
  9013. }
  9014. return null;
  9015. };
  9016. _proto._checkFragmentChanged = function _checkFragmentChanged() {
  9017. var fragPlayingCurrent,
  9018. currentTime,
  9019. video = this.media;
  9020. if (video && video.readyState && video.seeking === false) {
  9021. currentTime = video.currentTime;
  9022. /* if video element is in seeked state, currentTime can only increase.
  9023. (assuming that playback rate is positive ...)
  9024. As sometimes currentTime jumps back to zero after a
  9025. media decode error, check this, to avoid seeking back to
  9026. wrong position after a media decode error
  9027. */
  9028. if (currentTime > this.lastCurrentTime) {
  9029. this.lastCurrentTime = currentTime;
  9030. }
  9031. if (BufferHelper.isBuffered(video, currentTime)) {
  9032. fragPlayingCurrent = this.getBufferedFrag(currentTime);
  9033. } else if (BufferHelper.isBuffered(video, currentTime + 0.1)) {
  9034. /* ensure that FRAG_CHANGED event is triggered at startup,
  9035. when first video frame is displayed and playback is paused.
  9036. add a tolerance of 100ms, in case current position is not buffered,
  9037. check if current pos+100ms is buffered and use that buffer range
  9038. for FRAG_CHANGED event reporting */
  9039. fragPlayingCurrent = this.getBufferedFrag(currentTime + 0.1);
  9040. }
  9041. if (fragPlayingCurrent) {
  9042. var fragPlaying = fragPlayingCurrent;
  9043. if (fragPlaying !== this.fragPlaying) {
  9044. this.hls.trigger(events["default"].FRAG_CHANGED, {
  9045. frag: fragPlaying
  9046. });
  9047. var fragPlayingLevel = fragPlaying.level;
  9048. if (!this.fragPlaying || this.fragPlaying.level !== fragPlayingLevel) {
  9049. this.hls.trigger(events["default"].LEVEL_SWITCHED, {
  9050. level: fragPlayingLevel
  9051. });
  9052. }
  9053. this.fragPlaying = fragPlaying;
  9054. }
  9055. }
  9056. }
  9057. }
  9058. /*
  9059. on immediate level switch :
  9060. - pause playback if playing
  9061. - cancel any pending load request
  9062. - and trigger a buffer flush
  9063. */
  9064. ;
  9065. _proto.immediateLevelSwitch = function immediateLevelSwitch() {
  9066. logger["logger"].log('immediateLevelSwitch');
  9067. if (!this.immediateSwitch) {
  9068. this.immediateSwitch = true;
  9069. var media = this.media,
  9070. previouslyPaused;
  9071. if (media) {
  9072. previouslyPaused = media.paused;
  9073. if (!previouslyPaused) {
  9074. media.pause();
  9075. }
  9076. } else {
  9077. // don't restart playback after instant level switch in case media not attached
  9078. previouslyPaused = true;
  9079. }
  9080. this.previouslyPaused = previouslyPaused;
  9081. }
  9082. var fragCurrent = this.fragCurrent;
  9083. if (fragCurrent && fragCurrent.loader) {
  9084. fragCurrent.loader.abort();
  9085. }
  9086. this.fragCurrent = null; // flush everything
  9087. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  9088. }
  9089. /**
  9090. * on immediate level switch end, after new fragment has been buffered:
  9091. * - nudge video decoder by slightly adjusting video currentTime (if currentTime buffered)
  9092. * - resume the playback if needed
  9093. */
  9094. ;
  9095. _proto.immediateLevelSwitchEnd = function immediateLevelSwitchEnd() {
  9096. var media = this.media;
  9097. if (media && media.buffered.length) {
  9098. this.immediateSwitch = false;
  9099. if (media.currentTime > 0 && BufferHelper.isBuffered(media, media.currentTime)) {
  9100. // only nudge if currentTime is buffered
  9101. media.currentTime -= 0.0001;
  9102. }
  9103. if (!this.previouslyPaused) {
  9104. media.play();
  9105. }
  9106. }
  9107. }
  9108. /**
  9109. * try to switch ASAP without breaking video playback:
  9110. * in order to ensure smooth but quick level switching,
  9111. * we need to find the next flushable buffer range
  9112. * we should take into account new segment fetch time
  9113. */
  9114. ;
  9115. _proto.nextLevelSwitch = function nextLevelSwitch() {
  9116. var media = this.media; // ensure that media is defined and that metadata are available (to retrieve currentTime)
  9117. if (media && media.readyState) {
  9118. var fetchdelay;
  9119. var fragPlayingCurrent = this.getBufferedFrag(media.currentTime);
  9120. if (fragPlayingCurrent && fragPlayingCurrent.startPTS > 1) {
  9121. // flush buffer preceding current fragment (flush until current fragment start offset)
  9122. // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
  9123. this.flushMainBuffer(0, fragPlayingCurrent.startPTS - 1);
  9124. }
  9125. if (!media.paused) {
  9126. // add a safety delay of 1s
  9127. var nextLevelId = this.hls.nextLoadLevel,
  9128. nextLevel = this.levels[nextLevelId],
  9129. fragLastKbps = this.fragLastKbps;
  9130. if (fragLastKbps && this.fragCurrent) {
  9131. fetchdelay = this.fragCurrent.duration * nextLevel.bitrate / (1000 * fragLastKbps) + 1;
  9132. } else {
  9133. fetchdelay = 0;
  9134. }
  9135. } else {
  9136. fetchdelay = 0;
  9137. } // logger.log('fetchdelay:'+fetchdelay);
  9138. // find buffer range that will be reached once new fragment will be fetched
  9139. var bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
  9140. if (bufferedFrag) {
  9141. // we can flush buffer range following this one without stalling playback
  9142. var nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);
  9143. if (nextBufferedFrag) {
  9144. // if we are here, we can also cancel any loading/demuxing in progress, as they are useless
  9145. var fragCurrent = this.fragCurrent;
  9146. if (fragCurrent && fragCurrent.loader) {
  9147. fragCurrent.loader.abort();
  9148. }
  9149. this.fragCurrent = null; // start flush position is the start PTS of next buffered frag.
  9150. // we use frag.naxStartPTS which is max(audio startPTS, video startPTS).
  9151. // in case there is a small PTS Delta between audio and video, using maxStartPTS avoids flushing last samples from current fragment
  9152. var startPts = Math.max(bufferedFrag.endPTS, nextBufferedFrag.maxStartPTS + Math.min(this.config.maxFragLookUpTolerance, nextBufferedFrag.duration));
  9153. this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);
  9154. }
  9155. }
  9156. }
  9157. };
  9158. _proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset) {
  9159. this.state = State.BUFFER_FLUSHING;
  9160. var flushScope = {
  9161. startOffset: startOffset,
  9162. endOffset: endOffset
  9163. }; // if alternate audio tracks are used, only flush video, otherwise flush everything
  9164. if (this.altAudio) {
  9165. flushScope.type = 'video';
  9166. }
  9167. this.hls.trigger(events["default"].BUFFER_FLUSHING, flushScope);
  9168. };
  9169. _proto.onMediaAttached = function onMediaAttached(data) {
  9170. var media = this.media = this.mediaBuffer = data.media;
  9171. this.onvseeking = this.onMediaSeeking.bind(this);
  9172. this.onvseeked = this.onMediaSeeked.bind(this);
  9173. this.onvended = this.onMediaEnded.bind(this);
  9174. media.addEventListener('seeking', this.onvseeking);
  9175. media.addEventListener('seeked', this.onvseeked);
  9176. media.addEventListener('ended', this.onvended);
  9177. var config = this.config;
  9178. if (this.levels && config.autoStartLoad) {
  9179. this.hls.startLoad(config.startPosition);
  9180. }
  9181. this.gapController = new gap_controller_GapController(config, media, this.fragmentTracker, this.hls);
  9182. };
  9183. _proto.onMediaDetaching = function onMediaDetaching() {
  9184. var media = this.media;
  9185. if (media && media.ended) {
  9186. logger["logger"].log('MSE detaching and video ended, reset startPosition');
  9187. this.startPosition = this.lastCurrentTime = 0;
  9188. } // reset fragment backtracked flag
  9189. var levels = this.levels;
  9190. if (levels) {
  9191. levels.forEach(function (level) {
  9192. if (level.details) {
  9193. level.details.fragments.forEach(function (fragment) {
  9194. fragment.backtracked = undefined;
  9195. });
  9196. }
  9197. });
  9198. } // remove video listeners
  9199. if (media) {
  9200. media.removeEventListener('seeking', this.onvseeking);
  9201. media.removeEventListener('seeked', this.onvseeked);
  9202. media.removeEventListener('ended', this.onvended);
  9203. this.onvseeking = this.onvseeked = this.onvended = null;
  9204. }
  9205. this.fragmentTracker.removeAllFragments();
  9206. this.media = this.mediaBuffer = null;
  9207. this.loadedmetadata = false;
  9208. this.stopLoad();
  9209. };
  9210. _proto.onMediaSeeked = function onMediaSeeked() {
  9211. var media = this.media;
  9212. var currentTime = media ? media.currentTime : undefined;
  9213. if (Object(number["isFiniteNumber"])(currentTime)) {
  9214. logger["logger"].log("media seeked to " + currentTime.toFixed(3));
  9215. } // tick to speed up FRAGMENT_PLAYING triggering
  9216. this.tick();
  9217. };
  9218. _proto.onManifestLoading = function onManifestLoading() {
  9219. // reset buffer on manifest loading
  9220. logger["logger"].log('trigger BUFFER_RESET');
  9221. this.hls.trigger(events["default"].BUFFER_RESET);
  9222. this.fragmentTracker.removeAllFragments();
  9223. this.stalled = false;
  9224. this.startPosition = this.lastCurrentTime = 0;
  9225. };
  9226. _proto.onManifestParsed = function onManifestParsed(data) {
  9227. var aac = false,
  9228. heaac = false,
  9229. codec;
  9230. data.levels.forEach(function (level) {
  9231. // detect if we have different kind of audio codecs used amongst playlists
  9232. codec = level.audioCodec;
  9233. if (codec) {
  9234. if (codec.indexOf('mp4a.40.2') !== -1) {
  9235. aac = true;
  9236. }
  9237. if (codec.indexOf('mp4a.40.5') !== -1) {
  9238. heaac = true;
  9239. }
  9240. }
  9241. });
  9242. this.audioCodecSwitch = aac && heaac;
  9243. if (this.audioCodecSwitch) {
  9244. logger["logger"].log('both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
  9245. }
  9246. this.altAudio = data.altAudio;
  9247. this.levels = data.levels;
  9248. this.startFragRequested = false;
  9249. var config = this.config;
  9250. if (config.autoStartLoad || this.forceStartLoad) {
  9251. this.hls.startLoad(config.startPosition);
  9252. }
  9253. };
  9254. _proto.onLevelLoaded = function onLevelLoaded(data) {
  9255. var newDetails = data.details;
  9256. var newLevelId = data.level;
  9257. var lastLevel = this.levels[this.levelLastLoaded];
  9258. var curLevel = this.levels[newLevelId];
  9259. var duration = newDetails.totalduration;
  9260. var sliding = 0;
  9261. logger["logger"].log("level " + newLevelId + " loaded [" + newDetails.startSN + "," + newDetails.endSN + "],duration:" + duration);
  9262. if (newDetails.live || curLevel.details && curLevel.details.live) {
  9263. var curDetails = curLevel.details;
  9264. if (curDetails && newDetails.fragments.length > 0) {
  9265. // we already have details for that level, merge them
  9266. mergeDetails(curDetails, newDetails);
  9267. sliding = newDetails.fragments[0].start;
  9268. this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);
  9269. if (newDetails.PTSKnown && Object(number["isFiniteNumber"])(sliding)) {
  9270. logger["logger"].log("live playlist sliding:" + sliding.toFixed(3));
  9271. } else {
  9272. logger["logger"].log('live playlist - outdated PTS, unknown sliding');
  9273. alignStream(this.fragPrevious, lastLevel, newDetails);
  9274. }
  9275. } else {
  9276. logger["logger"].log('live playlist - first load, unknown sliding');
  9277. newDetails.PTSKnown = false;
  9278. alignStream(this.fragPrevious, lastLevel, newDetails);
  9279. }
  9280. } else {
  9281. newDetails.PTSKnown = false;
  9282. } // override level info
  9283. curLevel.details = newDetails;
  9284. this.levelLastLoaded = newLevelId;
  9285. this.hls.trigger(events["default"].LEVEL_UPDATED, {
  9286. details: newDetails,
  9287. level: newLevelId
  9288. });
  9289. if (this.startFragRequested === false) {
  9290. // compute start position if set to -1. use it straight away if value is defined
  9291. if (this.startPosition === -1 || this.lastCurrentTime === -1) {
  9292. // first, check if start time offset has been set in playlist, if yes, use this value
  9293. var startTimeOffset = newDetails.startTimeOffset;
  9294. if (Object(number["isFiniteNumber"])(startTimeOffset)) {
  9295. if (startTimeOffset < 0) {
  9296. logger["logger"].log("negative start time offset " + startTimeOffset + ", count from end of last fragment");
  9297. startTimeOffset = sliding + duration + startTimeOffset;
  9298. }
  9299. logger["logger"].log("start time offset found in playlist, adjust startPosition to " + startTimeOffset);
  9300. this.startPosition = startTimeOffset;
  9301. } else {
  9302. // if live playlist, set start position to be fragment N-this.config.liveSyncDurationCount (usually 3)
  9303. if (newDetails.live) {
  9304. this.startPosition = this.computeLivePosition(sliding, newDetails);
  9305. logger["logger"].log("configure startPosition to " + this.startPosition);
  9306. } else {
  9307. this.startPosition = 0;
  9308. }
  9309. }
  9310. this.lastCurrentTime = this.startPosition;
  9311. }
  9312. this.nextLoadPosition = this.startPosition;
  9313. } // only switch batck to IDLE state if we were waiting for level to start downloading a new fragment
  9314. if (this.state === State.WAITING_LEVEL) {
  9315. this.state = State.IDLE;
  9316. } // trigger handler right now
  9317. this.tick();
  9318. };
  9319. _proto.onKeyLoaded = function onKeyLoaded() {
  9320. if (this.state === State.KEY_LOADING) {
  9321. this.state = State.IDLE;
  9322. this.tick();
  9323. }
  9324. };
  9325. _proto.onFragLoaded = function onFragLoaded(data) {
  9326. var fragCurrent = this.fragCurrent,
  9327. hls = this.hls,
  9328. levels = this.levels,
  9329. media = this.media;
  9330. var fragLoaded = data.frag;
  9331. if (this.state === State.FRAG_LOADING && fragCurrent && fragLoaded.type === 'main' && fragLoaded.level === fragCurrent.level && fragLoaded.sn === fragCurrent.sn) {
  9332. var stats = data.stats;
  9333. var currentLevel = levels[fragCurrent.level];
  9334. var details = currentLevel.details; // reset frag bitrate test in any case after frag loaded event
  9335. // if this frag was loaded to perform a bitrate test AND if hls.nextLoadLevel is greater than 0
  9336. // then this means that we should be able to load a fragment at a higher quality level
  9337. this.bitrateTest = false;
  9338. this.stats = stats;
  9339. logger["logger"].log("Loaded " + fragCurrent.sn + " of [" + details.startSN + " ," + details.endSN + "],level " + fragCurrent.level);
  9340. if (fragLoaded.bitrateTest && hls.nextLoadLevel) {
  9341. // switch back to IDLE state ... we just loaded a fragment to determine adequate start bitrate and initialize autoswitch algo
  9342. this.state = State.IDLE;
  9343. this.startFragRequested = false;
  9344. stats.tparsed = stats.tbuffered = window.performance.now();
  9345. hls.trigger(events["default"].FRAG_BUFFERED, {
  9346. stats: stats,
  9347. frag: fragCurrent,
  9348. id: 'main'
  9349. });
  9350. this.tick();
  9351. } else if (fragLoaded.sn === 'initSegment') {
  9352. this.state = State.IDLE;
  9353. stats.tparsed = stats.tbuffered = window.performance.now();
  9354. details.initSegment.data = data.payload;
  9355. hls.trigger(events["default"].FRAG_BUFFERED, {
  9356. stats: stats,
  9357. frag: fragCurrent,
  9358. id: 'main'
  9359. });
  9360. this.tick();
  9361. } else {
  9362. logger["logger"].log("Parsing " + fragCurrent.sn + " of [" + details.startSN + " ," + details.endSN + "],level " + fragCurrent.level + ", cc " + fragCurrent.cc);
  9363. this.state = State.PARSING;
  9364. this.pendingBuffering = true;
  9365. this.appended = false; // Bitrate test frags are not usually buffered so the fragment tracker ignores them. If Hls.js decides to buffer
  9366. // it (and therefore ends up at this line), then the fragment tracker needs to be manually informed.
  9367. if (fragLoaded.bitrateTest) {
  9368. fragLoaded.bitrateTest = false;
  9369. this.fragmentTracker.onFragLoaded({
  9370. frag: fragLoaded
  9371. });
  9372. } // 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)
  9373. var accurateTimeOffset = !(media && media.seeking) && (details.PTSKnown || !details.live);
  9374. var initSegmentData = details.initSegment ? details.initSegment.data : [];
  9375. var audioCodec = this._getAudioCodec(currentLevel); // transmux the MPEG-TS data to ISO-BMFF segments
  9376. var demuxer = this.demuxer = this.demuxer || new demux_demuxer(this.hls, 'main');
  9377. demuxer.push(data.payload, initSegmentData, audioCodec, currentLevel.videoCodec, fragCurrent, details.totalduration, accurateTimeOffset);
  9378. }
  9379. }
  9380. this.fragLoadError = 0;
  9381. };
  9382. _proto.onFragParsingInitSegment = function onFragParsingInitSegment(data) {
  9383. var fragCurrent = this.fragCurrent;
  9384. var fragNew = data.frag;
  9385. if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {
  9386. var tracks = data.tracks,
  9387. trackName,
  9388. track;
  9389. this.audioOnly = tracks.audio && !tracks.video; // if audio track is expected to come from audio stream controller, discard any coming from main
  9390. if (this.altAudio && !this.audioOnly) {
  9391. delete tracks.audio;
  9392. } // include levelCodec in audio and video tracks
  9393. track = tracks.audio;
  9394. if (track) {
  9395. var audioCodec = this.levels[this.level].audioCodec,
  9396. ua = navigator.userAgent.toLowerCase();
  9397. if (audioCodec && this.audioCodecSwap) {
  9398. logger["logger"].log('swapping playlist audio codec');
  9399. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  9400. audioCodec = 'mp4a.40.2';
  9401. } else {
  9402. audioCodec = 'mp4a.40.5';
  9403. }
  9404. } // in case AAC and HE-AAC audio codecs are signalled in manifest
  9405. // force HE-AAC , as it seems that most browsers prefers that way,
  9406. // except for mono streams OR on FF
  9407. // these conditions might need to be reviewed ...
  9408. if (this.audioCodecSwitch) {
  9409. // don't force HE-AAC if mono stream
  9410. if (track.metadata.channelCount !== 1 && // don't force HE-AAC if firefox
  9411. ua.indexOf('firefox') === -1) {
  9412. audioCodec = 'mp4a.40.5';
  9413. }
  9414. } // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise
  9415. if (ua.indexOf('android') !== -1 && track.container !== 'audio/mpeg') {
  9416. // Exclude mpeg audio
  9417. audioCodec = 'mp4a.40.2';
  9418. logger["logger"].log("Android: force audio codec to " + audioCodec);
  9419. }
  9420. track.levelCodec = audioCodec;
  9421. track.id = data.id;
  9422. }
  9423. track = tracks.video;
  9424. if (track) {
  9425. track.levelCodec = this.levels[this.level].videoCodec;
  9426. track.id = data.id;
  9427. }
  9428. this.hls.trigger(events["default"].BUFFER_CODECS, tracks); // loop through tracks that are going to be provided to bufferController
  9429. for (trackName in tracks) {
  9430. track = tracks[trackName];
  9431. logger["logger"].log("main track:" + trackName + ",container:" + track.container + ",codecs[level/parsed]=[" + track.levelCodec + "/" + track.codec + "]");
  9432. var initSegment = track.initSegment;
  9433. if (initSegment) {
  9434. this.appended = true; // arm pending Buffering flag before appending a segment
  9435. this.pendingBuffering = true;
  9436. this.hls.trigger(events["default"].BUFFER_APPENDING, {
  9437. type: trackName,
  9438. data: initSegment,
  9439. parent: 'main',
  9440. content: 'initSegment'
  9441. });
  9442. }
  9443. } // trigger handler right now
  9444. this.tick();
  9445. }
  9446. };
  9447. _proto.onFragParsingData = function onFragParsingData(data) {
  9448. var _this2 = this;
  9449. var fragCurrent = this.fragCurrent;
  9450. var fragNew = data.frag;
  9451. 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
  9452. this.state === State.PARSING) {
  9453. var level = this.levels[this.level],
  9454. frag = fragCurrent;
  9455. if (!Object(number["isFiniteNumber"])(data.endPTS)) {
  9456. data.endPTS = data.startPTS + fragCurrent.duration;
  9457. data.endDTS = data.startDTS + fragCurrent.duration;
  9458. }
  9459. if (data.hasAudio === true) {
  9460. frag.addElementaryStream(ElementaryStreamTypes.AUDIO);
  9461. }
  9462. if (data.hasVideo === true) {
  9463. frag.addElementaryStream(ElementaryStreamTypes.VIDEO);
  9464. }
  9465. logger["logger"].log("Parsed " + data.type + ",PTS:[" + data.startPTS.toFixed(3) + "," + data.endPTS.toFixed(3) + "],DTS:[" + data.startDTS.toFixed(3) + "/" + data.endDTS.toFixed(3) + "],nb:" + data.nb + ",dropped:" + (data.dropped || 0)); // Detect gaps in a fragment and try to fix it by finding a keyframe in the previous fragment (see _findFragments)
  9466. if (data.type === 'video') {
  9467. frag.dropped = data.dropped;
  9468. if (frag.dropped) {
  9469. if (!frag.backtracked) {
  9470. var levelDetails = level.details;
  9471. if (levelDetails && frag.sn === levelDetails.startSN) {
  9472. logger["logger"].warn('missing video frame(s) on first frag, appending with gap', frag.sn);
  9473. } else {
  9474. logger["logger"].warn('missing video frame(s), backtracking fragment', frag.sn); // Return back to the IDLE state without appending to buffer
  9475. // Causes findFragments to backtrack a segment and find the keyframe
  9476. // Audio fragments arriving before video sets the nextLoadPosition, causing _findFragments to skip the backtracked fragment
  9477. this.fragmentTracker.removeFragment(frag);
  9478. frag.backtracked = true;
  9479. this.nextLoadPosition = data.startPTS;
  9480. this.state = State.IDLE;
  9481. this.fragPrevious = frag;
  9482. if (this.demuxer) {
  9483. this.demuxer.destroy();
  9484. this.demuxer = null;
  9485. }
  9486. this.tick();
  9487. return;
  9488. }
  9489. } else {
  9490. logger["logger"].warn('Already backtracked on this fragment, appending with the gap', frag.sn);
  9491. }
  9492. } else {
  9493. // Only reset the backtracked flag if we've loaded the frag without any dropped frames
  9494. frag.backtracked = false;
  9495. }
  9496. }
  9497. var drift = updateFragPTSDTS(level.details, frag, data.startPTS, data.endPTS, data.startDTS, data.endDTS),
  9498. hls = this.hls;
  9499. hls.trigger(events["default"].LEVEL_PTS_UPDATED, {
  9500. details: level.details,
  9501. level: this.level,
  9502. drift: drift,
  9503. type: data.type,
  9504. start: data.startPTS,
  9505. end: data.endPTS
  9506. }); // has remuxer dropped video frames located before first keyframe ?
  9507. [data.data1, data.data2].forEach(function (buffer) {
  9508. // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)
  9509. // in that case it is useless to append following segments
  9510. if (buffer && buffer.length && _this2.state === State.PARSING) {
  9511. _this2.appended = true; // arm pending Buffering flag before appending a segment
  9512. _this2.pendingBuffering = true;
  9513. hls.trigger(events["default"].BUFFER_APPENDING, {
  9514. type: data.type,
  9515. data: buffer,
  9516. parent: 'main',
  9517. content: 'data'
  9518. });
  9519. }
  9520. }); // trigger handler right now
  9521. this.tick();
  9522. }
  9523. };
  9524. _proto.onFragParsed = function onFragParsed(data) {
  9525. var fragCurrent = this.fragCurrent;
  9526. var fragNew = data.frag;
  9527. if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {
  9528. this.stats.tparsed = window.performance.now();
  9529. this.state = State.PARSED;
  9530. this._checkAppendedParsed();
  9531. }
  9532. };
  9533. _proto.onAudioTrackSwitching = function onAudioTrackSwitching(data) {
  9534. // if any URL found on new audio track, it is an alternate audio track
  9535. var fromAltAudio = this.altAudio;
  9536. var altAudio = !!data.url;
  9537. var trackId = data.id; // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered
  9538. // don't do anything if we switch to alt audio: audio stream controller is handling it.
  9539. // we will just have to change buffer scheduling on audioTrackSwitched
  9540. if (!altAudio) {
  9541. if (this.mediaBuffer !== this.media) {
  9542. logger["logger"].log('switching on main audio, use media.buffered to schedule main fragment loading');
  9543. this.mediaBuffer = this.media;
  9544. var fragCurrent = this.fragCurrent; // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch
  9545. if (fragCurrent.loader) {
  9546. logger["logger"].log('switching to main audio track, cancel main fragment load');
  9547. fragCurrent.loader.abort();
  9548. }
  9549. this.fragCurrent = null;
  9550. this.fragPrevious = null; // destroy demuxer to force init segment generation (following audio switch)
  9551. if (this.demuxer) {
  9552. this.demuxer.destroy();
  9553. this.demuxer = null;
  9554. } // switch to IDLE state to load new fragment
  9555. this.state = State.IDLE;
  9556. }
  9557. var hls = this.hls; // If switching from alt to main audio, flush all audio and trigger track switched
  9558. if (fromAltAudio) {
  9559. hls.trigger(events["default"].BUFFER_FLUSHING, {
  9560. startOffset: 0,
  9561. endOffset: Number.POSITIVE_INFINITY,
  9562. type: 'audio'
  9563. });
  9564. }
  9565. hls.trigger(events["default"].AUDIO_TRACK_SWITCHED, {
  9566. id: trackId
  9567. });
  9568. }
  9569. };
  9570. _proto.onAudioTrackSwitched = function onAudioTrackSwitched(data) {
  9571. var trackId = data.id,
  9572. altAudio = !!this.hls.audioTracks[trackId].url;
  9573. if (altAudio) {
  9574. var videoBuffer = this.videoBuffer; // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered
  9575. if (videoBuffer && this.mediaBuffer !== videoBuffer) {
  9576. logger["logger"].log('switching on alternate audio, use video.buffered to schedule main fragment loading');
  9577. this.mediaBuffer = videoBuffer;
  9578. }
  9579. }
  9580. this.altAudio = altAudio;
  9581. this.tick();
  9582. };
  9583. _proto.onBufferCreated = function onBufferCreated(data) {
  9584. var tracks = data.tracks,
  9585. mediaTrack,
  9586. name,
  9587. alternate = false;
  9588. for (var type in tracks) {
  9589. var track = tracks[type];
  9590. if (track.id === 'main') {
  9591. name = type;
  9592. mediaTrack = track; // keep video source buffer reference
  9593. if (type === 'video') {
  9594. this.videoBuffer = tracks[type].buffer;
  9595. }
  9596. } else {
  9597. alternate = true;
  9598. }
  9599. }
  9600. if (alternate && mediaTrack) {
  9601. logger["logger"].log("alternate track found, use " + name + ".buffered to schedule main fragment loading");
  9602. this.mediaBuffer = mediaTrack.buffer;
  9603. } else {
  9604. this.mediaBuffer = this.media;
  9605. }
  9606. };
  9607. _proto.onBufferAppended = function onBufferAppended(data) {
  9608. if (data.parent === 'main') {
  9609. var state = this.state;
  9610. if (state === State.PARSING || state === State.PARSED) {
  9611. // check if all buffers have been appended
  9612. this.pendingBuffering = data.pending > 0;
  9613. this._checkAppendedParsed();
  9614. }
  9615. }
  9616. };
  9617. _proto._checkAppendedParsed = function _checkAppendedParsed() {
  9618. // trigger handler right now
  9619. if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) {
  9620. var frag = this.fragCurrent;
  9621. if (frag) {
  9622. var media = this.mediaBuffer ? this.mediaBuffer : this.media;
  9623. logger["logger"].log("main buffered : " + time_ranges.toString(media.buffered));
  9624. this.fragPrevious = frag;
  9625. var stats = this.stats;
  9626. stats.tbuffered = window.performance.now(); // we should get rid of this.fragLastKbps
  9627. this.fragLastKbps = Math.round(8 * stats.total / (stats.tbuffered - stats.tfirst));
  9628. this.hls.trigger(events["default"].FRAG_BUFFERED, {
  9629. stats: stats,
  9630. frag: frag,
  9631. id: 'main'
  9632. });
  9633. this.state = State.IDLE;
  9634. } // Do not tick when _seekToStartPos needs to be called as seeking to the start can fail on live streams at this point
  9635. if (this.loadedmetadata || this.startPosition <= 0) {
  9636. this.tick();
  9637. }
  9638. }
  9639. };
  9640. _proto.onError = function onError(data) {
  9641. var frag = data.frag || this.fragCurrent; // don't handle frag error not related to main fragment
  9642. if (frag && frag.type !== 'main') {
  9643. return;
  9644. } // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
  9645. var mediaBuffered = !!this.media && BufferHelper.isBuffered(this.media, this.media.currentTime) && BufferHelper.isBuffered(this.media, this.media.currentTime + 0.5);
  9646. switch (data.details) {
  9647. case errors["ErrorDetails"].FRAG_LOAD_ERROR:
  9648. case errors["ErrorDetails"].FRAG_LOAD_TIMEOUT:
  9649. case errors["ErrorDetails"].KEY_LOAD_ERROR:
  9650. case errors["ErrorDetails"].KEY_LOAD_TIMEOUT:
  9651. if (!data.fatal) {
  9652. // keep retrying until the limit will be reached
  9653. if (this.fragLoadError + 1 <= this.config.fragLoadingMaxRetry) {
  9654. // exponential backoff capped to config.fragLoadingMaxRetryTimeout
  9655. var delay = Math.min(Math.pow(2, this.fragLoadError) * this.config.fragLoadingRetryDelay, this.config.fragLoadingMaxRetryTimeout);
  9656. logger["logger"].warn("mediaController: frag loading failed, retry in " + delay + " ms");
  9657. this.retryDate = window.performance.now() + delay; // retry loading state
  9658. // if loadedmetadata is not set, it means that we are emergency switch down on first frag
  9659. // in that case, reset startFragRequested flag
  9660. if (!this.loadedmetadata) {
  9661. this.startFragRequested = false;
  9662. this.nextLoadPosition = this.startPosition;
  9663. }
  9664. this.fragLoadError++;
  9665. this.state = State.FRAG_LOADING_WAITING_RETRY;
  9666. } else {
  9667. logger["logger"].error("mediaController: " + data.details + " reaches max retry, redispatch as fatal ..."); // switch error to fatal
  9668. data.fatal = true;
  9669. this.state = State.ERROR;
  9670. }
  9671. }
  9672. break;
  9673. case errors["ErrorDetails"].LEVEL_LOAD_ERROR:
  9674. case errors["ErrorDetails"].LEVEL_LOAD_TIMEOUT:
  9675. if (this.state !== State.ERROR) {
  9676. if (data.fatal) {
  9677. // if fatal error, stop processing
  9678. this.state = State.ERROR;
  9679. logger["logger"].warn("streamController: " + data.details + ",switch to " + this.state + " state ...");
  9680. } else {
  9681. // in case of non fatal error while loading level, if level controller is not retrying to load level , switch back to IDLE
  9682. if (!data.levelRetry && this.state === State.WAITING_LEVEL) {
  9683. this.state = State.IDLE;
  9684. }
  9685. }
  9686. }
  9687. break;
  9688. case errors["ErrorDetails"].BUFFER_FULL_ERROR:
  9689. // if in appending state
  9690. if (data.parent === 'main' && (this.state === State.PARSING || this.state === State.PARSED)) {
  9691. // reduce max buf len if current position is buffered
  9692. if (mediaBuffered) {
  9693. this._reduceMaxBufferLength(this.config.maxBufferLength);
  9694. this.state = State.IDLE;
  9695. } else {
  9696. // current position is not buffered, but browser is still complaining about buffer full error
  9697. // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
  9698. // in that case flush the whole buffer to recover
  9699. logger["logger"].warn('buffer full error also media.currentTime is not buffered, flush everything');
  9700. this.fragCurrent = null; // flush everything
  9701. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  9702. }
  9703. }
  9704. break;
  9705. default:
  9706. break;
  9707. }
  9708. };
  9709. _proto._reduceMaxBufferLength = function _reduceMaxBufferLength(minLength) {
  9710. var config = this.config;
  9711. if (config.maxMaxBufferLength >= minLength) {
  9712. // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
  9713. config.maxMaxBufferLength /= 2;
  9714. logger["logger"].warn("main:reduce max buffer length to " + config.maxMaxBufferLength + "s");
  9715. return true;
  9716. }
  9717. return false;
  9718. }
  9719. /**
  9720. * Checks the health of the buffer and attempts to resolve playback stalls.
  9721. * @private
  9722. */
  9723. ;
  9724. _proto._checkBuffer = function _checkBuffer() {
  9725. var media = this.media;
  9726. if (!media || media.readyState === 0) {
  9727. // Exit early if we don't have media or if the media hasn't bufferd anything yet (readyState 0)
  9728. return;
  9729. }
  9730. var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;
  9731. var buffered = mediaBuffer.buffered;
  9732. if (!this.loadedmetadata && buffered.length) {
  9733. this.loadedmetadata = true;
  9734. this._seekToStartPos();
  9735. } else if (this.immediateSwitch) {
  9736. this.immediateLevelSwitchEnd();
  9737. } else {
  9738. this.gapController.poll(this.lastCurrentTime, buffered);
  9739. }
  9740. };
  9741. _proto.onFragLoadEmergencyAborted = function onFragLoadEmergencyAborted() {
  9742. this.state = State.IDLE; // if loadedmetadata is not set, it means that we are emergency switch down on first frag
  9743. // in that case, reset startFragRequested flag
  9744. if (!this.loadedmetadata) {
  9745. this.startFragRequested = false;
  9746. this.nextLoadPosition = this.startPosition;
  9747. }
  9748. this.tick();
  9749. };
  9750. _proto.onBufferFlushed = function onBufferFlushed() {
  9751. /* after successful buffer flushing, filter flushed fragments from bufferedFrags
  9752. use mediaBuffered instead of media (so that we will check against video.buffered ranges in case of alt audio track)
  9753. */
  9754. var media = this.mediaBuffer ? this.mediaBuffer : this.media;
  9755. if (media) {
  9756. // filter fragments potentially evicted from buffer. this is to avoid memleak on live streams
  9757. var elementaryStreamType = this.audioOnly ? ElementaryStreamTypes.AUDIO : ElementaryStreamTypes.VIDEO;
  9758. this.fragmentTracker.detectEvictedFragments(elementaryStreamType, media.buffered);
  9759. } // move to IDLE once flush complete. this should trigger new fragment loading
  9760. this.state = State.IDLE; // reset reference to frag
  9761. this.fragPrevious = null;
  9762. };
  9763. _proto.onLevelsUpdated = function onLevelsUpdated(data) {
  9764. this.levels = data.levels;
  9765. };
  9766. _proto.swapAudioCodec = function swapAudioCodec() {
  9767. this.audioCodecSwap = !this.audioCodecSwap;
  9768. }
  9769. /**
  9770. * Seeks to the set startPosition if not equal to the mediaElement's current time.
  9771. * @private
  9772. */
  9773. ;
  9774. _proto._seekToStartPos = function _seekToStartPos() {
  9775. var media = this.media;
  9776. var currentTime = media.currentTime;
  9777. var startPosition = this.startPosition; // only adjust currentTime if different from startPosition or if startPosition not buffered
  9778. // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered
  9779. if (currentTime !== startPosition && startPosition >= 0) {
  9780. if (media.seeking) {
  9781. logger["logger"].log("could not seek to " + startPosition + ", already seeking at " + currentTime);
  9782. return;
  9783. }
  9784. var bufferStart = media.buffered.length ? media.buffered.start(0) : 0;
  9785. var delta = bufferStart - startPosition;
  9786. if (delta > 0 && delta < this.config.maxBufferHole) {
  9787. logger["logger"].log("adjusting start position by " + delta + " to match buffer start");
  9788. startPosition += delta;
  9789. this.startPosition = startPosition;
  9790. }
  9791. logger["logger"].log("seek to target start position " + startPosition + " from current time " + currentTime + ". ready state " + media.readyState);
  9792. media.currentTime = startPosition;
  9793. }
  9794. };
  9795. _proto._getAudioCodec = function _getAudioCodec(currentLevel) {
  9796. var audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
  9797. if (this.audioCodecSwap) {
  9798. logger["logger"].log('swapping playlist audio codec');
  9799. if (audioCodec) {
  9800. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  9801. audioCodec = 'mp4a.40.2';
  9802. } else {
  9803. audioCodec = 'mp4a.40.5';
  9804. }
  9805. }
  9806. }
  9807. return audioCodec;
  9808. };
  9809. stream_controller_createClass(StreamController, [{
  9810. key: "state",
  9811. set: function set(nextState) {
  9812. if (this.state !== nextState) {
  9813. var previousState = this.state;
  9814. this._state = nextState;
  9815. logger["logger"].log("main stream-controller: " + previousState + "->" + nextState);
  9816. this.hls.trigger(events["default"].STREAM_STATE_TRANSITION, {
  9817. previousState: previousState,
  9818. nextState: nextState
  9819. });
  9820. }
  9821. },
  9822. get: function get() {
  9823. return this._state;
  9824. }
  9825. }, {
  9826. key: "currentLevel",
  9827. get: function get() {
  9828. var media = this.media;
  9829. if (media) {
  9830. var frag = this.getBufferedFrag(media.currentTime);
  9831. if (frag) {
  9832. return frag.level;
  9833. }
  9834. }
  9835. return -1;
  9836. }
  9837. }, {
  9838. key: "nextBufferedFrag",
  9839. get: function get() {
  9840. var media = this.media;
  9841. if (media) {
  9842. // first get end range of current fragment
  9843. return this.followingBufferedFrag(this.getBufferedFrag(media.currentTime));
  9844. } else {
  9845. return null;
  9846. }
  9847. }
  9848. }, {
  9849. key: "nextLevel",
  9850. get: function get() {
  9851. var frag = this.nextBufferedFrag;
  9852. if (frag) {
  9853. return frag.level;
  9854. } else {
  9855. return -1;
  9856. }
  9857. }
  9858. }, {
  9859. key: "liveSyncPosition",
  9860. get: function get() {
  9861. return this._liveSyncPosition;
  9862. },
  9863. set: function set(value) {
  9864. this._liveSyncPosition = value;
  9865. }
  9866. }]);
  9867. return StreamController;
  9868. }(base_stream_controller_BaseStreamController);
  9869. /* harmony default export */ var stream_controller = (stream_controller_StreamController);
  9870. // CONCATENATED MODULE: ./src/controller/level-controller.js
  9871. function level_controller_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  9872. function level_controller_createClass(Constructor, protoProps, staticProps) { if (protoProps) level_controller_defineProperties(Constructor.prototype, protoProps); if (staticProps) level_controller_defineProperties(Constructor, staticProps); return Constructor; }
  9873. function level_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  9874. /*
  9875. * Level Controller
  9876. */
  9877. var chromeOrFirefox;
  9878. var level_controller_LevelController = /*#__PURE__*/function (_EventHandler) {
  9879. level_controller_inheritsLoose(LevelController, _EventHandler);
  9880. function LevelController(hls) {
  9881. var _this;
  9882. _this = _EventHandler.call(this, hls, events["default"].MANIFEST_LOADED, events["default"].LEVEL_LOADED, events["default"].AUDIO_TRACK_SWITCHED, events["default"].FRAG_LOADED, events["default"].ERROR) || this;
  9883. _this.canload = false;
  9884. _this.currentLevelIndex = null;
  9885. _this.manualLevelIndex = -1;
  9886. _this.timer = null;
  9887. chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase());
  9888. return _this;
  9889. }
  9890. var _proto = LevelController.prototype;
  9891. _proto.onHandlerDestroying = function onHandlerDestroying() {
  9892. this.clearTimer();
  9893. this.manualLevelIndex = -1;
  9894. };
  9895. _proto.clearTimer = function clearTimer() {
  9896. if (this.timer !== null) {
  9897. clearTimeout(this.timer);
  9898. this.timer = null;
  9899. }
  9900. };
  9901. _proto.startLoad = function startLoad() {
  9902. var levels = this._levels;
  9903. this.canload = true;
  9904. this.levelRetryCount = 0; // clean up live level details to force reload them, and reset load errors
  9905. if (levels) {
  9906. levels.forEach(function (level) {
  9907. level.loadError = 0;
  9908. var levelDetails = level.details;
  9909. if (levelDetails && levelDetails.live) {
  9910. level.details = undefined;
  9911. }
  9912. });
  9913. } // speed up live playlist refresh if timer exists
  9914. if (this.timer !== null) {
  9915. this.loadLevel();
  9916. }
  9917. };
  9918. _proto.stopLoad = function stopLoad() {
  9919. this.canload = false;
  9920. };
  9921. _proto.onManifestLoaded = function onManifestLoaded(data) {
  9922. var levels = [];
  9923. var audioTracks = [];
  9924. var bitrateStart;
  9925. var levelSet = {};
  9926. var levelFromSet = null;
  9927. var videoCodecFound = false;
  9928. var audioCodecFound = false; // regroup redundant levels together
  9929. data.levels.forEach(function (level) {
  9930. var attributes = level.attrs;
  9931. level.loadError = 0;
  9932. level.fragmentError = false;
  9933. videoCodecFound = videoCodecFound || !!level.videoCodec;
  9934. audioCodecFound = audioCodecFound || !!level.audioCodec; // erase audio codec info if browser does not support mp4a.40.34.
  9935. // demuxer will autodetect codec and fallback to mpeg/audio
  9936. if (chromeOrFirefox && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) {
  9937. level.audioCodec = undefined;
  9938. }
  9939. levelFromSet = levelSet[level.bitrate]; // FIXME: we would also have to match the resolution here
  9940. if (!levelFromSet) {
  9941. level.url = [level.url];
  9942. level.urlId = 0;
  9943. levelSet[level.bitrate] = level;
  9944. levels.push(level);
  9945. } else {
  9946. levelFromSet.url.push(level.url);
  9947. }
  9948. if (attributes) {
  9949. if (attributes.AUDIO) {
  9950. addGroupId(levelFromSet || level, 'audio', attributes.AUDIO);
  9951. }
  9952. if (attributes.SUBTITLES) {
  9953. addGroupId(levelFromSet || level, 'text', attributes.SUBTITLES);
  9954. }
  9955. }
  9956. }); // remove audio-only level if we also have levels with audio+video codecs signalled
  9957. if (videoCodecFound && audioCodecFound) {
  9958. levels = levels.filter(function (_ref) {
  9959. var videoCodec = _ref.videoCodec;
  9960. return !!videoCodec;
  9961. });
  9962. } // only keep levels with supported audio/video codecs
  9963. levels = levels.filter(function (_ref2) {
  9964. var audioCodec = _ref2.audioCodec,
  9965. videoCodec = _ref2.videoCodec;
  9966. return (!audioCodec || isCodecSupportedInMp4(audioCodec, 'audio')) && (!videoCodec || isCodecSupportedInMp4(videoCodec, 'video'));
  9967. });
  9968. if (data.audioTracks) {
  9969. audioTracks = data.audioTracks.filter(function (track) {
  9970. return !track.audioCodec || isCodecSupportedInMp4(track.audioCodec, 'audio');
  9971. }); // Reassign id's after filtering since they're used as array indices
  9972. audioTracks.forEach(function (track, index) {
  9973. track.id = index;
  9974. });
  9975. }
  9976. if (levels.length > 0) {
  9977. // start bitrate is the first bitrate of the manifest
  9978. bitrateStart = levels[0].bitrate; // sort level on bitrate
  9979. levels.sort(function (a, b) {
  9980. return a.bitrate - b.bitrate;
  9981. });
  9982. this._levels = levels; // find index of first level in sorted levels
  9983. for (var i = 0; i < levels.length; i++) {
  9984. if (levels[i].bitrate === bitrateStart) {
  9985. this._firstLevel = i;
  9986. logger["logger"].log("manifest loaded," + levels.length + " level(s) found, first bitrate:" + bitrateStart);
  9987. break;
  9988. }
  9989. } // Audio is only alternate if manifest include a URI along with the audio group tag,
  9990. // and this is not an audio-only stream where levels contain audio-only
  9991. var audioOnly = audioCodecFound && !videoCodecFound;
  9992. this.hls.trigger(events["default"].MANIFEST_PARSED, {
  9993. levels: levels,
  9994. audioTracks: audioTracks,
  9995. firstLevel: this._firstLevel,
  9996. stats: data.stats,
  9997. audio: audioCodecFound,
  9998. video: videoCodecFound,
  9999. altAudio: !audioOnly && audioTracks.some(function (t) {
  10000. return !!t.url;
  10001. })
  10002. });
  10003. } else {
  10004. this.hls.trigger(events["default"].ERROR, {
  10005. type: errors["ErrorTypes"].MEDIA_ERROR,
  10006. details: errors["ErrorDetails"].MANIFEST_INCOMPATIBLE_CODECS_ERROR,
  10007. fatal: true,
  10008. url: this.hls.url,
  10009. reason: 'no level with compatible codecs found in manifest'
  10010. });
  10011. }
  10012. };
  10013. _proto.setLevelInternal = function setLevelInternal(newLevel) {
  10014. var levels = this._levels;
  10015. var hls = this.hls; // check if level idx is valid
  10016. if (newLevel >= 0 && newLevel < levels.length) {
  10017. // stopping live reloading timer if any
  10018. this.clearTimer();
  10019. if (this.currentLevelIndex !== newLevel) {
  10020. logger["logger"].log("switching to level " + newLevel);
  10021. this.currentLevelIndex = newLevel;
  10022. var levelProperties = levels[newLevel];
  10023. levelProperties.level = newLevel;
  10024. hls.trigger(events["default"].LEVEL_SWITCHING, levelProperties);
  10025. }
  10026. var level = levels[newLevel];
  10027. var levelDetails = level.details; // check if we need to load playlist for this level
  10028. if (!levelDetails || levelDetails.live) {
  10029. // level not retrieved yet, or live playlist we need to (re)load it
  10030. var urlId = level.urlId;
  10031. hls.trigger(events["default"].LEVEL_LOADING, {
  10032. url: level.url[urlId],
  10033. level: newLevel,
  10034. id: urlId
  10035. });
  10036. }
  10037. } else {
  10038. // invalid level id given, trigger error
  10039. hls.trigger(events["default"].ERROR, {
  10040. type: errors["ErrorTypes"].OTHER_ERROR,
  10041. details: errors["ErrorDetails"].LEVEL_SWITCH_ERROR,
  10042. level: newLevel,
  10043. fatal: false,
  10044. reason: 'invalid level idx'
  10045. });
  10046. }
  10047. };
  10048. _proto.onError = function onError(data) {
  10049. if (data.fatal) {
  10050. if (data.type === errors["ErrorTypes"].NETWORK_ERROR) {
  10051. this.clearTimer();
  10052. }
  10053. return;
  10054. }
  10055. var levelError = false,
  10056. fragmentError = false;
  10057. var levelIndex; // try to recover not fatal errors
  10058. switch (data.details) {
  10059. case errors["ErrorDetails"].FRAG_LOAD_ERROR:
  10060. case errors["ErrorDetails"].FRAG_LOAD_TIMEOUT:
  10061. case errors["ErrorDetails"].KEY_LOAD_ERROR:
  10062. case errors["ErrorDetails"].KEY_LOAD_TIMEOUT:
  10063. levelIndex = data.frag.level;
  10064. fragmentError = true;
  10065. break;
  10066. case errors["ErrorDetails"].LEVEL_LOAD_ERROR:
  10067. case errors["ErrorDetails"].LEVEL_LOAD_TIMEOUT:
  10068. levelIndex = data.context.level;
  10069. levelError = true;
  10070. break;
  10071. case errors["ErrorDetails"].REMUX_ALLOC_ERROR:
  10072. levelIndex = data.level;
  10073. levelError = true;
  10074. break;
  10075. }
  10076. if (levelIndex !== undefined) {
  10077. this.recoverLevel(data, levelIndex, levelError, fragmentError);
  10078. }
  10079. }
  10080. /**
  10081. * Switch to a redundant stream if any available.
  10082. * If redundant stream is not available, emergency switch down if ABR mode is enabled.
  10083. *
  10084. * @param {Object} errorEvent
  10085. * @param {Number} levelIndex current level index
  10086. * @param {Boolean} levelError
  10087. * @param {Boolean} fragmentError
  10088. */
  10089. // FIXME Find a better abstraction where fragment/level retry management is well decoupled
  10090. ;
  10091. _proto.recoverLevel = function recoverLevel(errorEvent, levelIndex, levelError, fragmentError) {
  10092. var _this2 = this;
  10093. var config = this.hls.config;
  10094. var errorDetails = errorEvent.details;
  10095. var level = this._levels[levelIndex];
  10096. var redundantLevels, delay, nextLevel;
  10097. level.loadError++;
  10098. level.fragmentError = fragmentError;
  10099. if (levelError) {
  10100. if (this.levelRetryCount + 1 <= config.levelLoadingMaxRetry) {
  10101. // exponential backoff capped to max retry timeout
  10102. delay = Math.min(Math.pow(2, this.levelRetryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout); // Schedule level reload
  10103. this.timer = setTimeout(function () {
  10104. return _this2.loadLevel();
  10105. }, delay); // boolean used to inform stream controller not to switch back to IDLE on non fatal error
  10106. errorEvent.levelRetry = true;
  10107. this.levelRetryCount++;
  10108. logger["logger"].warn("level controller, " + errorDetails + ", retry in " + delay + " ms, current retry count is " + this.levelRetryCount);
  10109. } else {
  10110. logger["logger"].error("level controller, cannot recover from " + errorDetails + " error");
  10111. this.currentLevelIndex = null; // stopping live reloading timer if any
  10112. this.clearTimer(); // switch error to fatal
  10113. errorEvent.fatal = true;
  10114. return;
  10115. }
  10116. } // Try any redundant streams if available for both errors: level and fragment
  10117. // If level.loadError reaches redundantLevels it means that we tried them all, no hope => let's switch down
  10118. if (levelError || fragmentError) {
  10119. redundantLevels = level.url.length;
  10120. if (redundantLevels > 1 && level.loadError < redundantLevels) {
  10121. level.urlId = (level.urlId + 1) % redundantLevels;
  10122. level.details = undefined;
  10123. logger["logger"].warn("level controller, " + errorDetails + " for level " + levelIndex + ": switching to redundant URL-id " + level.urlId); // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
  10124. // console.log('New video quality level audio group id:', level.attrs.AUDIO);
  10125. } else {
  10126. // Search for available level
  10127. if (this.manualLevelIndex === -1) {
  10128. // When lowest level has been reached, let's start hunt from the top
  10129. nextLevel = levelIndex === 0 ? this._levels.length - 1 : levelIndex - 1;
  10130. logger["logger"].warn("level controller, " + errorDetails + ": switch to " + nextLevel);
  10131. this.hls.nextAutoLevel = this.currentLevelIndex = nextLevel;
  10132. } else if (fragmentError) {
  10133. // Allow fragment retry as long as configuration allows.
  10134. // reset this._level so that another call to set level() will trigger again a frag load
  10135. logger["logger"].warn("level controller, " + errorDetails + ": reload a fragment");
  10136. this.currentLevelIndex = null;
  10137. }
  10138. }
  10139. }
  10140. } // reset errors on the successful load of a fragment
  10141. ;
  10142. _proto.onFragLoaded = function onFragLoaded(_ref3) {
  10143. var frag = _ref3.frag;
  10144. if (frag !== undefined && frag.type === 'main') {
  10145. var level = this._levels[frag.level];
  10146. if (level !== undefined) {
  10147. level.fragmentError = false;
  10148. level.loadError = 0;
  10149. this.levelRetryCount = 0;
  10150. }
  10151. }
  10152. };
  10153. _proto.onLevelLoaded = function onLevelLoaded(data) {
  10154. var _this3 = this;
  10155. var level = data.level,
  10156. details = data.details; // only process level loaded events matching with expected level
  10157. if (level !== this.currentLevelIndex) {
  10158. return;
  10159. }
  10160. var curLevel = this._levels[level]; // reset level load error counter on successful level loaded only if there is no issues with fragments
  10161. if (!curLevel.fragmentError) {
  10162. curLevel.loadError = 0;
  10163. this.levelRetryCount = 0;
  10164. } // if current playlist is a live playlist, arm a timer to reload it
  10165. if (details.live) {
  10166. var reloadInterval = computeReloadInterval(curLevel.details, details, data.stats.trequest);
  10167. logger["logger"].log("live playlist, reload in " + Math.round(reloadInterval) + " ms");
  10168. this.timer = setTimeout(function () {
  10169. return _this3.loadLevel();
  10170. }, reloadInterval);
  10171. } else {
  10172. this.clearTimer();
  10173. }
  10174. };
  10175. _proto.onAudioTrackSwitched = function onAudioTrackSwitched(data) {
  10176. var audioGroupId = this.hls.audioTracks[data.id].groupId;
  10177. var currentLevel = this.hls.levels[this.currentLevelIndex];
  10178. if (!currentLevel) {
  10179. return;
  10180. }
  10181. if (currentLevel.audioGroupIds) {
  10182. var urlId = -1;
  10183. for (var i = 0; i < currentLevel.audioGroupIds.length; i++) {
  10184. if (currentLevel.audioGroupIds[i] === audioGroupId) {
  10185. urlId = i;
  10186. break;
  10187. }
  10188. }
  10189. if (urlId !== currentLevel.urlId) {
  10190. currentLevel.urlId = urlId;
  10191. this.startLoad();
  10192. }
  10193. }
  10194. };
  10195. _proto.loadLevel = function loadLevel() {
  10196. logger["logger"].debug('call to loadLevel');
  10197. if (this.currentLevelIndex !== null && this.canload) {
  10198. var levelObject = this._levels[this.currentLevelIndex];
  10199. if (typeof levelObject === 'object' && levelObject.url.length > 0) {
  10200. var level = this.currentLevelIndex;
  10201. var id = levelObject.urlId;
  10202. var url = levelObject.url[id];
  10203. logger["logger"].log("Attempt loading level index " + level + " with URL-id " + id); // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
  10204. // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);
  10205. this.hls.trigger(events["default"].LEVEL_LOADING, {
  10206. url: url,
  10207. level: level,
  10208. id: id
  10209. });
  10210. }
  10211. }
  10212. };
  10213. _proto.removeLevel = function removeLevel(levelIndex, urlId) {
  10214. var levels = this.levels.filter(function (level, index) {
  10215. if (index !== levelIndex) {
  10216. return true;
  10217. }
  10218. if (level.url.length > 1 && urlId !== undefined) {
  10219. level.url = level.url.filter(function (url, id) {
  10220. return id !== urlId;
  10221. });
  10222. level.urlId = 0;
  10223. return true;
  10224. }
  10225. return false;
  10226. }).map(function (level, index) {
  10227. var details = level.details;
  10228. if (details && details.fragments) {
  10229. details.fragments.forEach(function (fragment) {
  10230. fragment.level = index;
  10231. });
  10232. }
  10233. return level;
  10234. });
  10235. this._levels = levels;
  10236. this.hls.trigger(events["default"].LEVELS_UPDATED, {
  10237. levels: levels
  10238. });
  10239. };
  10240. level_controller_createClass(LevelController, [{
  10241. key: "levels",
  10242. get: function get() {
  10243. return this._levels;
  10244. }
  10245. }, {
  10246. key: "level",
  10247. get: function get() {
  10248. return this.currentLevelIndex;
  10249. },
  10250. set: function set(newLevel) {
  10251. var levels = this._levels;
  10252. if (levels) {
  10253. newLevel = Math.min(newLevel, levels.length - 1);
  10254. if (this.currentLevelIndex !== newLevel || !levels[newLevel].details) {
  10255. this.setLevelInternal(newLevel);
  10256. }
  10257. }
  10258. }
  10259. }, {
  10260. key: "manualLevel",
  10261. get: function get() {
  10262. return this.manualLevelIndex;
  10263. },
  10264. set: function set(newLevel) {
  10265. this.manualLevelIndex = newLevel;
  10266. if (this._startLevel === undefined) {
  10267. this._startLevel = newLevel;
  10268. }
  10269. if (newLevel !== -1) {
  10270. this.level = newLevel;
  10271. }
  10272. }
  10273. }, {
  10274. key: "firstLevel",
  10275. get: function get() {
  10276. return this._firstLevel;
  10277. },
  10278. set: function set(newLevel) {
  10279. this._firstLevel = newLevel;
  10280. }
  10281. }, {
  10282. key: "startLevel",
  10283. get: function get() {
  10284. // hls.startLevel takes precedence over config.startLevel
  10285. // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)
  10286. if (this._startLevel === undefined) {
  10287. var configStartLevel = this.hls.config.startLevel;
  10288. if (configStartLevel !== undefined) {
  10289. return configStartLevel;
  10290. } else {
  10291. return this._firstLevel;
  10292. }
  10293. } else {
  10294. return this._startLevel;
  10295. }
  10296. },
  10297. set: function set(newLevel) {
  10298. this._startLevel = newLevel;
  10299. }
  10300. }, {
  10301. key: "nextLoadLevel",
  10302. get: function get() {
  10303. if (this.manualLevelIndex !== -1) {
  10304. return this.manualLevelIndex;
  10305. } else {
  10306. return this.hls.nextAutoLevel;
  10307. }
  10308. },
  10309. set: function set(nextLevel) {
  10310. this.level = nextLevel;
  10311. if (this.manualLevelIndex === -1) {
  10312. this.hls.nextAutoLevel = nextLevel;
  10313. }
  10314. }
  10315. }]);
  10316. return LevelController;
  10317. }(event_handler);
  10318. // EXTERNAL MODULE: ./src/demux/id3.js
  10319. var id3 = __webpack_require__("./src/demux/id3.js");
  10320. // CONCATENATED MODULE: ./src/utils/texttrack-utils.ts
  10321. function sendAddTrackEvent(track, videoEl) {
  10322. var event;
  10323. try {
  10324. event = new Event('addtrack');
  10325. } catch (err) {
  10326. // for IE11
  10327. event = document.createEvent('Event');
  10328. event.initEvent('addtrack', false, false);
  10329. }
  10330. event.track = track;
  10331. videoEl.dispatchEvent(event);
  10332. }
  10333. function clearCurrentCues(track) {
  10334. if (track === null || track === void 0 ? void 0 : track.cues) {
  10335. while (track.cues.length > 0) {
  10336. track.removeCue(track.cues[0]);
  10337. }
  10338. }
  10339. }
  10340. /**
  10341. * Given a list of Cues, finds the closest cue matching the given time.
  10342. * Modified verison of binary search O(log(n)).
  10343. *
  10344. * @export
  10345. * @param {(TextTrackCueList | TextTrackCue[])} cues - List of cues.
  10346. * @param {number} time - Target time, to find closest cue to.
  10347. * @returns {TextTrackCue}
  10348. */
  10349. function getClosestCue(cues, time) {
  10350. // If the offset is less than the first element, the first element is the closest.
  10351. if (time < cues[0].endTime) {
  10352. return cues[0];
  10353. } // If the offset is greater than the last cue, the last is the closest.
  10354. if (time > cues[cues.length - 1].endTime) {
  10355. return cues[cues.length - 1];
  10356. }
  10357. var left = 0;
  10358. var right = cues.length - 1;
  10359. while (left <= right) {
  10360. var mid = Math.floor((right + left) / 2);
  10361. if (time < cues[mid].endTime) {
  10362. right = mid - 1;
  10363. } else if (time > cues[mid].endTime) {
  10364. left = mid + 1;
  10365. } else {
  10366. // If it's not lower or higher, it must be equal.
  10367. return cues[mid];
  10368. }
  10369. } // At this point, left and right have swapped.
  10370. // No direct match was found, left or right element must be the closest. Check which one has the smallest diff.
  10371. return cues[left].endTime - time < time - cues[right].endTime ? cues[left] : cues[right];
  10372. }
  10373. // CONCATENATED MODULE: ./src/controller/id3-track-controller.js
  10374. function id3_track_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  10375. /*
  10376. * id3 metadata track controller
  10377. */
  10378. var MIN_CUE_DURATION = 0.25;
  10379. var id3_track_controller_ID3TrackController = /*#__PURE__*/function (_EventHandler) {
  10380. id3_track_controller_inheritsLoose(ID3TrackController, _EventHandler);
  10381. function ID3TrackController(hls) {
  10382. var _this;
  10383. _this = _EventHandler.call(this, hls, events["default"].MEDIA_ATTACHED, events["default"].MEDIA_DETACHING, events["default"].FRAG_PARSING_METADATA, events["default"].LIVE_BACK_BUFFER_REACHED) || this;
  10384. _this.id3Track = undefined;
  10385. _this.media = undefined;
  10386. return _this;
  10387. }
  10388. var _proto = ID3TrackController.prototype;
  10389. _proto.destroy = function destroy() {
  10390. event_handler.prototype.destroy.call(this);
  10391. } // Add ID3 metatadata text track.
  10392. ;
  10393. _proto.onMediaAttached = function onMediaAttached(data) {
  10394. this.media = data.media;
  10395. if (!this.media) {}
  10396. };
  10397. _proto.onMediaDetaching = function onMediaDetaching() {
  10398. clearCurrentCues(this.id3Track);
  10399. this.id3Track = undefined;
  10400. this.media = undefined;
  10401. };
  10402. _proto.getID3Track = function getID3Track(textTracks) {
  10403. for (var i = 0; i < textTracks.length; i++) {
  10404. var textTrack = textTracks[i];
  10405. if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {
  10406. // send 'addtrack' when reusing the textTrack for metadata,
  10407. // same as what we do for captions
  10408. sendAddTrackEvent(textTrack, this.media);
  10409. return textTrack;
  10410. }
  10411. }
  10412. return this.media.addTextTrack('metadata', 'id3');
  10413. };
  10414. _proto.onFragParsingMetadata = function onFragParsingMetadata(data) {
  10415. var fragment = data.frag;
  10416. var samples = data.samples; // create track dynamically
  10417. if (!this.id3Track) {
  10418. this.id3Track = this.getID3Track(this.media.textTracks);
  10419. this.id3Track.mode = 'hidden';
  10420. } // Attempt to recreate Safari functionality by creating
  10421. // WebKitDataCue objects when available and store the decoded
  10422. // ID3 data in the value property of the cue
  10423. var Cue = window.WebKitDataCue || window.VTTCue || window.TextTrackCue;
  10424. for (var i = 0; i < samples.length; i++) {
  10425. var frames = id3["default"].getID3Frames(samples[i].data);
  10426. if (frames) {
  10427. // Ensure the pts is positive - sometimes it's reported as a small negative number
  10428. var startTime = Math.max(samples[i].pts, 0);
  10429. var endTime = i < samples.length - 1 ? samples[i + 1].pts : fragment.endPTS;
  10430. if (!endTime) {
  10431. endTime = fragment.start + fragment.duration;
  10432. }
  10433. var timeDiff = endTime - startTime;
  10434. if (timeDiff <= 0) {
  10435. endTime = startTime + MIN_CUE_DURATION;
  10436. }
  10437. for (var j = 0; j < frames.length; j++) {
  10438. var frame = frames[j]; // Safari doesn't put the timestamp frame in the TextTrack
  10439. if (!id3["default"].isTimeStampFrame(frame)) {
  10440. var cue = new Cue(startTime, endTime, '');
  10441. cue.value = frame;
  10442. this.id3Track.addCue(cue);
  10443. }
  10444. }
  10445. }
  10446. }
  10447. };
  10448. _proto.onLiveBackBufferReached = function onLiveBackBufferReached(_ref) {
  10449. var bufferEnd = _ref.bufferEnd;
  10450. var id3Track = this.id3Track;
  10451. if (!id3Track || !id3Track.cues || !id3Track.cues.length) {
  10452. return;
  10453. }
  10454. var foundCue = getClosestCue(id3Track.cues, bufferEnd);
  10455. if (!foundCue) {
  10456. return;
  10457. }
  10458. while (id3Track.cues[0] !== foundCue) {
  10459. id3Track.removeCue(id3Track.cues[0]);
  10460. }
  10461. };
  10462. return ID3TrackController;
  10463. }(event_handler);
  10464. /* harmony default export */ var id3_track_controller = (id3_track_controller_ID3TrackController);
  10465. // CONCATENATED MODULE: ./src/is-supported.ts
  10466. function is_supported_isSupported() {
  10467. var mediaSource = getMediaSource();
  10468. if (!mediaSource) {
  10469. return false;
  10470. }
  10471. var sourceBuffer = self.SourceBuffer || self.WebKitSourceBuffer;
  10472. var isTypeSupported = mediaSource && typeof mediaSource.isTypeSupported === 'function' && mediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'); // if SourceBuffer is exposed ensure its API is valid
  10473. // safari and old version of Chrome doe not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible
  10474. var sourceBufferValidAPI = !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function';
  10475. return !!isTypeSupported && !!sourceBufferValidAPI;
  10476. }
  10477. // CONCATENATED MODULE: ./src/utils/ewma.ts
  10478. /*
  10479. * compute an Exponential Weighted moving average
  10480. * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  10481. * - heavily inspired from shaka-player
  10482. */
  10483. var EWMA = /*#__PURE__*/function () {
  10484. // About half of the estimated value will be from the last |halfLife| samples by weight.
  10485. function EWMA(halfLife) {
  10486. this.alpha_ = void 0;
  10487. this.estimate_ = void 0;
  10488. this.totalWeight_ = void 0;
  10489. // Larger values of alpha expire historical data more slowly.
  10490. this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
  10491. this.estimate_ = 0;
  10492. this.totalWeight_ = 0;
  10493. }
  10494. var _proto = EWMA.prototype;
  10495. _proto.sample = function sample(weight, value) {
  10496. var adjAlpha = Math.pow(this.alpha_, weight);
  10497. this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
  10498. this.totalWeight_ += weight;
  10499. };
  10500. _proto.getTotalWeight = function getTotalWeight() {
  10501. return this.totalWeight_;
  10502. };
  10503. _proto.getEstimate = function getEstimate() {
  10504. if (this.alpha_) {
  10505. var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
  10506. return this.estimate_ / zeroFactor;
  10507. } else {
  10508. return this.estimate_;
  10509. }
  10510. };
  10511. return EWMA;
  10512. }();
  10513. /* harmony default export */ var ewma = (EWMA);
  10514. // CONCATENATED MODULE: ./src/utils/ewma-bandwidth-estimator.ts
  10515. /*
  10516. * EWMA Bandwidth Estimator
  10517. * - heavily inspired from shaka-player
  10518. * Tracks bandwidth samples and estimates available bandwidth.
  10519. * Based on the minimum of two exponentially-weighted moving averages with
  10520. * different half-lives.
  10521. */
  10522. var ewma_bandwidth_estimator_EwmaBandWidthEstimator = /*#__PURE__*/function () {
  10523. // TODO(typescript-hls)
  10524. function EwmaBandWidthEstimator(hls, slow, fast, defaultEstimate) {
  10525. this.hls = void 0;
  10526. this.defaultEstimate_ = void 0;
  10527. this.minWeight_ = void 0;
  10528. this.minDelayMs_ = void 0;
  10529. this.slow_ = void 0;
  10530. this.fast_ = void 0;
  10531. this.hls = hls;
  10532. this.defaultEstimate_ = defaultEstimate;
  10533. this.minWeight_ = 0.001;
  10534. this.minDelayMs_ = 50;
  10535. this.slow_ = new ewma(slow);
  10536. this.fast_ = new ewma(fast);
  10537. }
  10538. var _proto = EwmaBandWidthEstimator.prototype;
  10539. _proto.sample = function sample(durationMs, numBytes) {
  10540. durationMs = Math.max(durationMs, this.minDelayMs_);
  10541. var numBits = 8 * numBytes,
  10542. // weight is duration in seconds
  10543. durationS = durationMs / 1000,
  10544. // value is bandwidth in bits/s
  10545. bandwidthInBps = numBits / durationS;
  10546. this.fast_.sample(durationS, bandwidthInBps);
  10547. this.slow_.sample(durationS, bandwidthInBps);
  10548. };
  10549. _proto.canEstimate = function canEstimate() {
  10550. var fast = this.fast_;
  10551. return fast && fast.getTotalWeight() >= this.minWeight_;
  10552. };
  10553. _proto.getEstimate = function getEstimate() {
  10554. if (this.canEstimate()) {
  10555. // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));
  10556. // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));
  10557. // Take the minimum of these two estimates. This should have the effect of
  10558. // adapting down quickly, but up more slowly.
  10559. return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
  10560. } else {
  10561. return this.defaultEstimate_;
  10562. }
  10563. };
  10564. _proto.destroy = function destroy() {};
  10565. return EwmaBandWidthEstimator;
  10566. }();
  10567. /* harmony default export */ var ewma_bandwidth_estimator = (ewma_bandwidth_estimator_EwmaBandWidthEstimator);
  10568. // CONCATENATED MODULE: ./src/controller/abr-controller.js
  10569. function abr_controller_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  10570. function abr_controller_createClass(Constructor, protoProps, staticProps) { if (protoProps) abr_controller_defineProperties(Constructor.prototype, protoProps); if (staticProps) abr_controller_defineProperties(Constructor, staticProps); return Constructor; }
  10571. function abr_controller_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  10572. function abr_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  10573. /*
  10574. * simple ABR Controller
  10575. * - compute next level based on last fragment bw heuristics
  10576. * - implement an abandon rules triggered if we have less than 2 frag buffered and if computed bw shows that we risk buffer stalling
  10577. */
  10578. var abr_controller_window = window,
  10579. abr_controller_performance = abr_controller_window.performance;
  10580. var abr_controller_AbrController = /*#__PURE__*/function (_EventHandler) {
  10581. abr_controller_inheritsLoose(AbrController, _EventHandler);
  10582. function AbrController(hls) {
  10583. var _this;
  10584. _this = _EventHandler.call(this, hls, events["default"].FRAG_LOADING, events["default"].FRAG_LOADED, events["default"].FRAG_BUFFERED, events["default"].ERROR) || this;
  10585. _this.lastLoadedFragLevel = 0;
  10586. _this._nextAutoLevel = -1;
  10587. _this.hls = hls;
  10588. _this.timer = null;
  10589. _this._bwEstimator = null;
  10590. _this.onCheck = _this._abandonRulesCheck.bind(abr_controller_assertThisInitialized(_this));
  10591. return _this;
  10592. }
  10593. var _proto = AbrController.prototype;
  10594. _proto.destroy = function destroy() {
  10595. this.clearTimer();
  10596. event_handler.prototype.destroy.call(this);
  10597. };
  10598. _proto.onFragLoading = function onFragLoading(data) {
  10599. var frag = data.frag;
  10600. if (frag.type === 'main') {
  10601. if (!this.timer) {
  10602. this.fragCurrent = frag;
  10603. this.timer = setInterval(this.onCheck, 100);
  10604. } // lazy init of BwEstimator, rationale is that we use different params for Live/VoD
  10605. // so we need to wait for stream manifest / playlist type to instantiate it.
  10606. if (!this._bwEstimator) {
  10607. var hls = this.hls;
  10608. var config = hls.config;
  10609. var level = frag.level;
  10610. var isLive = hls.levels[level].details.live;
  10611. var ewmaFast;
  10612. var ewmaSlow;
  10613. if (isLive) {
  10614. ewmaFast = config.abrEwmaFastLive;
  10615. ewmaSlow = config.abrEwmaSlowLive;
  10616. } else {
  10617. ewmaFast = config.abrEwmaFastVoD;
  10618. ewmaSlow = config.abrEwmaSlowVoD;
  10619. }
  10620. this._bwEstimator = new ewma_bandwidth_estimator(hls, ewmaSlow, ewmaFast, config.abrEwmaDefaultEstimate);
  10621. }
  10622. }
  10623. };
  10624. _proto._abandonRulesCheck = function _abandonRulesCheck() {
  10625. /*
  10626. monitor fragment retrieval time...
  10627. we compute expected time of arrival of the complete fragment.
  10628. we compare it to expected time of buffer starvation
  10629. */
  10630. var hls = this.hls;
  10631. var video = hls.media;
  10632. var frag = this.fragCurrent;
  10633. if (!frag) {
  10634. return;
  10635. }
  10636. var loader = frag.loader; // if loader has been destroyed or loading has been aborted, stop timer and return
  10637. if (!loader || loader.stats && loader.stats.aborted) {
  10638. logger["logger"].warn('frag loader destroy or aborted, disarm abandonRules');
  10639. this.clearTimer(); // reset forced auto level value so that next level will be selected
  10640. this._nextAutoLevel = -1;
  10641. return;
  10642. }
  10643. var stats = loader.stats;
  10644. /* only monitor frag retrieval time if
  10645. (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) */
  10646. if (video && stats && (!video.paused && video.playbackRate !== 0 || !video.readyState) && frag.autoLevel && frag.level) {
  10647. var requestDelay = abr_controller_performance.now() - stats.trequest;
  10648. var playbackRate = Math.abs(video.playbackRate); // monitor fragment load progress after half of expected fragment duration,to stabilize bitrate
  10649. if (requestDelay > 500 * frag.duration / playbackRate) {
  10650. var levels = hls.levels;
  10651. var loadRate = Math.max(1, stats.bw ? stats.bw / 8 : stats.loaded * 1000 / requestDelay); // byte/s; at least 1 byte/s to avoid division by zero
  10652. // compute expected fragment length using frag duration and level bitrate. also ensure that expected len is gte than already loaded size
  10653. var level = levels[frag.level];
  10654. if (!level) {
  10655. return;
  10656. }
  10657. var levelBitrate = level.realBitrate ? Math.max(level.realBitrate, level.bitrate) : level.bitrate;
  10658. var expectedLen = stats.total ? stats.total : Math.max(stats.loaded, Math.round(frag.duration * levelBitrate / 8));
  10659. var pos = video.currentTime;
  10660. var fragLoadedDelay = (expectedLen - stats.loaded) / loadRate;
  10661. var bufferStarvationDelay = (BufferHelper.bufferInfo(video, pos, hls.config.maxBufferHole).end - pos) / playbackRate; // consider emergency switch down only if we have less than 2 frag buffered AND
  10662. // time to finish loading current fragment is bigger than buffer starvation delay
  10663. // ie if we risk buffer starvation if bw does not increase quickly
  10664. if (bufferStarvationDelay < 2 * frag.duration / playbackRate && fragLoadedDelay > bufferStarvationDelay) {
  10665. var minAutoLevel = hls.minAutoLevel;
  10666. var fragLevelNextLoadedDelay;
  10667. var nextLoadLevel; // lets iterate through lower level and try to find the biggest one that could avoid rebuffering
  10668. // we start from current level - 1 and we step down , until we find a matching level
  10669. for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
  10670. // compute time to load next fragment at lower level
  10671. // 0.8 : consider only 80% of current bw to be conservative
  10672. // 8 = bits per byte (bps/Bps)
  10673. var levelNextBitrate = levels[nextLoadLevel].realBitrate ? Math.max(levels[nextLoadLevel].realBitrate, levels[nextLoadLevel].bitrate) : levels[nextLoadLevel].bitrate;
  10674. var _fragLevelNextLoadedDelay = frag.duration * levelNextBitrate / (8 * 0.8 * loadRate);
  10675. if (_fragLevelNextLoadedDelay < bufferStarvationDelay) {
  10676. // we found a lower level that be rebuffering free with current estimated bw !
  10677. break;
  10678. }
  10679. } // only emergency switch down if it takes less time to load new fragment at lowest level instead
  10680. // of finishing loading current one ...
  10681. if (fragLevelNextLoadedDelay < fragLoadedDelay) {
  10682. logger["logger"].warn("loading too slow, abort fragment loading and switch to level " + nextLoadLevel + ":fragLoadedDelay[" + nextLoadLevel + "]<fragLoadedDelay[" + (frag.level - 1) + "];bufferStarvationDelay:" + fragLevelNextLoadedDelay.toFixed(1) + "<" + fragLoadedDelay.toFixed(1) + ":" + bufferStarvationDelay.toFixed(1)); // force next load level in auto mode
  10683. hls.nextLoadLevel = nextLoadLevel; // update bw estimate for this fragment before cancelling load (this will help reducing the bw)
  10684. this._bwEstimator.sample(requestDelay, stats.loaded); // abort fragment loading
  10685. loader.abort(); // stop abandon rules timer
  10686. this.clearTimer();
  10687. hls.trigger(events["default"].FRAG_LOAD_EMERGENCY_ABORTED, {
  10688. frag: frag,
  10689. stats: stats
  10690. });
  10691. }
  10692. }
  10693. }
  10694. }
  10695. };
  10696. _proto.onFragLoaded = function onFragLoaded(data) {
  10697. var frag = data.frag;
  10698. if (frag.type === 'main' && Object(number["isFiniteNumber"])(frag.sn)) {
  10699. // stop monitoring bw once frag loaded
  10700. this.clearTimer(); // store level id after successful fragment load
  10701. this.lastLoadedFragLevel = frag.level; // reset forced auto level value so that next level will be selected
  10702. this._nextAutoLevel = -1; // compute level average bitrate
  10703. if (this.hls.config.abrMaxWithRealBitrate) {
  10704. var level = this.hls.levels[frag.level];
  10705. var loadedBytes = (level.loaded ? level.loaded.bytes : 0) + data.stats.loaded;
  10706. var loadedDuration = (level.loaded ? level.loaded.duration : 0) + data.frag.duration;
  10707. level.loaded = {
  10708. bytes: loadedBytes,
  10709. duration: loadedDuration
  10710. };
  10711. level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
  10712. } // if fragment has been loaded to perform a bitrate test,
  10713. if (data.frag.bitrateTest) {
  10714. var stats = data.stats;
  10715. stats.tparsed = stats.tbuffered = stats.tload;
  10716. this.onFragBuffered(data);
  10717. }
  10718. }
  10719. };
  10720. _proto.onFragBuffered = function onFragBuffered(data) {
  10721. var stats = data.stats;
  10722. var frag = data.frag; // only update stats on first frag buffering
  10723. // if same frag is loaded multiple times, it might be in browser cache, and loaded quickly
  10724. // and leading to wrong bw estimation
  10725. // on bitrate test, also only update stats once (if tload = tbuffered == on FRAG_LOADED)
  10726. if (stats.aborted !== true && frag.type === 'main' && Object(number["isFiniteNumber"])(frag.sn) && (!frag.bitrateTest || stats.tload === stats.tbuffered)) {
  10727. // use tparsed-trequest instead of tbuffered-trequest to compute fragLoadingProcessing; rationale is that buffer appending only happens once media is attached
  10728. // 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
  10729. // as a consequence it could happen really late in the process. meaning that appending duration might appears huge ... leading to underestimated throughput estimation
  10730. var fragLoadingProcessingMs = stats.tparsed - stats.trequest;
  10731. logger["logger"].log("latency/loading/parsing/append/kbps:" + Math.round(stats.tfirst - stats.trequest) + "/" + Math.round(stats.tload - stats.tfirst) + "/" + Math.round(stats.tparsed - stats.tload) + "/" + Math.round(stats.tbuffered - stats.tparsed) + "/" + Math.round(8 * stats.loaded / (stats.tbuffered - stats.trequest)));
  10732. this._bwEstimator.sample(fragLoadingProcessingMs, stats.loaded);
  10733. stats.bwEstimate = this._bwEstimator.getEstimate(); // if fragment has been loaded to perform a bitrate test, (hls.startLevel = -1), store bitrate test delay duration
  10734. if (frag.bitrateTest) {
  10735. this.bitrateTestDelay = fragLoadingProcessingMs / 1000;
  10736. } else {
  10737. this.bitrateTestDelay = 0;
  10738. }
  10739. }
  10740. };
  10741. _proto.onError = function onError(data) {
  10742. // stop timer in case of frag loading error
  10743. switch (data.details) {
  10744. case errors["ErrorDetails"].FRAG_LOAD_ERROR:
  10745. case errors["ErrorDetails"].FRAG_LOAD_TIMEOUT:
  10746. this.clearTimer();
  10747. break;
  10748. default:
  10749. break;
  10750. }
  10751. };
  10752. _proto.clearTimer = function clearTimer() {
  10753. clearInterval(this.timer);
  10754. this.timer = null;
  10755. } // return next auto level
  10756. ;
  10757. _proto._findBestLevel = function _findBestLevel(currentLevel, currentFragDuration, currentBw, minAutoLevel, maxAutoLevel, maxFetchDuration, bwFactor, bwUpFactor, levels) {
  10758. for (var i = maxAutoLevel; i >= minAutoLevel; i--) {
  10759. var levelInfo = levels[i];
  10760. if (!levelInfo) {
  10761. continue;
  10762. }
  10763. var levelDetails = levelInfo.details;
  10764. var avgDuration = levelDetails ? levelDetails.totalduration / levelDetails.fragments.length : currentFragDuration;
  10765. var live = levelDetails ? levelDetails.live : false;
  10766. var adjustedbw = void 0; // follow algorithm captured from stagefright :
  10767. // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
  10768. // Pick the highest bandwidth stream below or equal to estimated bandwidth.
  10769. // consider only 80% of the available bandwidth, but if we are switching up,
  10770. // be even more conservative (70%) to avoid overestimating and immediately
  10771. // switching back.
  10772. if (i <= currentLevel) {
  10773. adjustedbw = bwFactor * currentBw;
  10774. } else {
  10775. adjustedbw = bwUpFactor * currentBw;
  10776. }
  10777. var bitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate;
  10778. var fetchDuration = bitrate * avgDuration / adjustedbw;
  10779. logger["logger"].trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: " + i + "/" + Math.round(adjustedbw) + "/" + bitrate + "/" + avgDuration + "/" + maxFetchDuration + "/" + fetchDuration); // if adjusted bw is greater than level bitrate AND
  10780. if (adjustedbw > bitrate && ( // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
  10781. // 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 ...
  10782. // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that _findBestLevel will return -1
  10783. !fetchDuration || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration)) {
  10784. // as we are looping from highest to lowest, this will return the best achievable quality level
  10785. return i;
  10786. }
  10787. } // not enough time budget even with quality level 0 ... rebuffering might happen
  10788. return -1;
  10789. };
  10790. abr_controller_createClass(AbrController, [{
  10791. key: "nextAutoLevel",
  10792. get: function get() {
  10793. var forcedAutoLevel = this._nextAutoLevel;
  10794. var bwEstimator = this._bwEstimator; // in case next auto level has been forced, and bw not available or not reliable, return forced value
  10795. if (forcedAutoLevel !== -1 && (!bwEstimator || !bwEstimator.canEstimate())) {
  10796. return forcedAutoLevel;
  10797. } // compute next level using ABR logic
  10798. var nextABRAutoLevel = this._nextABRAutoLevel; // if forced auto level has been defined, use it to cap ABR computed quality level
  10799. if (forcedAutoLevel !== -1) {
  10800. nextABRAutoLevel = Math.min(forcedAutoLevel, nextABRAutoLevel);
  10801. }
  10802. return nextABRAutoLevel;
  10803. },
  10804. set: function set(nextLevel) {
  10805. this._nextAutoLevel = nextLevel;
  10806. }
  10807. }, {
  10808. key: "_nextABRAutoLevel",
  10809. get: function get() {
  10810. var hls = this.hls;
  10811. var maxAutoLevel = hls.maxAutoLevel,
  10812. levels = hls.levels,
  10813. config = hls.config,
  10814. minAutoLevel = hls.minAutoLevel;
  10815. var video = hls.media;
  10816. var currentLevel = this.lastLoadedFragLevel;
  10817. var currentFragDuration = this.fragCurrent ? this.fragCurrent.duration : 0;
  10818. var pos = video ? video.currentTime : 0; // playbackRate is the absolute value of the playback rate; if video.playbackRate is 0, we use 1 to load as
  10819. // if we're playing back at the normal rate.
  10820. var playbackRate = video && video.playbackRate !== 0 ? Math.abs(video.playbackRate) : 1.0;
  10821. var avgbw = this._bwEstimator ? this._bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate; // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.
  10822. var bufferStarvationDelay = (BufferHelper.bufferInfo(video, pos, config.maxBufferHole).end - pos) / playbackRate; // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all
  10823. var bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, config.abrBandWidthFactor, config.abrBandWidthUpFactor, levels);
  10824. if (bestLevel >= 0) {
  10825. return bestLevel;
  10826. } else {
  10827. logger["logger"].trace('rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering'); // not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering
  10828. // if no matching level found, logic will return 0
  10829. var maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay;
  10830. var bwFactor = config.abrBandWidthFactor;
  10831. var bwUpFactor = config.abrBandWidthUpFactor;
  10832. if (bufferStarvationDelay === 0) {
  10833. // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test
  10834. var bitrateTestDelay = this.bitrateTestDelay;
  10835. if (bitrateTestDelay) {
  10836. // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value
  10837. // max video loading delay used in automatic start level selection :
  10838. // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +
  10839. // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )
  10840. // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration
  10841. var maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
  10842. maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
  10843. logger["logger"].trace("bitrate test took " + Math.round(1000 * bitrateTestDelay) + "ms, set first fragment max fetchDuration to " + Math.round(1000 * maxStarvationDelay) + " ms"); // don't use conservative factor on bitrate test
  10844. bwFactor = bwUpFactor = 1;
  10845. }
  10846. }
  10847. bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay + maxStarvationDelay, bwFactor, bwUpFactor, levels);
  10848. return Math.max(bestLevel, 0);
  10849. }
  10850. }
  10851. }]);
  10852. return AbrController;
  10853. }(event_handler);
  10854. /* harmony default export */ var abr_controller = (abr_controller_AbrController);
  10855. // CONCATENATED MODULE: ./src/controller/buffer-controller.ts
  10856. function buffer_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  10857. /*
  10858. * Buffer Controller
  10859. */
  10860. var buffer_controller_MediaSource = getMediaSource();
  10861. var buffer_controller_BufferController = /*#__PURE__*/function (_EventHandler) {
  10862. buffer_controller_inheritsLoose(BufferController, _EventHandler);
  10863. // the value that we have set mediasource.duration to
  10864. // (the actual duration may be tweaked slighly by the browser)
  10865. // the value that we want to set mediaSource.duration to
  10866. // the target duration of the current media playlist
  10867. // current stream state: true - for live broadcast, false - for VoD content
  10868. // cache the self generated object url to detect hijack of video tag
  10869. // signals that the sourceBuffers need to be flushed
  10870. // signals that mediaSource should have endOfStream called
  10871. // this is optional because this property is removed from the class sometimes
  10872. // The number of BUFFER_CODEC events received before any sourceBuffers are created
  10873. // The total number of BUFFER_CODEC events received
  10874. // A reference to the attached media element
  10875. // A reference to the active media source
  10876. // List of pending segments to be appended to source buffer
  10877. // A guard to see if we are currently appending to the source buffer
  10878. // counters
  10879. function BufferController(hls) {
  10880. var _this;
  10881. _this = _EventHandler.call(this, hls, events["default"].MEDIA_ATTACHING, events["default"].MEDIA_DETACHING, events["default"].MANIFEST_PARSED, events["default"].BUFFER_RESET, events["default"].BUFFER_APPENDING, events["default"].BUFFER_CODECS, events["default"].BUFFER_EOS, events["default"].BUFFER_FLUSHING, events["default"].LEVEL_PTS_UPDATED, events["default"].LEVEL_UPDATED) || this;
  10882. _this._msDuration = null;
  10883. _this._levelDuration = null;
  10884. _this._levelTargetDuration = 10;
  10885. _this._live = null;
  10886. _this._objectUrl = null;
  10887. _this._needsFlush = false;
  10888. _this._needsEos = false;
  10889. _this.config = void 0;
  10890. _this.audioTimestampOffset = void 0;
  10891. _this.bufferCodecEventsExpected = 0;
  10892. _this._bufferCodecEventsTotal = 0;
  10893. _this.media = null;
  10894. _this.mediaSource = null;
  10895. _this.segments = [];
  10896. _this.parent = void 0;
  10897. _this.appending = false;
  10898. _this.appended = 0;
  10899. _this.appendError = 0;
  10900. _this.flushBufferCounter = 0;
  10901. _this.tracks = {};
  10902. _this.pendingTracks = {};
  10903. _this.sourceBuffer = {};
  10904. _this.flushRange = [];
  10905. _this._onMediaSourceOpen = function () {
  10906. logger["logger"].log('media source opened');
  10907. _this.hls.trigger(events["default"].MEDIA_ATTACHED, {
  10908. media: _this.media
  10909. });
  10910. var mediaSource = _this.mediaSource;
  10911. if (mediaSource) {
  10912. // once received, don't listen anymore to sourceopen event
  10913. mediaSource.removeEventListener('sourceopen', _this._onMediaSourceOpen);
  10914. }
  10915. _this.checkPendingTracks();
  10916. };
  10917. _this._onMediaSourceClose = function () {
  10918. logger["logger"].log('media source closed');
  10919. };
  10920. _this._onMediaSourceEnded = function () {
  10921. logger["logger"].log('media source ended');
  10922. };
  10923. _this._onSBUpdateEnd = function () {
  10924. // update timestampOffset
  10925. if (_this.audioTimestampOffset && _this.sourceBuffer.audio) {
  10926. var audioBuffer = _this.sourceBuffer.audio;
  10927. logger["logger"].warn("change mpeg audio timestamp offset from " + audioBuffer.timestampOffset + " to " + _this.audioTimestampOffset);
  10928. audioBuffer.timestampOffset = _this.audioTimestampOffset;
  10929. delete _this.audioTimestampOffset;
  10930. }
  10931. if (_this._needsFlush) {
  10932. _this.doFlush();
  10933. }
  10934. if (_this._needsEos) {
  10935. _this.checkEos();
  10936. }
  10937. _this.appending = false;
  10938. var parent = _this.parent; // count nb of pending segments waiting for appending on this sourcebuffer
  10939. var pending = _this.segments.reduce(function (counter, segment) {
  10940. return segment.parent === parent ? counter + 1 : counter;
  10941. }, 0); // this.sourceBuffer is better to use than media.buffered as it is closer to the PTS data from the fragments
  10942. var timeRanges = {};
  10943. var sbSet = _this.sourceBuffer;
  10944. for (var streamType in sbSet) {
  10945. var sb = sbSet[streamType];
  10946. if (!sb) {
  10947. throw Error("handling source buffer update end error: source buffer for " + streamType + " uninitilized and unable to update buffered TimeRanges.");
  10948. }
  10949. timeRanges[streamType] = sb.buffered;
  10950. }
  10951. _this.hls.trigger(events["default"].BUFFER_APPENDED, {
  10952. parent: parent,
  10953. pending: pending,
  10954. timeRanges: timeRanges
  10955. }); // don't append in flushing mode
  10956. if (!_this._needsFlush) {
  10957. _this.doAppending();
  10958. }
  10959. _this.updateMediaElementDuration(); // appending goes first
  10960. if (pending === 0) {
  10961. _this.flushLiveBackBuffer();
  10962. }
  10963. };
  10964. _this._onSBUpdateError = function (event) {
  10965. logger["logger"].error('sourceBuffer error:', event); // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
  10966. // this error might not always be fatal (it is fatal if decode error is set, in that case
  10967. // it will be followed by a mediaElement error ...)
  10968. _this.hls.trigger(events["default"].ERROR, {
  10969. type: errors["ErrorTypes"].MEDIA_ERROR,
  10970. details: errors["ErrorDetails"].BUFFER_APPENDING_ERROR,
  10971. fatal: false
  10972. }); // we don't need to do more than that, as accordin to the spec, updateend will be fired just after
  10973. };
  10974. _this.config = hls.config;
  10975. return _this;
  10976. }
  10977. var _proto = BufferController.prototype;
  10978. _proto.destroy = function destroy() {
  10979. event_handler.prototype.destroy.call(this);
  10980. };
  10981. _proto.onLevelPtsUpdated = function onLevelPtsUpdated(data) {
  10982. var type = data.type;
  10983. var audioTrack = this.tracks.audio; // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)
  10984. // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`
  10985. // 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
  10986. // `SourceBuffer.abort()` and adjusting `SourceBuffer.timestampOffset` if `SourceBuffer.updating` is false or awaiting `updateend`
  10987. // event if SB is in updating state.
  10988. // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486
  10989. if (type === 'audio' && audioTrack && audioTrack.container === 'audio/mpeg') {
  10990. // Chrome audio mp3 track
  10991. var audioBuffer = this.sourceBuffer.audio;
  10992. if (!audioBuffer) {
  10993. throw Error('Level PTS Updated and source buffer for audio uninitalized');
  10994. }
  10995. var delta = Math.abs(audioBuffer.timestampOffset - data.start); // adjust timestamp offset if time delta is greater than 100ms
  10996. if (delta > 0.1) {
  10997. var updating = audioBuffer.updating;
  10998. try {
  10999. audioBuffer.abort();
  11000. } catch (err) {
  11001. logger["logger"].warn('can not abort audio buffer: ' + err);
  11002. }
  11003. if (!updating) {
  11004. logger["logger"].warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + data.start);
  11005. audioBuffer.timestampOffset = data.start;
  11006. } else {
  11007. this.audioTimestampOffset = data.start;
  11008. }
  11009. }
  11010. }
  11011. };
  11012. _proto.onManifestParsed = function onManifestParsed(data) {
  11013. // in case of alt audio (where all tracks have urls) 2 BUFFER_CODECS events will be triggered, one per stream controller
  11014. // sourcebuffers will be created all at once when the expected nb of tracks will be reached
  11015. // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller
  11016. // it will contain the expected nb of source buffers, no need to compute it
  11017. var codecEvents = 2;
  11018. if (data.audio && !data.video || !data.altAudio) {
  11019. codecEvents = 1;
  11020. }
  11021. this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = codecEvents;
  11022. logger["logger"].log(this.bufferCodecEventsExpected + " bufferCodec event(s) expected");
  11023. };
  11024. _proto.onMediaAttaching = function onMediaAttaching(data) {
  11025. var media = this.media = data.media;
  11026. if (media && buffer_controller_MediaSource) {
  11027. // setup the media source
  11028. var ms = this.mediaSource = new buffer_controller_MediaSource(); // Media Source listeners
  11029. ms.addEventListener('sourceopen', this._onMediaSourceOpen);
  11030. ms.addEventListener('sourceended', this._onMediaSourceEnded);
  11031. ms.addEventListener('sourceclose', this._onMediaSourceClose); // link video and media Source
  11032. media.src = window.URL.createObjectURL(ms); // cache the locally generated object url
  11033. this._objectUrl = media.src;
  11034. }
  11035. };
  11036. _proto.onMediaDetaching = function onMediaDetaching() {
  11037. logger["logger"].log('media source detaching');
  11038. var ms = this.mediaSource;
  11039. if (ms) {
  11040. if (ms.readyState === 'open') {
  11041. try {
  11042. // endOfStream could trigger exception if any sourcebuffer is in updating state
  11043. // we don't really care about checking sourcebuffer state here,
  11044. // as we are anyway detaching the MediaSource
  11045. // let's just avoid this exception to propagate
  11046. ms.endOfStream();
  11047. } catch (err) {
  11048. logger["logger"].warn("onMediaDetaching:" + err.message + " while calling endOfStream");
  11049. }
  11050. }
  11051. ms.removeEventListener('sourceopen', this._onMediaSourceOpen);
  11052. ms.removeEventListener('sourceended', this._onMediaSourceEnded);
  11053. ms.removeEventListener('sourceclose', this._onMediaSourceClose); // Detach properly the MediaSource from the HTMLMediaElement as
  11054. // suggested in https://github.com/w3c/media-source/issues/53.
  11055. if (this.media) {
  11056. if (this._objectUrl) {
  11057. window.URL.revokeObjectURL(this._objectUrl);
  11058. } // clean up video tag src only if it's our own url. some external libraries might
  11059. // hijack the video tag and change its 'src' without destroying the Hls instance first
  11060. if (this.media.src === this._objectUrl) {
  11061. this.media.removeAttribute('src');
  11062. this.media.load();
  11063. } else {
  11064. logger["logger"].warn('media.src was changed by a third party - skip cleanup');
  11065. }
  11066. }
  11067. this.mediaSource = null;
  11068. this.media = null;
  11069. this._objectUrl = null;
  11070. this.bufferCodecEventsExpected = this._bufferCodecEventsTotal;
  11071. this.pendingTracks = {};
  11072. this.tracks = {};
  11073. this.sourceBuffer = {};
  11074. this.flushRange = [];
  11075. this.segments = [];
  11076. this.appended = 0;
  11077. }
  11078. this.hls.trigger(events["default"].MEDIA_DETACHED);
  11079. };
  11080. _proto.checkPendingTracks = function checkPendingTracks() {
  11081. var bufferCodecEventsExpected = this.bufferCodecEventsExpected,
  11082. pendingTracks = this.pendingTracks; // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.
  11083. // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after
  11084. // data has been appended to existing ones.
  11085. // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.
  11086. var pendingTracksCount = Object.keys(pendingTracks).length;
  11087. if (pendingTracksCount && !bufferCodecEventsExpected || pendingTracksCount === 2) {
  11088. // ok, let's create them now !
  11089. this.createSourceBuffers(pendingTracks);
  11090. this.pendingTracks = {}; // append any pending segments now !
  11091. this.doAppending();
  11092. }
  11093. };
  11094. _proto.onBufferReset = function onBufferReset() {
  11095. var sourceBuffer = this.sourceBuffer;
  11096. for (var type in sourceBuffer) {
  11097. var sb = sourceBuffer[type];
  11098. try {
  11099. if (sb) {
  11100. if (this.mediaSource) {
  11101. this.mediaSource.removeSourceBuffer(sb);
  11102. }
  11103. sb.removeEventListener('updateend', this._onSBUpdateEnd);
  11104. sb.removeEventListener('error', this._onSBUpdateError);
  11105. }
  11106. } catch (err) {}
  11107. }
  11108. this.sourceBuffer = {};
  11109. this.flushRange = [];
  11110. this.segments = [];
  11111. this.appended = 0;
  11112. };
  11113. _proto.onBufferCodecs = function onBufferCodecs(tracks) {
  11114. var _this2 = this;
  11115. // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks
  11116. // if sourcebuffers already created, do nothing ...
  11117. if (Object.keys(this.sourceBuffer).length) {
  11118. return;
  11119. }
  11120. Object.keys(tracks).forEach(function (trackName) {
  11121. _this2.pendingTracks[trackName] = tracks[trackName];
  11122. });
  11123. this.bufferCodecEventsExpected = Math.max(this.bufferCodecEventsExpected - 1, 0);
  11124. if (this.mediaSource && this.mediaSource.readyState === 'open') {
  11125. this.checkPendingTracks();
  11126. }
  11127. };
  11128. _proto.createSourceBuffers = function createSourceBuffers(tracks) {
  11129. var sourceBuffer = this.sourceBuffer,
  11130. mediaSource = this.mediaSource;
  11131. if (!mediaSource) {
  11132. throw Error('createSourceBuffers called when mediaSource was null');
  11133. }
  11134. for (var trackName in tracks) {
  11135. if (!sourceBuffer[trackName]) {
  11136. var track = tracks[trackName];
  11137. if (!track) {
  11138. throw Error("source buffer exists for track " + trackName + ", however track does not");
  11139. } // use levelCodec as first priority
  11140. var codec = track.levelCodec || track.codec;
  11141. var mimeType = track.container + ";codecs=" + codec;
  11142. logger["logger"].log("creating sourceBuffer(" + mimeType + ")");
  11143. try {
  11144. var sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);
  11145. sb.addEventListener('updateend', this._onSBUpdateEnd);
  11146. sb.addEventListener('error', this._onSBUpdateError);
  11147. this.tracks[trackName] = {
  11148. buffer: sb,
  11149. codec: codec,
  11150. id: track.id,
  11151. container: track.container,
  11152. levelCodec: track.levelCodec
  11153. };
  11154. } catch (err) {
  11155. logger["logger"].error("error while trying to add sourceBuffer:" + err.message);
  11156. this.hls.trigger(events["default"].ERROR, {
  11157. type: errors["ErrorTypes"].MEDIA_ERROR,
  11158. details: errors["ErrorDetails"].BUFFER_ADD_CODEC_ERROR,
  11159. fatal: false,
  11160. err: err,
  11161. mimeType: mimeType
  11162. });
  11163. }
  11164. }
  11165. }
  11166. this.hls.trigger(events["default"].BUFFER_CREATED, {
  11167. tracks: this.tracks
  11168. });
  11169. };
  11170. _proto.onBufferAppending = function onBufferAppending(data) {
  11171. if (!this._needsFlush) {
  11172. if (!this.segments) {
  11173. this.segments = [data];
  11174. } else {
  11175. this.segments.push(data);
  11176. }
  11177. this.doAppending();
  11178. }
  11179. } // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()
  11180. // an undefined data.type will mark all buffers as EOS.
  11181. ;
  11182. _proto.onBufferEos = function onBufferEos(data) {
  11183. for (var type in this.sourceBuffer) {
  11184. if (!data.type || data.type === type) {
  11185. var sb = this.sourceBuffer[type];
  11186. if (sb && !sb.ended) {
  11187. sb.ended = true;
  11188. logger["logger"].log(type + " sourceBuffer now EOS");
  11189. }
  11190. }
  11191. }
  11192. this.checkEos();
  11193. } // if all source buffers are marked as ended, signal endOfStream() to MediaSource.
  11194. ;
  11195. _proto.checkEos = function checkEos() {
  11196. var sourceBuffer = this.sourceBuffer,
  11197. mediaSource = this.mediaSource;
  11198. if (!mediaSource || mediaSource.readyState !== 'open') {
  11199. this._needsEos = false;
  11200. return;
  11201. }
  11202. for (var type in sourceBuffer) {
  11203. var sb = sourceBuffer[type];
  11204. if (!sb) continue;
  11205. if (!sb.ended) {
  11206. return;
  11207. }
  11208. if (sb.updating) {
  11209. this._needsEos = true;
  11210. return;
  11211. }
  11212. }
  11213. logger["logger"].log('all media data are available, signal endOfStream() to MediaSource and stop loading fragment'); // Notify the media element that it now has all of the media data
  11214. try {
  11215. mediaSource.endOfStream();
  11216. } catch (e) {
  11217. logger["logger"].warn('exception while calling mediaSource.endOfStream()');
  11218. }
  11219. this._needsEos = false;
  11220. };
  11221. _proto.onBufferFlushing = function onBufferFlushing(data) {
  11222. if (data.type) {
  11223. this.flushRange.push({
  11224. start: data.startOffset,
  11225. end: data.endOffset,
  11226. type: data.type
  11227. });
  11228. } else {
  11229. this.flushRange.push({
  11230. start: data.startOffset,
  11231. end: data.endOffset,
  11232. type: 'video'
  11233. });
  11234. this.flushRange.push({
  11235. start: data.startOffset,
  11236. end: data.endOffset,
  11237. type: 'audio'
  11238. });
  11239. } // attempt flush immediately
  11240. this.flushBufferCounter = 0;
  11241. this.doFlush();
  11242. };
  11243. _proto.flushLiveBackBuffer = function flushLiveBackBuffer() {
  11244. // clear back buffer for live only
  11245. if (!this._live) {
  11246. return;
  11247. }
  11248. var liveBackBufferLength = this.config.liveBackBufferLength;
  11249. if (!isFinite(liveBackBufferLength) || liveBackBufferLength < 0) {
  11250. return;
  11251. }
  11252. if (!this.media) {
  11253. logger["logger"].error('flushLiveBackBuffer called without attaching media');
  11254. return;
  11255. }
  11256. var currentTime = this.media.currentTime;
  11257. var sourceBuffer = this.sourceBuffer;
  11258. var bufferTypes = Object.keys(sourceBuffer);
  11259. var targetBackBufferPosition = currentTime - Math.max(liveBackBufferLength, this._levelTargetDuration);
  11260. for (var index = bufferTypes.length - 1; index >= 0; index--) {
  11261. var bufferType = bufferTypes[index];
  11262. var sb = sourceBuffer[bufferType];
  11263. if (sb) {
  11264. var buffered = sb.buffered; // when target buffer start exceeds actual buffer start
  11265. if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
  11266. // remove buffer up until current time minus minimum back buffer length (removing buffer too close to current
  11267. // time will lead to playback freezing)
  11268. // credits for level target duration - https://github.com/videojs/http-streaming/blob/3132933b6aa99ddefab29c10447624efd6fd6e52/src/segment-loader.js#L91
  11269. if (this.removeBufferRange(bufferType, sb, 0, targetBackBufferPosition)) {
  11270. this.hls.trigger(events["default"].LIVE_BACK_BUFFER_REACHED, {
  11271. bufferEnd: targetBackBufferPosition
  11272. });
  11273. }
  11274. }
  11275. }
  11276. }
  11277. };
  11278. _proto.onLevelUpdated = function onLevelUpdated(_ref) {
  11279. var details = _ref.details;
  11280. if (details.fragments.length > 0) {
  11281. this._levelDuration = details.totalduration + details.fragments[0].start;
  11282. this._levelTargetDuration = details.averagetargetduration || details.targetduration || 10;
  11283. this._live = details.live;
  11284. this.updateMediaElementDuration();
  11285. }
  11286. }
  11287. /**
  11288. * Update Media Source duration to current level duration or override to Infinity if configuration parameter
  11289. * 'liveDurationInfinity` is set to `true`
  11290. * More details: https://github.com/video-dev/hls.js/issues/355
  11291. */
  11292. ;
  11293. _proto.updateMediaElementDuration = function updateMediaElementDuration() {
  11294. var config = this.config;
  11295. var duration;
  11296. if (this._levelDuration === null || !this.media || !this.mediaSource || !this.sourceBuffer || this.media.readyState === 0 || this.mediaSource.readyState !== 'open') {
  11297. return;
  11298. }
  11299. for (var type in this.sourceBuffer) {
  11300. var sb = this.sourceBuffer[type];
  11301. if (sb && sb.updating === true) {
  11302. // can't set duration whilst a buffer is updating
  11303. return;
  11304. }
  11305. }
  11306. duration = this.media.duration; // initialise to the value that the media source is reporting
  11307. if (this._msDuration === null) {
  11308. this._msDuration = this.mediaSource.duration;
  11309. }
  11310. if (this._live === true && config.liveDurationInfinity === true) {
  11311. // Override duration to Infinity
  11312. logger["logger"].log('Media Source duration is set to Infinity');
  11313. this._msDuration = this.mediaSource.duration = Infinity;
  11314. } else if (this._levelDuration > this._msDuration && this._levelDuration > duration || !Object(number["isFiniteNumber"])(duration)) {
  11315. // levelDuration was the last value we set.
  11316. // not using mediaSource.duration as the browser may tweak this value
  11317. // only update Media Source duration if its value increase, this is to avoid
  11318. // flushing already buffered portion when switching between quality level
  11319. logger["logger"].log("Updating Media Source duration to " + this._levelDuration.toFixed(3));
  11320. this._msDuration = this.mediaSource.duration = this._levelDuration;
  11321. }
  11322. };
  11323. _proto.doFlush = function doFlush() {
  11324. // loop through all buffer ranges to flush
  11325. while (this.flushRange.length) {
  11326. var range = this.flushRange[0]; // flushBuffer will abort any buffer append in progress and flush Audio/Video Buffer
  11327. if (this.flushBuffer(range.start, range.end, range.type)) {
  11328. // range flushed, remove from flush array
  11329. this.flushRange.shift();
  11330. this.flushBufferCounter = 0;
  11331. } else {
  11332. this._needsFlush = true; // avoid looping, wait for SB update end to retrigger a flush
  11333. return;
  11334. }
  11335. }
  11336. if (this.flushRange.length === 0) {
  11337. // everything flushed
  11338. this._needsFlush = false; // let's recompute this.appended, which is used to avoid flush looping
  11339. var appended = 0;
  11340. var sourceBuffer = this.sourceBuffer;
  11341. try {
  11342. for (var type in sourceBuffer) {
  11343. var sb = sourceBuffer[type];
  11344. if (sb) {
  11345. appended += sb.buffered.length;
  11346. }
  11347. }
  11348. } catch (error) {
  11349. // error could be thrown while accessing buffered, in case sourcebuffer has already been removed from MediaSource
  11350. // this is harmess at this stage, catch this to avoid reporting an internal exception
  11351. logger["logger"].error('error while accessing sourceBuffer.buffered');
  11352. }
  11353. this.appended = appended;
  11354. this.hls.trigger(events["default"].BUFFER_FLUSHED);
  11355. }
  11356. };
  11357. _proto.doAppending = function doAppending() {
  11358. var config = this.config,
  11359. hls = this.hls,
  11360. segments = this.segments,
  11361. sourceBuffer = this.sourceBuffer;
  11362. if (!Object.keys(sourceBuffer).length) {
  11363. // early exit if no source buffers have been initialized yet
  11364. return;
  11365. }
  11366. if (!this.media || this.media.error) {
  11367. this.segments = [];
  11368. logger["logger"].error('trying to append although a media error occured, flush segment and abort');
  11369. return;
  11370. }
  11371. if (this.appending) {
  11372. // logger.log(`sb appending in progress`);
  11373. return;
  11374. }
  11375. var segment = segments.shift();
  11376. if (!segment) {
  11377. // handle undefined shift
  11378. return;
  11379. }
  11380. try {
  11381. var sb = sourceBuffer[segment.type];
  11382. if (!sb) {
  11383. // in case we don't have any source buffer matching with this segment type,
  11384. // it means that Mediasource fails to create sourcebuffer
  11385. // discard this segment, and trigger update end
  11386. this._onSBUpdateEnd();
  11387. return;
  11388. }
  11389. if (sb.updating) {
  11390. // if we are still updating the source buffer from the last segment, place this back at the front of the queue
  11391. segments.unshift(segment);
  11392. return;
  11393. } // reset sourceBuffer ended flag before appending segment
  11394. sb.ended = false; // logger.log(`appending ${segment.content} ${type} SB, size:${segment.data.length}, ${segment.parent}`);
  11395. this.parent = segment.parent;
  11396. sb.appendBuffer(segment.data);
  11397. this.appendError = 0;
  11398. this.appended++;
  11399. this.appending = true;
  11400. } catch (err) {
  11401. // in case any error occured while appending, put back segment in segments table
  11402. logger["logger"].error("error while trying to append buffer:" + err.message);
  11403. segments.unshift(segment);
  11404. var event = {
  11405. type: errors["ErrorTypes"].MEDIA_ERROR,
  11406. parent: segment.parent,
  11407. details: '',
  11408. fatal: false
  11409. };
  11410. if (err.code === 22) {
  11411. // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
  11412. // let's stop appending any segments, and report BUFFER_FULL_ERROR error
  11413. this.segments = [];
  11414. event.details = errors["ErrorDetails"].BUFFER_FULL_ERROR;
  11415. } else {
  11416. this.appendError++;
  11417. event.details = errors["ErrorDetails"].BUFFER_APPEND_ERROR;
  11418. /* with UHD content, we could get loop of quota exceeded error until
  11419. browser is able to evict some data from sourcebuffer. retrying help recovering this
  11420. */
  11421. if (this.appendError > config.appendErrorMaxRetry) {
  11422. logger["logger"].log("fail " + config.appendErrorMaxRetry + " times to append segment in sourceBuffer");
  11423. this.segments = [];
  11424. event.fatal = true;
  11425. }
  11426. }
  11427. hls.trigger(events["default"].ERROR, event);
  11428. }
  11429. }
  11430. /*
  11431. flush specified buffered range,
  11432. return true once range has been flushed.
  11433. as sourceBuffer.remove() is asynchronous, flushBuffer will be retriggered on sourceBuffer update end
  11434. */
  11435. ;
  11436. _proto.flushBuffer = function flushBuffer(startOffset, endOffset, sbType) {
  11437. var sourceBuffer = this.sourceBuffer; // exit if no sourceBuffers are initialized
  11438. if (!Object.keys(sourceBuffer).length) {
  11439. return true;
  11440. }
  11441. var currentTime = 'null';
  11442. if (this.media) {
  11443. currentTime = this.media.currentTime.toFixed(3);
  11444. }
  11445. logger["logger"].log("flushBuffer,pos/start/end: " + currentTime + "/" + startOffset + "/" + endOffset); // safeguard to avoid infinite looping : don't try to flush more than the nb of appended segments
  11446. if (this.flushBufferCounter >= this.appended) {
  11447. logger["logger"].warn('abort flushing too many retries');
  11448. return true;
  11449. }
  11450. var sb = sourceBuffer[sbType]; // we are going to flush buffer, mark source buffer as 'not ended'
  11451. if (sb) {
  11452. sb.ended = false;
  11453. if (!sb.updating) {
  11454. if (this.removeBufferRange(sbType, sb, startOffset, endOffset)) {
  11455. this.flushBufferCounter++;
  11456. return false;
  11457. }
  11458. } else {
  11459. logger["logger"].warn('cannot flush, sb updating in progress');
  11460. return false;
  11461. }
  11462. }
  11463. logger["logger"].log('buffer flushed'); // everything flushed !
  11464. return true;
  11465. }
  11466. /**
  11467. * Removes first buffered range from provided source buffer that lies within given start and end offsets.
  11468. *
  11469. * @param {string} type Type of the source buffer, logging purposes only.
  11470. * @param {SourceBuffer} sb Target SourceBuffer instance.
  11471. * @param {number} startOffset
  11472. * @param {number} endOffset
  11473. *
  11474. * @returns {boolean} True when source buffer remove requested.
  11475. */
  11476. ;
  11477. _proto.removeBufferRange = function removeBufferRange(type, sb, startOffset, endOffset) {
  11478. try {
  11479. for (var i = 0; i < sb.buffered.length; i++) {
  11480. var bufStart = sb.buffered.start(i);
  11481. var bufEnd = sb.buffered.end(i);
  11482. var removeStart = Math.max(bufStart, startOffset);
  11483. var removeEnd = Math.min(bufEnd, endOffset);
  11484. /* sometimes sourcebuffer.remove() does not flush
  11485. the exact expected time range.
  11486. to avoid rounding issues/infinite loop,
  11487. only flush buffer range of length greater than 500ms.
  11488. */
  11489. if (Math.min(removeEnd, bufEnd) - removeStart > 0.5) {
  11490. var currentTime = 'null';
  11491. if (this.media) {
  11492. currentTime = this.media.currentTime.toString();
  11493. }
  11494. logger["logger"].log("sb remove " + type + " [" + removeStart + "," + removeEnd + "], of [" + bufStart + "," + bufEnd + "], pos:" + currentTime);
  11495. sb.remove(removeStart, removeEnd);
  11496. return true;
  11497. }
  11498. }
  11499. } catch (error) {
  11500. logger["logger"].warn('removeBufferRange failed', error);
  11501. }
  11502. return false;
  11503. };
  11504. return BufferController;
  11505. }(event_handler);
  11506. /* harmony default export */ var buffer_controller = (buffer_controller_BufferController);
  11507. // CONCATENATED MODULE: ./src/controller/cap-level-controller.js
  11508. function cap_level_controller_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  11509. function cap_level_controller_createClass(Constructor, protoProps, staticProps) { if (protoProps) cap_level_controller_defineProperties(Constructor.prototype, protoProps); if (staticProps) cap_level_controller_defineProperties(Constructor, staticProps); return Constructor; }
  11510. function cap_level_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  11511. /*
  11512. * cap stream level to media size dimension controller
  11513. */
  11514. var cap_level_controller_CapLevelController = /*#__PURE__*/function (_EventHandler) {
  11515. cap_level_controller_inheritsLoose(CapLevelController, _EventHandler);
  11516. function CapLevelController(hls) {
  11517. var _this;
  11518. _this = _EventHandler.call(this, hls, events["default"].FPS_DROP_LEVEL_CAPPING, events["default"].MEDIA_ATTACHING, events["default"].MANIFEST_PARSED, events["default"].LEVELS_UPDATED, events["default"].BUFFER_CODECS, events["default"].MEDIA_DETACHING) || this;
  11519. _this.autoLevelCapping = Number.POSITIVE_INFINITY;
  11520. _this.firstLevel = null;
  11521. _this.levels = [];
  11522. _this.media = null;
  11523. _this.restrictedLevels = [];
  11524. _this.timer = null;
  11525. _this.clientRect = null;
  11526. return _this;
  11527. }
  11528. var _proto = CapLevelController.prototype;
  11529. _proto.destroy = function destroy() {
  11530. if (this.hls.config.capLevelToPlayerSize) {
  11531. this.media = null;
  11532. this.clientRect = null;
  11533. this.stopCapping();
  11534. }
  11535. };
  11536. _proto.onFpsDropLevelCapping = function onFpsDropLevelCapping(data) {
  11537. // Don't add a restricted level more than once
  11538. if (CapLevelController.isLevelAllowed(data.droppedLevel, this.restrictedLevels)) {
  11539. this.restrictedLevels.push(data.droppedLevel);
  11540. }
  11541. };
  11542. _proto.onMediaAttaching = function onMediaAttaching(data) {
  11543. this.media = data.media instanceof window.HTMLVideoElement ? data.media : null;
  11544. };
  11545. _proto.onManifestParsed = function onManifestParsed(data) {
  11546. var hls = this.hls;
  11547. this.restrictedLevels = [];
  11548. this.levels = data.levels;
  11549. this.firstLevel = data.firstLevel;
  11550. if (hls.config.capLevelToPlayerSize && data.video) {
  11551. // Start capping immediately if the manifest has signaled video codecs
  11552. this.startCapping();
  11553. }
  11554. } // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted
  11555. // to the first level
  11556. ;
  11557. _proto.onBufferCodecs = function onBufferCodecs(data) {
  11558. var hls = this.hls;
  11559. if (hls.config.capLevelToPlayerSize && data.video) {
  11560. // If the manifest did not signal a video codec capping has been deferred until we're certain video is present
  11561. this.startCapping();
  11562. }
  11563. };
  11564. _proto.onLevelsUpdated = function onLevelsUpdated(data) {
  11565. this.levels = data.levels;
  11566. };
  11567. _proto.onMediaDetaching = function onMediaDetaching() {
  11568. this.stopCapping();
  11569. };
  11570. _proto.detectPlayerSize = function detectPlayerSize() {
  11571. if (this.media) {
  11572. var levelsLength = this.levels ? this.levels.length : 0;
  11573. if (levelsLength) {
  11574. var hls = this.hls;
  11575. hls.autoLevelCapping = this.getMaxLevel(levelsLength - 1);
  11576. if (hls.autoLevelCapping > this.autoLevelCapping) {
  11577. // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch
  11578. // usually happen when the user go to the fullscreen mode.
  11579. hls.streamController.nextLevelSwitch();
  11580. }
  11581. this.autoLevelCapping = hls.autoLevelCapping;
  11582. }
  11583. }
  11584. }
  11585. /*
  11586. * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
  11587. */
  11588. ;
  11589. _proto.getMaxLevel = function getMaxLevel(capLevelIndex) {
  11590. var _this2 = this;
  11591. if (!this.levels) {
  11592. return -1;
  11593. }
  11594. var validLevels = this.levels.filter(function (level, index) {
  11595. return CapLevelController.isLevelAllowed(index, _this2.restrictedLevels) && index <= capLevelIndex;
  11596. });
  11597. this.clientRect = null;
  11598. return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
  11599. };
  11600. _proto.startCapping = function startCapping() {
  11601. if (this.timer) {
  11602. // Don't reset capping if started twice; this can happen if the manifest signals a video codec
  11603. return;
  11604. }
  11605. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  11606. this.hls.firstLevel = this.getMaxLevel(this.firstLevel);
  11607. clearInterval(this.timer);
  11608. this.timer = setInterval(this.detectPlayerSize.bind(this), 1000);
  11609. this.detectPlayerSize();
  11610. };
  11611. _proto.stopCapping = function stopCapping() {
  11612. this.restrictedLevels = [];
  11613. this.firstLevel = null;
  11614. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  11615. if (this.timer) {
  11616. this.timer = clearInterval(this.timer);
  11617. this.timer = null;
  11618. }
  11619. };
  11620. _proto.getDimensions = function getDimensions() {
  11621. if (this.clientRect) {
  11622. return this.clientRect;
  11623. }
  11624. var media = this.media;
  11625. var boundsRect = {
  11626. width: 0,
  11627. height: 0
  11628. };
  11629. if (media) {
  11630. var clientRect = media.getBoundingClientRect();
  11631. boundsRect.width = clientRect.width;
  11632. boundsRect.height = clientRect.height;
  11633. if (!boundsRect.width && !boundsRect.height) {
  11634. // When the media element has no width or height (equivalent to not being in the DOM),
  11635. // then use its width and height attributes (media.width, media.height)
  11636. boundsRect.width = clientRect.right - clientRect.left || media.width || 0;
  11637. boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;
  11638. }
  11639. }
  11640. this.clientRect = boundsRect;
  11641. return boundsRect;
  11642. };
  11643. CapLevelController.isLevelAllowed = function isLevelAllowed(level, restrictedLevels) {
  11644. if (restrictedLevels === void 0) {
  11645. restrictedLevels = [];
  11646. }
  11647. return restrictedLevels.indexOf(level) === -1;
  11648. };
  11649. CapLevelController.getMaxLevelByMediaSize = function getMaxLevelByMediaSize(levels, width, height) {
  11650. if (!levels || levels && !levels.length) {
  11651. return -1;
  11652. } // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next
  11653. // to determine whether we've chosen the greatest bandwidth for the media's dimensions
  11654. var atGreatestBandiwdth = function atGreatestBandiwdth(curLevel, nextLevel) {
  11655. if (!nextLevel) {
  11656. return true;
  11657. }
  11658. return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
  11659. }; // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to
  11660. // the max level
  11661. var maxLevelIndex = levels.length - 1;
  11662. for (var i = 0; i < levels.length; i += 1) {
  11663. var level = levels[i];
  11664. if ((level.width >= width || level.height >= height) && atGreatestBandiwdth(level, levels[i + 1])) {
  11665. maxLevelIndex = i;
  11666. break;
  11667. }
  11668. }
  11669. return maxLevelIndex;
  11670. };
  11671. cap_level_controller_createClass(CapLevelController, [{
  11672. key: "mediaWidth",
  11673. get: function get() {
  11674. return this.getDimensions().width * CapLevelController.contentScaleFactor;
  11675. }
  11676. }, {
  11677. key: "mediaHeight",
  11678. get: function get() {
  11679. return this.getDimensions().height * CapLevelController.contentScaleFactor;
  11680. }
  11681. }], [{
  11682. key: "contentScaleFactor",
  11683. get: function get() {
  11684. var pixelRatio = 1;
  11685. try {
  11686. pixelRatio = window.devicePixelRatio;
  11687. } catch (e) {}
  11688. return pixelRatio;
  11689. }
  11690. }]);
  11691. return CapLevelController;
  11692. }(event_handler);
  11693. /* harmony default export */ var cap_level_controller = (cap_level_controller_CapLevelController);
  11694. // CONCATENATED MODULE: ./src/controller/fps-controller.js
  11695. function fps_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  11696. /*
  11697. * FPS Controller
  11698. */
  11699. var fps_controller_window = window,
  11700. fps_controller_performance = fps_controller_window.performance;
  11701. var fps_controller_FPSController = /*#__PURE__*/function (_EventHandler) {
  11702. fps_controller_inheritsLoose(FPSController, _EventHandler);
  11703. function FPSController(hls) {
  11704. return _EventHandler.call(this, hls, events["default"].MEDIA_ATTACHING) || this;
  11705. }
  11706. var _proto = FPSController.prototype;
  11707. _proto.destroy = function destroy() {
  11708. if (this.timer) {
  11709. clearInterval(this.timer);
  11710. }
  11711. this.isVideoPlaybackQualityAvailable = false;
  11712. };
  11713. _proto.onMediaAttaching = function onMediaAttaching(data) {
  11714. var config = this.hls.config;
  11715. if (config.capLevelOnFPSDrop) {
  11716. var video = this.video = data.media instanceof window.HTMLVideoElement ? data.media : null;
  11717. if (typeof video.getVideoPlaybackQuality === 'function') {
  11718. this.isVideoPlaybackQualityAvailable = true;
  11719. }
  11720. clearInterval(this.timer);
  11721. this.timer = setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
  11722. }
  11723. };
  11724. _proto.checkFPS = function checkFPS(video, decodedFrames, droppedFrames) {
  11725. var currentTime = fps_controller_performance.now();
  11726. if (decodedFrames) {
  11727. if (this.lastTime) {
  11728. var currentPeriod = currentTime - this.lastTime,
  11729. currentDropped = droppedFrames - this.lastDroppedFrames,
  11730. currentDecoded = decodedFrames - this.lastDecodedFrames,
  11731. droppedFPS = 1000 * currentDropped / currentPeriod,
  11732. hls = this.hls;
  11733. hls.trigger(events["default"].FPS_DROP, {
  11734. currentDropped: currentDropped,
  11735. currentDecoded: currentDecoded,
  11736. totalDroppedFrames: droppedFrames
  11737. });
  11738. if (droppedFPS > 0) {
  11739. // logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));
  11740. if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
  11741. var currentLevel = hls.currentLevel;
  11742. logger["logger"].warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);
  11743. if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
  11744. currentLevel = currentLevel - 1;
  11745. hls.trigger(events["default"].FPS_DROP_LEVEL_CAPPING, {
  11746. level: currentLevel,
  11747. droppedLevel: hls.currentLevel
  11748. });
  11749. hls.autoLevelCapping = currentLevel;
  11750. hls.streamController.nextLevelSwitch();
  11751. }
  11752. }
  11753. }
  11754. }
  11755. this.lastTime = currentTime;
  11756. this.lastDroppedFrames = droppedFrames;
  11757. this.lastDecodedFrames = decodedFrames;
  11758. }
  11759. };
  11760. _proto.checkFPSInterval = function checkFPSInterval() {
  11761. var video = this.video;
  11762. if (video) {
  11763. if (this.isVideoPlaybackQualityAvailable) {
  11764. var videoPlaybackQuality = video.getVideoPlaybackQuality();
  11765. this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
  11766. } else {
  11767. this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
  11768. }
  11769. }
  11770. };
  11771. return FPSController;
  11772. }(event_handler);
  11773. /* harmony default export */ var fps_controller = (fps_controller_FPSController);
  11774. // CONCATENATED MODULE: ./src/utils/xhr-loader.js
  11775. /**
  11776. * XHR based logger
  11777. */
  11778. var xhr_loader_XhrLoader = /*#__PURE__*/function () {
  11779. function XhrLoader(config) {
  11780. if (config && config.xhrSetup) {
  11781. this.xhrSetup = config.xhrSetup;
  11782. }
  11783. }
  11784. var _proto = XhrLoader.prototype;
  11785. _proto.destroy = function destroy() {
  11786. this.abort();
  11787. this.loader = null;
  11788. };
  11789. _proto.abort = function abort() {
  11790. var loader = this.loader;
  11791. if (loader && loader.readyState !== 4) {
  11792. this.stats.aborted = true;
  11793. loader.abort();
  11794. }
  11795. window.clearTimeout(this.requestTimeout);
  11796. this.requestTimeout = null;
  11797. window.clearTimeout(this.retryTimeout);
  11798. this.retryTimeout = null;
  11799. };
  11800. _proto.load = function load(context, config, callbacks) {
  11801. this.context = context;
  11802. this.config = config;
  11803. this.callbacks = callbacks;
  11804. this.stats = {
  11805. trequest: window.performance.now(),
  11806. retry: 0
  11807. };
  11808. this.retryDelay = config.retryDelay;
  11809. this.loadInternal();
  11810. };
  11811. _proto.loadInternal = function loadInternal() {
  11812. var xhr,
  11813. context = this.context;
  11814. xhr = this.loader = new window.XMLHttpRequest();
  11815. var stats = this.stats;
  11816. stats.tfirst = 0;
  11817. stats.loaded = 0;
  11818. var xhrSetup = this.xhrSetup;
  11819. try {
  11820. if (xhrSetup) {
  11821. try {
  11822. xhrSetup(xhr, context.url);
  11823. } catch (e) {
  11824. // fix xhrSetup: (xhr, url) => {xhr.setRequestHeader("Content-Language", "test");}
  11825. // not working, as xhr.setRequestHeader expects xhr.readyState === OPEN
  11826. xhr.open('GET', context.url, true);
  11827. xhrSetup(xhr, context.url);
  11828. }
  11829. }
  11830. if (!xhr.readyState) {
  11831. xhr.open('GET', context.url, true);
  11832. }
  11833. } catch (e) {
  11834. // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
  11835. this.callbacks.onError({
  11836. code: xhr.status,
  11837. text: e.message
  11838. }, context, xhr);
  11839. return;
  11840. }
  11841. if (context.rangeEnd) {
  11842. xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));
  11843. }
  11844. xhr.onreadystatechange = this.readystatechange.bind(this);
  11845. xhr.onprogress = this.loadprogress.bind(this);
  11846. xhr.responseType = context.responseType; // setup timeout before we perform request
  11847. this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), this.config.timeout);
  11848. xhr.send();
  11849. };
  11850. _proto.readystatechange = function readystatechange(event) {
  11851. var xhr = event.currentTarget,
  11852. readyState = xhr.readyState,
  11853. stats = this.stats,
  11854. context = this.context,
  11855. config = this.config; // don't proceed if xhr has been aborted
  11856. if (stats.aborted) {
  11857. return;
  11858. } // >= HEADERS_RECEIVED
  11859. if (readyState >= 2) {
  11860. // clear xhr timeout and rearm it if readyState less than 4
  11861. window.clearTimeout(this.requestTimeout);
  11862. if (stats.tfirst === 0) {
  11863. stats.tfirst = Math.max(window.performance.now(), stats.trequest);
  11864. }
  11865. if (readyState === 4) {
  11866. var status = xhr.status; // http status between 200 to 299 are all successful
  11867. if (status >= 200 && status < 300) {
  11868. stats.tload = Math.max(stats.tfirst, window.performance.now());
  11869. var data, len;
  11870. if (context.responseType === 'arraybuffer') {
  11871. data = xhr.response;
  11872. len = data.byteLength;
  11873. } else {
  11874. data = xhr.responseText;
  11875. len = data.length;
  11876. }
  11877. stats.loaded = stats.total = len;
  11878. var response = {
  11879. url: xhr.responseURL,
  11880. data: data
  11881. };
  11882. this.callbacks.onSuccess(response, stats, context, xhr);
  11883. } else {
  11884. // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error
  11885. if (stats.retry >= config.maxRetry || status >= 400 && status < 499) {
  11886. logger["logger"].error(status + " while loading " + context.url);
  11887. this.callbacks.onError({
  11888. code: status,
  11889. text: xhr.statusText
  11890. }, context, xhr);
  11891. } else {
  11892. // retry
  11893. logger["logger"].warn(status + " while loading " + context.url + ", retrying in " + this.retryDelay + "..."); // aborts and resets internal state
  11894. this.destroy(); // schedule retry
  11895. this.retryTimeout = window.setTimeout(this.loadInternal.bind(this), this.retryDelay); // set exponential backoff
  11896. this.retryDelay = Math.min(2 * this.retryDelay, config.maxRetryDelay);
  11897. stats.retry++;
  11898. }
  11899. }
  11900. } else {
  11901. // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet
  11902. this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), config.timeout);
  11903. }
  11904. }
  11905. };
  11906. _proto.loadtimeout = function loadtimeout() {
  11907. logger["logger"].warn("timeout while loading " + this.context.url);
  11908. this.callbacks.onTimeout(this.stats, this.context, null);
  11909. };
  11910. _proto.loadprogress = function loadprogress(event) {
  11911. var xhr = event.currentTarget,
  11912. stats = this.stats;
  11913. stats.loaded = event.loaded;
  11914. if (event.lengthComputable) {
  11915. stats.total = event.total;
  11916. }
  11917. var onProgress = this.callbacks.onProgress;
  11918. if (onProgress) {
  11919. // third arg is to provide on progress data
  11920. onProgress(stats, this.context, null, xhr);
  11921. }
  11922. };
  11923. return XhrLoader;
  11924. }();
  11925. /* harmony default export */ var xhr_loader = (xhr_loader_XhrLoader);
  11926. // CONCATENATED MODULE: ./src/controller/audio-track-controller.js
  11927. function audio_track_controller_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  11928. function audio_track_controller_createClass(Constructor, protoProps, staticProps) { if (protoProps) audio_track_controller_defineProperties(Constructor.prototype, protoProps); if (staticProps) audio_track_controller_defineProperties(Constructor, staticProps); return Constructor; }
  11929. function audio_track_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  11930. /**
  11931. * @class AudioTrackController
  11932. * @implements {EventHandler}
  11933. *
  11934. * Handles main manifest and audio-track metadata loaded,
  11935. * owns and exposes the selectable audio-tracks data-models.
  11936. *
  11937. * Exposes internal interface to select available audio-tracks.
  11938. *
  11939. * Handles errors on loading audio-track playlists. Manages fallback mechanism
  11940. * with redundants tracks (group-IDs).
  11941. *
  11942. * Handles level-loading and group-ID switches for video (fallback on video levels),
  11943. * and eventually adapts the audio-track group-ID to match.
  11944. *
  11945. * @fires AUDIO_TRACK_LOADING
  11946. * @fires AUDIO_TRACK_SWITCHING
  11947. * @fires AUDIO_TRACKS_UPDATED
  11948. * @fires ERROR
  11949. *
  11950. */
  11951. var audio_track_controller_AudioTrackController = /*#__PURE__*/function (_TaskLoop) {
  11952. audio_track_controller_inheritsLoose(AudioTrackController, _TaskLoop);
  11953. function AudioTrackController(hls) {
  11954. var _this;
  11955. _this = _TaskLoop.call(this, hls, events["default"].MANIFEST_LOADING, events["default"].MANIFEST_PARSED, events["default"].AUDIO_TRACK_LOADED, events["default"].AUDIO_TRACK_SWITCHED, events["default"].LEVEL_LOADED, events["default"].ERROR) || this;
  11956. /**
  11957. * @private
  11958. * Currently selected index in `tracks`
  11959. * @member {number} trackId
  11960. */
  11961. _this._trackId = -1;
  11962. /**
  11963. * @private
  11964. * If should select tracks according to default track attribute
  11965. * @member {boolean} _selectDefaultTrack
  11966. */
  11967. _this._selectDefaultTrack = true;
  11968. /**
  11969. * @public
  11970. * All tracks available
  11971. * @member {AudioTrack[]}
  11972. */
  11973. _this.tracks = [];
  11974. /**
  11975. * @public
  11976. * List of blacklisted audio track IDs (that have caused failure)
  11977. * @member {number[]}
  11978. */
  11979. _this.trackIdBlacklist = Object.create(null);
  11980. /**
  11981. * @public
  11982. * The currently running group ID for audio
  11983. * (we grab this on manifest-parsed and new level-loaded)
  11984. * @member {string}
  11985. */
  11986. _this.audioGroupId = null;
  11987. return _this;
  11988. }
  11989. /**
  11990. * Reset audio tracks on new manifest loading.
  11991. */
  11992. var _proto = AudioTrackController.prototype;
  11993. _proto.onManifestLoading = function onManifestLoading() {
  11994. this.tracks = [];
  11995. this._trackId = -1;
  11996. this._selectDefaultTrack = true;
  11997. }
  11998. /**
  11999. * Store tracks data from manifest parsed data.
  12000. *
  12001. * Trigger AUDIO_TRACKS_UPDATED event.
  12002. *
  12003. * @param {*} data
  12004. */
  12005. ;
  12006. _proto.onManifestParsed = function onManifestParsed(data) {
  12007. var tracks = this.tracks = data.audioTracks || [];
  12008. this.hls.trigger(events["default"].AUDIO_TRACKS_UPDATED, {
  12009. audioTracks: tracks
  12010. });
  12011. this._selectAudioGroup(this.hls.nextLoadLevel);
  12012. }
  12013. /**
  12014. * Store track details of loaded track in our data-model.
  12015. *
  12016. * Set-up metadata update interval task for live-mode streams.
  12017. *
  12018. * @param {*} data
  12019. */
  12020. ;
  12021. _proto.onAudioTrackLoaded = function onAudioTrackLoaded(data) {
  12022. if (data.id >= this.tracks.length) {
  12023. logger["logger"].warn('Invalid audio track id:', data.id);
  12024. return;
  12025. }
  12026. logger["logger"].log("audioTrack " + data.id + " loaded");
  12027. this.tracks[data.id].details = data.details; // check if current playlist is a live playlist
  12028. // and if we have already our reload interval setup
  12029. if (data.details.live && !this.hasInterval()) {
  12030. // if live playlist we will have to reload it periodically
  12031. // set reload period to playlist target duration
  12032. var updatePeriodMs = data.details.targetduration * 1000;
  12033. this.setInterval(updatePeriodMs);
  12034. }
  12035. if (!data.details.live && this.hasInterval()) {
  12036. // playlist is not live and timer is scheduled: cancel it
  12037. this.clearInterval();
  12038. }
  12039. }
  12040. /**
  12041. * Update the internal group ID to any audio-track we may have set manually
  12042. * or because of a failure-handling fallback.
  12043. *
  12044. * Quality-levels should update to that group ID in this case.
  12045. *
  12046. * @param {*} data
  12047. */
  12048. ;
  12049. _proto.onAudioTrackSwitched = function onAudioTrackSwitched(data) {
  12050. var audioGroupId = this.tracks[data.id].groupId;
  12051. if (audioGroupId && this.audioGroupId !== audioGroupId) {
  12052. this.audioGroupId = audioGroupId;
  12053. }
  12054. }
  12055. /**
  12056. * When a level gets loaded, if it has redundant audioGroupIds (in the same ordinality as it's redundant URLs)
  12057. * we are setting our audio-group ID internally to the one set, if it is different from the group ID currently set.
  12058. *
  12059. * If group-ID got update, we re-select the appropriate audio-track with this group-ID matching the currently
  12060. * selected one (based on NAME property).
  12061. *
  12062. * @param {*} data
  12063. */
  12064. ;
  12065. _proto.onLevelLoaded = function onLevelLoaded(data) {
  12066. this._selectAudioGroup(data.level);
  12067. }
  12068. /**
  12069. * Handle network errors loading audio track manifests
  12070. * and also pausing on any netwok errors.
  12071. *
  12072. * @param {ErrorEventData} data
  12073. */
  12074. ;
  12075. _proto.onError = function onError(data) {
  12076. // Only handle network errors
  12077. if (data.type !== errors["ErrorTypes"].NETWORK_ERROR) {
  12078. return;
  12079. } // If fatal network error, cancel update task
  12080. if (data.fatal) {
  12081. this.clearInterval();
  12082. } // If not an audio-track loading error don't handle further
  12083. if (data.details !== errors["ErrorDetails"].AUDIO_TRACK_LOAD_ERROR) {
  12084. return;
  12085. }
  12086. logger["logger"].warn('Network failure on audio-track id:', data.context.id);
  12087. this._handleLoadError();
  12088. }
  12089. /**
  12090. * @type {AudioTrack[]} Audio-track list we own
  12091. */
  12092. ;
  12093. /**
  12094. * @private
  12095. * @param {number} newId
  12096. */
  12097. _proto._setAudioTrack = function _setAudioTrack(newId) {
  12098. // noop on same audio track id as already set
  12099. if (this._trackId === newId && this.tracks[this._trackId].details) {
  12100. logger["logger"].debug('Same id as current audio-track passed, and track details available -> no-op');
  12101. return;
  12102. } // check if level idx is valid
  12103. if (newId < 0 || newId >= this.tracks.length) {
  12104. logger["logger"].warn('Invalid id passed to audio-track controller');
  12105. return;
  12106. }
  12107. var audioTrack = this.tracks[newId];
  12108. logger["logger"].log("Now switching to audio-track index " + newId); // stopping live reloading timer if any
  12109. this.clearInterval();
  12110. this._trackId = newId;
  12111. var url = audioTrack.url,
  12112. type = audioTrack.type,
  12113. id = audioTrack.id;
  12114. this.hls.trigger(events["default"].AUDIO_TRACK_SWITCHING, {
  12115. id: id,
  12116. type: type,
  12117. url: url
  12118. });
  12119. this._loadTrackDetailsIfNeeded(audioTrack);
  12120. }
  12121. /**
  12122. * @override
  12123. */
  12124. ;
  12125. _proto.doTick = function doTick() {
  12126. this._updateTrack(this._trackId);
  12127. }
  12128. /**
  12129. * @param levelId
  12130. * @private
  12131. */
  12132. ;
  12133. _proto._selectAudioGroup = function _selectAudioGroup(levelId) {
  12134. var levelInfo = this.hls.levels[levelId];
  12135. if (!levelInfo || !levelInfo.audioGroupIds) {
  12136. return;
  12137. }
  12138. var audioGroupId = levelInfo.audioGroupIds[levelInfo.urlId];
  12139. if (this.audioGroupId !== audioGroupId) {
  12140. this.audioGroupId = audioGroupId;
  12141. this._selectInitialAudioTrack();
  12142. }
  12143. }
  12144. /**
  12145. * Select initial track
  12146. * @private
  12147. */
  12148. ;
  12149. _proto._selectInitialAudioTrack = function _selectInitialAudioTrack() {
  12150. var _this2 = this;
  12151. var tracks = this.tracks;
  12152. if (!tracks.length) {
  12153. return;
  12154. }
  12155. var currentAudioTrack = this.tracks[this._trackId];
  12156. var name = null;
  12157. if (currentAudioTrack) {
  12158. name = currentAudioTrack.name;
  12159. } // Pre-select default tracks if there are any
  12160. if (this._selectDefaultTrack) {
  12161. var defaultTracks = tracks.filter(function (track) {
  12162. return track.default;
  12163. });
  12164. if (defaultTracks.length) {
  12165. tracks = defaultTracks;
  12166. } else {
  12167. logger["logger"].warn('No default audio tracks defined');
  12168. }
  12169. }
  12170. var trackFound = false;
  12171. var traverseTracks = function traverseTracks() {
  12172. // Select track with right group ID
  12173. tracks.forEach(function (track) {
  12174. if (trackFound) {
  12175. return;
  12176. } // We need to match the (pre-)selected group ID
  12177. // and the NAME of the current track.
  12178. if ((!_this2.audioGroupId || track.groupId === _this2.audioGroupId) && (!name || name === track.name)) {
  12179. // If there was a previous track try to stay with the same `NAME`.
  12180. // It should be unique across tracks of same group, and consistent through redundant track groups.
  12181. _this2._setAudioTrack(track.id);
  12182. trackFound = true;
  12183. }
  12184. });
  12185. };
  12186. traverseTracks();
  12187. if (!trackFound) {
  12188. name = null;
  12189. traverseTracks();
  12190. }
  12191. if (!trackFound) {
  12192. logger["logger"].error("No track found for running audio group-ID: " + this.audioGroupId);
  12193. this.hls.trigger(events["default"].ERROR, {
  12194. type: errors["ErrorTypes"].MEDIA_ERROR,
  12195. details: errors["ErrorDetails"].AUDIO_TRACK_LOAD_ERROR,
  12196. fatal: true
  12197. });
  12198. }
  12199. }
  12200. /**
  12201. * @private
  12202. * @param {AudioTrack} audioTrack
  12203. * @returns {boolean}
  12204. */
  12205. ;
  12206. _proto._needsTrackLoading = function _needsTrackLoading(audioTrack) {
  12207. var details = audioTrack.details,
  12208. url = audioTrack.url;
  12209. if (!details || details.live) {
  12210. // check if we face an audio track embedded in main playlist (audio track without URI attribute)
  12211. return !!url;
  12212. }
  12213. return false;
  12214. }
  12215. /**
  12216. * @private
  12217. * @param {AudioTrack} audioTrack
  12218. */
  12219. ;
  12220. _proto._loadTrackDetailsIfNeeded = function _loadTrackDetailsIfNeeded(audioTrack) {
  12221. if (this._needsTrackLoading(audioTrack)) {
  12222. var url = audioTrack.url,
  12223. id = audioTrack.id; // track not retrieved yet, or live playlist we need to (re)load it
  12224. logger["logger"].log("loading audio-track playlist for id: " + id);
  12225. this.hls.trigger(events["default"].AUDIO_TRACK_LOADING, {
  12226. url: url,
  12227. id: id
  12228. });
  12229. }
  12230. }
  12231. /**
  12232. * @private
  12233. * @param {number} newId
  12234. */
  12235. ;
  12236. _proto._updateTrack = function _updateTrack(newId) {
  12237. // check if level idx is valid
  12238. if (newId < 0 || newId >= this.tracks.length) {
  12239. return;
  12240. } // stopping live reloading timer if any
  12241. this.clearInterval();
  12242. this._trackId = newId;
  12243. logger["logger"].log("trying to update audio-track " + newId);
  12244. var audioTrack = this.tracks[newId];
  12245. this._loadTrackDetailsIfNeeded(audioTrack);
  12246. }
  12247. /**
  12248. * @private
  12249. */
  12250. ;
  12251. _proto._handleLoadError = function _handleLoadError() {
  12252. // First, let's black list current track id
  12253. this.trackIdBlacklist[this._trackId] = true; // Let's try to fall back on a functional audio-track with the same group ID
  12254. var previousId = this._trackId;
  12255. var _this$tracks$previous = this.tracks[previousId],
  12256. name = _this$tracks$previous.name,
  12257. language = _this$tracks$previous.language,
  12258. groupId = _this$tracks$previous.groupId;
  12259. logger["logger"].warn("Loading failed on audio track id: " + previousId + ", group-id: " + groupId + ", name/language: \"" + name + "\" / \"" + language + "\""); // Find a non-blacklisted track ID with the same NAME
  12260. // At least a track that is not blacklisted, thus on another group-ID.
  12261. var newId = previousId;
  12262. for (var i = 0; i < this.tracks.length; i++) {
  12263. if (this.trackIdBlacklist[i]) {
  12264. continue;
  12265. }
  12266. var newTrack = this.tracks[i];
  12267. if (newTrack.name === name) {
  12268. newId = i;
  12269. break;
  12270. }
  12271. }
  12272. if (newId === previousId) {
  12273. logger["logger"].warn("No fallback audio-track found for name/language: \"" + name + "\" / \"" + language + "\"");
  12274. return;
  12275. }
  12276. logger["logger"].log('Attempting audio-track fallback id:', newId, 'group-id:', this.tracks[newId].groupId);
  12277. this._setAudioTrack(newId);
  12278. };
  12279. audio_track_controller_createClass(AudioTrackController, [{
  12280. key: "audioTracks",
  12281. get: function get() {
  12282. return this.tracks;
  12283. }
  12284. /**
  12285. * @type {number} Index into audio-tracks list of currently selected track.
  12286. */
  12287. }, {
  12288. key: "audioTrack",
  12289. get: function get() {
  12290. return this._trackId;
  12291. }
  12292. /**
  12293. * Select current track by index
  12294. */
  12295. ,
  12296. set: function set(newId) {
  12297. this._setAudioTrack(newId); // If audio track is selected from API then don't choose from the manifest default track
  12298. this._selectDefaultTrack = false;
  12299. }
  12300. }]);
  12301. return AudioTrackController;
  12302. }(TaskLoop);
  12303. /* harmony default export */ var audio_track_controller = (audio_track_controller_AudioTrackController);
  12304. // CONCATENATED MODULE: ./src/controller/audio-stream-controller.js
  12305. function audio_stream_controller_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  12306. function audio_stream_controller_createClass(Constructor, protoProps, staticProps) { if (protoProps) audio_stream_controller_defineProperties(Constructor.prototype, protoProps); if (staticProps) audio_stream_controller_defineProperties(Constructor, staticProps); return Constructor; }
  12307. function audio_stream_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  12308. /*
  12309. * Audio Stream Controller
  12310. */
  12311. var audio_stream_controller_window = window,
  12312. audio_stream_controller_performance = audio_stream_controller_window.performance;
  12313. var audio_stream_controller_TICK_INTERVAL = 100; // how often to tick in ms
  12314. var audio_stream_controller_AudioStreamController = /*#__PURE__*/function (_BaseStreamController) {
  12315. audio_stream_controller_inheritsLoose(AudioStreamController, _BaseStreamController);
  12316. function AudioStreamController(hls, fragmentTracker) {
  12317. var _this;
  12318. _this = _BaseStreamController.call(this, hls, events["default"].MEDIA_ATTACHED, events["default"].MEDIA_DETACHING, events["default"].AUDIO_TRACKS_UPDATED, events["default"].AUDIO_TRACK_SWITCHING, events["default"].AUDIO_TRACK_LOADED, events["default"].KEY_LOADED, events["default"].FRAG_LOADED, events["default"].FRAG_PARSING_INIT_SEGMENT, events["default"].FRAG_PARSING_DATA, events["default"].FRAG_PARSED, events["default"].ERROR, events["default"].BUFFER_RESET, events["default"].BUFFER_CREATED, events["default"].BUFFER_APPENDED, events["default"].BUFFER_FLUSHED, events["default"].INIT_PTS_FOUND) || this;
  12319. _this.fragmentTracker = fragmentTracker;
  12320. _this.config = hls.config;
  12321. _this.audioCodecSwap = false;
  12322. _this._state = State.STOPPED;
  12323. _this.initPTS = [];
  12324. _this.waitingFragment = null;
  12325. _this.videoTrackCC = null;
  12326. _this.waitingVideoCC = null;
  12327. return _this;
  12328. } // Signal that video PTS was found
  12329. var _proto = AudioStreamController.prototype;
  12330. _proto.onInitPtsFound = function onInitPtsFound(data) {
  12331. var demuxerId = data.id,
  12332. cc = data.frag.cc,
  12333. initPTS = data.initPTS;
  12334. if (demuxerId === 'main') {
  12335. // Always update the new INIT PTS
  12336. // Can change due level switch
  12337. this.initPTS[cc] = initPTS;
  12338. this.videoTrackCC = cc;
  12339. logger["logger"].log("InitPTS for cc: " + cc + " found from main: " + initPTS); // If we are waiting we need to demux/remux the waiting frag
  12340. // With the new initPTS
  12341. if (this.state === State.WAITING_INIT_PTS) {
  12342. this.tick();
  12343. }
  12344. }
  12345. };
  12346. _proto.startLoad = function startLoad(startPosition) {
  12347. if (this.tracks) {
  12348. var lastCurrentTime = this.lastCurrentTime;
  12349. this.stopLoad();
  12350. this.setInterval(audio_stream_controller_TICK_INTERVAL);
  12351. this.fragLoadError = 0;
  12352. if (lastCurrentTime > 0 && startPosition === -1) {
  12353. logger["logger"].log("audio:override startPosition with lastCurrentTime @" + lastCurrentTime.toFixed(3));
  12354. this.state = State.IDLE;
  12355. } else {
  12356. this.lastCurrentTime = this.startPosition ? this.startPosition : startPosition;
  12357. this.state = State.STARTING;
  12358. }
  12359. this.nextLoadPosition = this.startPosition = this.lastCurrentTime;
  12360. this.tick();
  12361. } else {
  12362. this.startPosition = startPosition;
  12363. this.state = State.STOPPED;
  12364. }
  12365. };
  12366. _proto.doTick = function doTick() {
  12367. var pos,
  12368. track,
  12369. trackDetails,
  12370. hls = this.hls,
  12371. config = hls.config; // logger.log('audioStream:' + this.state);
  12372. switch (this.state) {
  12373. case State.ERROR: // don't do anything in error state to avoid breaking further ...
  12374. case State.PAUSED: // don't do anything in paused state either ...
  12375. case State.BUFFER_FLUSHING:
  12376. break;
  12377. case State.STARTING:
  12378. this.state = State.WAITING_TRACK;
  12379. this.loadedmetadata = false;
  12380. break;
  12381. case State.IDLE:
  12382. var tracks = this.tracks; // audio tracks not received => exit loop
  12383. if (!tracks) {
  12384. break;
  12385. } // if video not attached AND
  12386. // start fragment already requested OR start frag prefetch disable
  12387. // exit loop
  12388. // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop
  12389. if (!this.media && (this.startFragRequested || !config.startFragPrefetch)) {
  12390. break;
  12391. } // determine next candidate fragment to be loaded, based on current position and
  12392. // end of buffer position
  12393. // if we have not yet loaded any fragment, start loading from start position
  12394. if (this.loadedmetadata) {
  12395. pos = this.media.currentTime;
  12396. } else {
  12397. pos = this.nextLoadPosition;
  12398. if (pos === undefined) {
  12399. break;
  12400. }
  12401. }
  12402. var media = this.mediaBuffer ? this.mediaBuffer : this.media;
  12403. var videoBuffer = this.videoBuffer ? this.videoBuffer : this.media;
  12404. var maxBufferHole = pos < config.maxBufferHole ? Math.max(MAX_START_GAP_JUMP, config.maxBufferHole) : config.maxBufferHole;
  12405. var bufferInfo = BufferHelper.bufferInfo(media, pos, maxBufferHole);
  12406. var mainBufferInfo = BufferHelper.bufferInfo(videoBuffer, pos, maxBufferHole);
  12407. var bufferLen = bufferInfo.len;
  12408. var bufferEnd = bufferInfo.end;
  12409. var fragPrevious = this.fragPrevious; // ensure we buffer at least config.maxBufferLength (default 30s) or config.maxMaxBufferLength (default: 600s)
  12410. // whichever is smaller.
  12411. // once we reach that threshold, don't buffer more than video (mainBufferInfo.len)
  12412. var maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength);
  12413. var maxBufLen = Math.max(maxConfigBuffer, mainBufferInfo.len);
  12414. var audioSwitch = this.audioSwitch;
  12415. var trackId = this.trackId; // if buffer length is less than maxBufLen try to load a new fragment
  12416. if ((bufferLen < maxBufLen || audioSwitch) && trackId < tracks.length) {
  12417. trackDetails = tracks[trackId].details; // if track info not retrieved yet, switch state and wait for track retrieval
  12418. if (typeof trackDetails === 'undefined') {
  12419. this.state = State.WAITING_TRACK;
  12420. break;
  12421. }
  12422. if (!audioSwitch && this._streamEnded(bufferInfo, trackDetails)) {
  12423. this.hls.trigger(events["default"].BUFFER_EOS, {
  12424. type: 'audio'
  12425. });
  12426. this.state = State.ENDED;
  12427. return;
  12428. } // find fragment index, contiguous with end of buffer position
  12429. var fragments = trackDetails.fragments,
  12430. fragLen = fragments.length,
  12431. start = fragments[0].start,
  12432. end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,
  12433. frag; // When switching audio track, reload audio as close as possible to currentTime
  12434. if (audioSwitch) {
  12435. if (trackDetails.live && !trackDetails.PTSKnown) {
  12436. logger["logger"].log('switching audiotrack, live stream, unknown PTS,load first fragment');
  12437. bufferEnd = 0;
  12438. } else {
  12439. bufferEnd = pos; // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime
  12440. if (trackDetails.PTSKnown && pos < start) {
  12441. // if everything is buffered from pos to start or if audio buffer upfront, let's seek to start
  12442. if (bufferInfo.end > start || bufferInfo.nextStart) {
  12443. logger["logger"].log('alt audio track ahead of main track, seek to start of alt audio track');
  12444. this.media.currentTime = start + 0.05;
  12445. } else {
  12446. return;
  12447. }
  12448. }
  12449. }
  12450. }
  12451. if (trackDetails.initSegment && !trackDetails.initSegment.data) {
  12452. frag = trackDetails.initSegment;
  12453. } // eslint-disable-line brace-style
  12454. // if bufferEnd before start of playlist, load first fragment
  12455. else if (bufferEnd <= start) {
  12456. frag = fragments[0];
  12457. if (this.videoTrackCC !== null && frag.cc !== this.videoTrackCC) {
  12458. // Ensure we find a fragment which matches the continuity of the video track
  12459. frag = findFragWithCC(fragments, this.videoTrackCC);
  12460. }
  12461. if (trackDetails.live && frag.loadIdx && frag.loadIdx === this.fragLoadIdx) {
  12462. // we just loaded this first fragment, and we are still lagging behind the start of the live playlist
  12463. // let's force seek to start
  12464. var nextBuffered = bufferInfo.nextStart ? bufferInfo.nextStart : start;
  12465. logger["logger"].log("no alt audio available @currentTime:" + this.media.currentTime + ", seeking @" + (nextBuffered + 0.05));
  12466. this.media.currentTime = nextBuffered + 0.05;
  12467. return;
  12468. }
  12469. } else {
  12470. var foundFrag;
  12471. var maxFragLookUpTolerance = config.maxFragLookUpTolerance;
  12472. var fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : undefined;
  12473. if (bufferEnd < end) {
  12474. if (bufferEnd > end - maxFragLookUpTolerance) {
  12475. maxFragLookUpTolerance = 0;
  12476. } // Prefer the next fragment if it's within tolerance
  12477. if (fragNext && !fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext)) {
  12478. foundFrag = fragNext;
  12479. } else {
  12480. foundFrag = binary_search.search(fragments, function (frag) {
  12481. return fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, frag);
  12482. });
  12483. }
  12484. } else {
  12485. // reach end of playlist
  12486. foundFrag = fragments[fragLen - 1];
  12487. }
  12488. if (foundFrag) {
  12489. frag = foundFrag;
  12490. start = foundFrag.start; // logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);
  12491. if (fragPrevious && frag.level === fragPrevious.level && frag.sn === fragPrevious.sn) {
  12492. if (frag.sn < trackDetails.endSN) {
  12493. frag = fragments[frag.sn + 1 - trackDetails.startSN];
  12494. if (this.fragmentTracker.getState(frag) !== FragmentState.OK) {
  12495. logger["logger"].log("SN just loaded, load next one: " + frag.sn);
  12496. }
  12497. } else {
  12498. frag = null;
  12499. }
  12500. }
  12501. }
  12502. }
  12503. if (frag) {
  12504. // logger.log(' loading frag ' + i +',pos/bufEnd:' + pos.toFixed(3) + '/' + bufferEnd.toFixed(3));
  12505. if (frag.encrypted) {
  12506. logger["logger"].log("Loading key for " + frag.sn + " of [" + trackDetails.startSN + " ," + trackDetails.endSN + "],track " + trackId);
  12507. this.state = State.KEY_LOADING;
  12508. hls.trigger(events["default"].KEY_LOADING, {
  12509. frag: frag
  12510. });
  12511. } else {
  12512. // only load if fragment is not loaded or if in audio switch
  12513. // we force a frag loading in audio switch as fragment tracker might not have evicted previous frags in case of quick audio switch
  12514. this.fragCurrent = frag;
  12515. if (audioSwitch || this.fragmentTracker.getState(frag) === FragmentState.NOT_LOADED) {
  12516. logger["logger"].log("Loading " + frag.sn + ", cc: " + frag.cc + " of [" + trackDetails.startSN + " ," + trackDetails.endSN + "],track " + trackId + ", " + (this.loadedmetadata ? 'currentTime' : 'nextLoadPosition') + ": " + pos + ", bufferEnd: " + bufferEnd.toFixed(3));
  12517. if (frag.sn !== 'initSegment') {
  12518. this.startFragRequested = true;
  12519. }
  12520. if (Object(number["isFiniteNumber"])(frag.sn)) {
  12521. this.nextLoadPosition = frag.start + frag.duration;
  12522. }
  12523. hls.trigger(events["default"].FRAG_LOADING, {
  12524. frag: frag
  12525. });
  12526. this.state = State.FRAG_LOADING;
  12527. }
  12528. }
  12529. }
  12530. }
  12531. break;
  12532. case State.WAITING_TRACK:
  12533. track = this.tracks[this.trackId]; // check if playlist is already loaded
  12534. if (track && track.details) {
  12535. this.state = State.IDLE;
  12536. }
  12537. break;
  12538. case State.FRAG_LOADING_WAITING_RETRY:
  12539. var now = audio_stream_controller_performance.now();
  12540. var retryDate = this.retryDate;
  12541. media = this.media;
  12542. var isSeeking = media && media.seeking; // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  12543. if (!retryDate || now >= retryDate || isSeeking) {
  12544. logger["logger"].log('audioStreamController: retryDate reached, switch back to IDLE state');
  12545. this.state = State.IDLE;
  12546. }
  12547. break;
  12548. case State.WAITING_INIT_PTS:
  12549. // Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS
  12550. var waitingFrag = this.waitingFragment;
  12551. if (waitingFrag) {
  12552. var waitingFragCC = waitingFrag.frag.cc;
  12553. if (this.initPTS[waitingFragCC] !== undefined) {
  12554. this.waitingFragment = null;
  12555. this.state = State.FRAG_LOADING;
  12556. this.onFragLoaded(waitingFrag);
  12557. } else if (this.videoTrackCC !== this.waitingVideoCC) {
  12558. // Drop waiting fragment if videoTrackCC has changed since waitingFragment was set and initPTS was not found
  12559. logger["logger"].log("Waiting fragment cc (" + waitingFragCC + ") cancelled because video is at cc " + this.videoTrackCC);
  12560. this.clearWaitingFragment();
  12561. } else {
  12562. // Drop waiting fragment if an earlier fragment is needed
  12563. var _bufferInfo = BufferHelper.bufferInfo(this.mediaBuffer, this.media.currentTime, config.maxBufferHole);
  12564. var waitingFragmentAtPosition = fragmentWithinToleranceTest(_bufferInfo.end, config.maxFragLookUpTolerance, waitingFrag.frag);
  12565. if (waitingFragmentAtPosition < 0) {
  12566. logger["logger"].log("Waiting fragment cc (" + waitingFragCC + ") @ " + waitingFrag.frag.start + " cancelled because another fragment at " + _bufferInfo.end + " is needed");
  12567. this.clearWaitingFragment();
  12568. }
  12569. }
  12570. } else {
  12571. this.state = State.IDLE;
  12572. }
  12573. break;
  12574. case State.STOPPED:
  12575. case State.FRAG_LOADING:
  12576. case State.PARSING:
  12577. case State.PARSED:
  12578. case State.ENDED:
  12579. break;
  12580. default:
  12581. break;
  12582. }
  12583. };
  12584. _proto.clearWaitingFragment = function clearWaitingFragment() {
  12585. var waitingFrag = this.waitingFragment;
  12586. if (waitingFrag) {
  12587. this.fragmentTracker.removeFragment(waitingFrag.frag);
  12588. this.waitingFragment = null;
  12589. this.waitingVideoCC = null;
  12590. this.state = State.IDLE;
  12591. }
  12592. };
  12593. _proto.onMediaAttached = function onMediaAttached(data) {
  12594. var media = this.media = this.mediaBuffer = data.media;
  12595. this.onvseeking = this.onMediaSeeking.bind(this);
  12596. this.onvended = this.onMediaEnded.bind(this);
  12597. media.addEventListener('seeking', this.onvseeking);
  12598. media.addEventListener('ended', this.onvended);
  12599. var config = this.config;
  12600. if (this.tracks && config.autoStartLoad) {
  12601. this.startLoad(config.startPosition);
  12602. }
  12603. };
  12604. _proto.onMediaDetaching = function onMediaDetaching() {
  12605. var media = this.media;
  12606. if (media && media.ended) {
  12607. logger["logger"].log('MSE detaching and video ended, reset startPosition');
  12608. this.startPosition = this.lastCurrentTime = 0;
  12609. } // remove video listeners
  12610. if (media) {
  12611. media.removeEventListener('seeking', this.onvseeking);
  12612. media.removeEventListener('ended', this.onvended);
  12613. this.onvseeking = this.onvseeked = this.onvended = null;
  12614. }
  12615. this.media = this.mediaBuffer = this.videoBuffer = null;
  12616. this.loadedmetadata = false;
  12617. this.fragmentTracker.removeAllFragments();
  12618. this.stopLoad();
  12619. };
  12620. _proto.onAudioTracksUpdated = function onAudioTracksUpdated(data) {
  12621. logger["logger"].log('audio tracks updated');
  12622. this.tracks = data.audioTracks;
  12623. };
  12624. _proto.onAudioTrackSwitching = function onAudioTrackSwitching(data) {
  12625. // if any URL found on new audio track, it is an alternate audio track
  12626. var altAudio = !!data.url;
  12627. this.trackId = data.id;
  12628. this.fragCurrent = null;
  12629. this.clearWaitingFragment();
  12630. this.state = State.PAUSED; // destroy useless demuxer when switching audio to main
  12631. if (!altAudio) {
  12632. if (this.demuxer) {
  12633. this.demuxer.destroy();
  12634. this.demuxer = null;
  12635. }
  12636. } else {
  12637. // switching to audio track, start timer if not already started
  12638. this.setInterval(audio_stream_controller_TICK_INTERVAL);
  12639. } // should we switch tracks ?
  12640. if (altAudio) {
  12641. this.audioSwitch = true; // main audio track are handled by stream-controller, just do something if switching to alt audio track
  12642. this.state = State.IDLE;
  12643. }
  12644. this.tick();
  12645. };
  12646. _proto.onAudioTrackLoaded = function onAudioTrackLoaded(data) {
  12647. var newDetails = data.details,
  12648. trackId = data.id,
  12649. track = this.tracks[trackId],
  12650. curDetails = track.details,
  12651. duration = newDetails.totalduration,
  12652. sliding = 0;
  12653. logger["logger"].log("track " + trackId + " loaded [" + newDetails.startSN + "," + newDetails.endSN + "],duration:" + duration);
  12654. if (newDetails.live || curDetails && curDetails.live) {
  12655. if (curDetails && newDetails.fragments.length > 0) {
  12656. // we already have details for that level, merge them
  12657. mergeDetails(curDetails, newDetails);
  12658. sliding = newDetails.fragments[0].start; // TODO
  12659. // this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);
  12660. if (newDetails.PTSKnown) {
  12661. logger["logger"].log("live audio playlist sliding:" + sliding.toFixed(3));
  12662. } else {
  12663. logger["logger"].log('live audio playlist - outdated PTS, unknown sliding');
  12664. }
  12665. } else {
  12666. newDetails.PTSKnown = false;
  12667. logger["logger"].log('live audio playlist - first load, unknown sliding');
  12668. }
  12669. } else {
  12670. newDetails.PTSKnown = false;
  12671. }
  12672. track.details = newDetails; // compute start position
  12673. if (!this.startFragRequested) {
  12674. // compute start position if set to -1. use it straight away if value is defined
  12675. if (this.startPosition === -1) {
  12676. // first, check if start time offset has been set in playlist, if yes, use this value
  12677. var startTimeOffset = newDetails.startTimeOffset;
  12678. if (Object(number["isFiniteNumber"])(startTimeOffset)) {
  12679. logger["logger"].log("start time offset found in playlist, adjust startPosition to " + startTimeOffset);
  12680. this.startPosition = startTimeOffset;
  12681. } else {
  12682. if (newDetails.live) {
  12683. this.startPosition = this.computeLivePosition(sliding, newDetails);
  12684. logger["logger"].log("compute startPosition for audio-track to " + this.startPosition);
  12685. } else {
  12686. this.startPosition = 0;
  12687. }
  12688. }
  12689. }
  12690. this.nextLoadPosition = this.startPosition;
  12691. } // only switch batck to IDLE state if we were waiting for track to start downloading a new fragment
  12692. if (this.state === State.WAITING_TRACK) {
  12693. this.state = State.IDLE;
  12694. } // trigger handler right now
  12695. this.tick();
  12696. };
  12697. _proto.onKeyLoaded = function onKeyLoaded() {
  12698. if (this.state === State.KEY_LOADING) {
  12699. this.state = State.IDLE;
  12700. this.tick();
  12701. }
  12702. };
  12703. _proto.onFragLoaded = function onFragLoaded(data) {
  12704. var fragCurrent = this.fragCurrent,
  12705. fragLoaded = data.frag;
  12706. if (this.state === State.FRAG_LOADING && fragCurrent && fragLoaded.type === 'audio' && fragLoaded.level === fragCurrent.level && fragLoaded.sn === fragCurrent.sn) {
  12707. var track = this.tracks[this.trackId],
  12708. details = track.details,
  12709. duration = details.totalduration,
  12710. trackId = fragCurrent.level,
  12711. sn = fragCurrent.sn,
  12712. cc = fragCurrent.cc,
  12713. audioCodec = this.config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2',
  12714. stats = this.stats = data.stats;
  12715. if (sn === 'initSegment') {
  12716. this.state = State.IDLE;
  12717. stats.tparsed = stats.tbuffered = audio_stream_controller_performance.now();
  12718. details.initSegment.data = data.payload;
  12719. this.hls.trigger(events["default"].FRAG_BUFFERED, {
  12720. stats: stats,
  12721. frag: fragCurrent,
  12722. id: 'audio'
  12723. });
  12724. this.tick();
  12725. } else {
  12726. this.state = State.PARSING; // transmux the MPEG-TS data to ISO-BMFF segments
  12727. this.appended = false;
  12728. if (!this.demuxer) {
  12729. this.demuxer = new demux_demuxer(this.hls, 'audio');
  12730. } // Check if we have video initPTS
  12731. // If not we need to wait for it
  12732. var initPTS = this.initPTS[cc];
  12733. var initSegmentData = details.initSegment ? details.initSegment.data : [];
  12734. if (initPTS !== undefined) {
  12735. this.pendingBuffering = true;
  12736. logger["logger"].log("Demuxing " + sn + " of [" + details.startSN + " ," + details.endSN + "],track " + trackId); // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
  12737. var accurateTimeOffset = false; // details.PTSKnown || !details.live;
  12738. this.demuxer.push(data.payload, initSegmentData, audioCodec, null, fragCurrent, duration, accurateTimeOffset, initPTS);
  12739. } else {
  12740. logger["logger"].log("Unknown video PTS for cc " + cc + ", waiting for video PTS before demuxing audio frag " + sn + " of [" + details.startSN + " ," + details.endSN + "],track " + trackId);
  12741. this.waitingFragment = data;
  12742. this.waitingVideoCC = this.videoTrackCC;
  12743. this.state = State.WAITING_INIT_PTS;
  12744. }
  12745. }
  12746. }
  12747. this.fragLoadError = 0;
  12748. };
  12749. _proto.onFragParsingInitSegment = function onFragParsingInitSegment(data) {
  12750. var fragCurrent = this.fragCurrent;
  12751. var fragNew = data.frag;
  12752. if (fragCurrent && data.id === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {
  12753. var tracks = data.tracks,
  12754. track; // delete any video track found on audio demuxer
  12755. if (tracks.video) {
  12756. delete tracks.video;
  12757. } // include levelCodec in audio and video tracks
  12758. track = tracks.audio;
  12759. if (track) {
  12760. track.levelCodec = track.codec;
  12761. track.id = data.id;
  12762. this.hls.trigger(events["default"].BUFFER_CODECS, tracks);
  12763. logger["logger"].log("audio track:audio,container:" + track.container + ",codecs[level/parsed]=[" + track.levelCodec + "/" + track.codec + "]");
  12764. var initSegment = track.initSegment;
  12765. if (initSegment) {
  12766. var appendObj = {
  12767. type: 'audio',
  12768. data: initSegment,
  12769. parent: 'audio',
  12770. content: 'initSegment'
  12771. };
  12772. if (this.audioSwitch) {
  12773. this.pendingData = [appendObj];
  12774. } else {
  12775. this.appended = true; // arm pending Buffering flag before appending a segment
  12776. this.pendingBuffering = true;
  12777. this.hls.trigger(events["default"].BUFFER_APPENDING, appendObj);
  12778. }
  12779. } // trigger handler right now
  12780. this.tick();
  12781. }
  12782. }
  12783. };
  12784. _proto.onFragParsingData = function onFragParsingData(data) {
  12785. var _this2 = this;
  12786. var fragCurrent = this.fragCurrent;
  12787. var fragNew = data.frag;
  12788. if (fragCurrent && data.id === 'audio' && data.type === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {
  12789. var trackId = this.trackId,
  12790. track = this.tracks[trackId],
  12791. hls = this.hls;
  12792. if (!Object(number["isFiniteNumber"])(data.endPTS)) {
  12793. data.endPTS = data.startPTS + fragCurrent.duration;
  12794. data.endDTS = data.startDTS + fragCurrent.duration;
  12795. }
  12796. fragCurrent.addElementaryStream(ElementaryStreamTypes.AUDIO);
  12797. logger["logger"].log("parsed " + data.type + ",PTS:[" + data.startPTS.toFixed(3) + "," + data.endPTS.toFixed(3) + "],DTS:[" + data.startDTS.toFixed(3) + "/" + data.endDTS.toFixed(3) + "],nb:" + data.nb);
  12798. updateFragPTSDTS(track.details, fragCurrent, data.startPTS, data.endPTS);
  12799. var media = this.media;
  12800. var appendOnBufferFlush = false; // Only flush audio from old audio tracks when PTS is known on new audio track
  12801. if (this.audioSwitch) {
  12802. if (media && media.readyState) {
  12803. var currentTime = media.currentTime;
  12804. logger["logger"].log('switching audio track : currentTime:' + currentTime);
  12805. if (currentTime >= data.startPTS) {
  12806. logger["logger"].log('switching audio track : flushing all audio');
  12807. this.state = State.BUFFER_FLUSHING;
  12808. hls.trigger(events["default"].BUFFER_FLUSHING, {
  12809. startOffset: 0,
  12810. endOffset: Number.POSITIVE_INFINITY,
  12811. type: 'audio'
  12812. });
  12813. appendOnBufferFlush = true; // Lets announce that the initial audio track switch flush occur
  12814. this.audioSwitch = false;
  12815. hls.trigger(events["default"].AUDIO_TRACK_SWITCHED, {
  12816. id: trackId
  12817. });
  12818. }
  12819. } else {
  12820. // Lets announce that the initial audio track switch flush occur
  12821. this.audioSwitch = false;
  12822. hls.trigger(events["default"].AUDIO_TRACK_SWITCHED, {
  12823. id: trackId
  12824. });
  12825. }
  12826. }
  12827. var pendingData = this.pendingData;
  12828. if (!pendingData) {
  12829. logger["logger"].warn('Apparently attempt to enqueue media payload without codec initialization data upfront');
  12830. hls.trigger(events["default"].ERROR, {
  12831. type: errors["ErrorTypes"].MEDIA_ERROR,
  12832. details: null,
  12833. fatal: true
  12834. });
  12835. return;
  12836. }
  12837. if (!this.audioSwitch) {
  12838. [data.data1, data.data2].forEach(function (buffer) {
  12839. if (buffer && buffer.length) {
  12840. pendingData.push({
  12841. type: data.type,
  12842. data: buffer,
  12843. parent: 'audio',
  12844. content: 'data'
  12845. });
  12846. }
  12847. });
  12848. if (!appendOnBufferFlush && pendingData.length) {
  12849. pendingData.forEach(function (appendObj) {
  12850. // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)
  12851. // in that case it is useless to append following segments
  12852. if (_this2.state === State.PARSING) {
  12853. // arm pending Buffering flag before appending a segment
  12854. _this2.pendingBuffering = true;
  12855. _this2.hls.trigger(events["default"].BUFFER_APPENDING, appendObj);
  12856. }
  12857. });
  12858. this.pendingData = [];
  12859. this.appended = true;
  12860. }
  12861. } // trigger handler right now
  12862. this.tick();
  12863. }
  12864. };
  12865. _proto.onFragParsed = function onFragParsed(data) {
  12866. var fragCurrent = this.fragCurrent;
  12867. var fragNew = data.frag;
  12868. if (fragCurrent && data.id === 'audio' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {
  12869. this.stats.tparsed = audio_stream_controller_performance.now();
  12870. this.state = State.PARSED;
  12871. this._checkAppendedParsed();
  12872. }
  12873. };
  12874. _proto.onBufferReset = function onBufferReset() {
  12875. // reset reference to sourcebuffers
  12876. this.mediaBuffer = this.videoBuffer = null;
  12877. this.loadedmetadata = false;
  12878. };
  12879. _proto.onBufferCreated = function onBufferCreated(data) {
  12880. var audioTrack = data.tracks.audio;
  12881. if (audioTrack) {
  12882. this.mediaBuffer = audioTrack.buffer;
  12883. this.loadedmetadata = true;
  12884. }
  12885. if (data.tracks.video) {
  12886. this.videoBuffer = data.tracks.video.buffer;
  12887. }
  12888. };
  12889. _proto.onBufferAppended = function onBufferAppended(data) {
  12890. if (data.parent === 'audio') {
  12891. var state = this.state;
  12892. if (state === State.PARSING || state === State.PARSED) {
  12893. // check if all buffers have been appended
  12894. this.pendingBuffering = data.pending > 0;
  12895. this._checkAppendedParsed();
  12896. }
  12897. }
  12898. };
  12899. _proto._checkAppendedParsed = function _checkAppendedParsed() {
  12900. // trigger handler right now
  12901. if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) {
  12902. var frag = this.fragCurrent,
  12903. stats = this.stats,
  12904. hls = this.hls;
  12905. if (frag) {
  12906. this.fragPrevious = frag;
  12907. stats.tbuffered = audio_stream_controller_performance.now();
  12908. hls.trigger(events["default"].FRAG_BUFFERED, {
  12909. stats: stats,
  12910. frag: frag,
  12911. id: 'audio'
  12912. });
  12913. var media = this.mediaBuffer ? this.mediaBuffer : this.media;
  12914. if (media) {
  12915. logger["logger"].log("audio buffered : " + time_ranges.toString(media.buffered));
  12916. }
  12917. if (this.audioSwitch && this.appended) {
  12918. this.audioSwitch = false;
  12919. hls.trigger(events["default"].AUDIO_TRACK_SWITCHED, {
  12920. id: this.trackId
  12921. });
  12922. }
  12923. this.state = State.IDLE;
  12924. }
  12925. this.tick();
  12926. }
  12927. };
  12928. _proto.onError = function onError(data) {
  12929. var frag = data.frag; // don't handle frag error not related to audio fragment
  12930. if (frag && frag.type !== 'audio') {
  12931. return;
  12932. }
  12933. switch (data.details) {
  12934. case errors["ErrorDetails"].FRAG_LOAD_ERROR:
  12935. case errors["ErrorDetails"].FRAG_LOAD_TIMEOUT:
  12936. var _frag = data.frag; // don't handle frag error not related to audio fragment
  12937. if (_frag && _frag.type !== 'audio') {
  12938. break;
  12939. }
  12940. if (!data.fatal) {
  12941. var loadError = this.fragLoadError;
  12942. if (loadError) {
  12943. loadError++;
  12944. } else {
  12945. loadError = 1;
  12946. }
  12947. var config = this.config;
  12948. if (loadError <= config.fragLoadingMaxRetry) {
  12949. this.fragLoadError = loadError; // exponential backoff capped to config.fragLoadingMaxRetryTimeout
  12950. var delay = Math.min(Math.pow(2, loadError - 1) * config.fragLoadingRetryDelay, config.fragLoadingMaxRetryTimeout);
  12951. logger["logger"].warn("AudioStreamController: frag loading failed, retry in " + delay + " ms");
  12952. this.retryDate = audio_stream_controller_performance.now() + delay; // retry loading state
  12953. this.state = State.FRAG_LOADING_WAITING_RETRY;
  12954. } else {
  12955. logger["logger"].error("AudioStreamController: " + data.details + " reaches max retry, redispatch as fatal ..."); // switch error to fatal
  12956. data.fatal = true;
  12957. this.state = State.ERROR;
  12958. }
  12959. }
  12960. break;
  12961. case errors["ErrorDetails"].AUDIO_TRACK_LOAD_ERROR:
  12962. case errors["ErrorDetails"].AUDIO_TRACK_LOAD_TIMEOUT:
  12963. case errors["ErrorDetails"].KEY_LOAD_ERROR:
  12964. case errors["ErrorDetails"].KEY_LOAD_TIMEOUT:
  12965. // when in ERROR state, don't switch back to IDLE state in case a non-fatal error is received
  12966. if (this.state !== State.ERROR) {
  12967. // if fatal error, stop processing, otherwise move to IDLE to retry loading
  12968. this.state = data.fatal ? State.ERROR : State.IDLE;
  12969. logger["logger"].warn("AudioStreamController: " + data.details + " while loading frag, now switching to " + this.state + " state ...");
  12970. }
  12971. break;
  12972. case errors["ErrorDetails"].BUFFER_FULL_ERROR:
  12973. // if in appending state
  12974. if (data.parent === 'audio' && (this.state === State.PARSING || this.state === State.PARSED)) {
  12975. var media = this.mediaBuffer,
  12976. currentTime = this.media.currentTime,
  12977. mediaBuffered = media && BufferHelper.isBuffered(media, currentTime) && BufferHelper.isBuffered(media, currentTime + 0.5); // reduce max buf len if current position is buffered
  12978. if (mediaBuffered) {
  12979. var _config = this.config;
  12980. if (_config.maxMaxBufferLength >= _config.maxBufferLength) {
  12981. // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
  12982. _config.maxMaxBufferLength /= 2;
  12983. logger["logger"].warn("AudioStreamController: reduce max buffer length to " + _config.maxMaxBufferLength + "s");
  12984. }
  12985. this.state = State.IDLE;
  12986. } else {
  12987. // current position is not buffered, but browser is still complaining about buffer full error
  12988. // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
  12989. // in that case flush the whole audio buffer to recover
  12990. logger["logger"].warn('AudioStreamController: buffer full error also media.currentTime is not buffered, flush audio buffer');
  12991. this.fragCurrent = null; // flush everything
  12992. this.state = State.BUFFER_FLUSHING;
  12993. this.hls.trigger(events["default"].BUFFER_FLUSHING, {
  12994. startOffset: 0,
  12995. endOffset: Number.POSITIVE_INFINITY,
  12996. type: 'audio'
  12997. });
  12998. }
  12999. }
  13000. break;
  13001. default:
  13002. break;
  13003. }
  13004. };
  13005. _proto.onBufferFlushed = function onBufferFlushed() {
  13006. var _this3 = this;
  13007. var pendingData = this.pendingData;
  13008. if (pendingData && pendingData.length) {
  13009. logger["logger"].log('AudioStreamController: appending pending audio data after buffer flushed');
  13010. pendingData.forEach(function (appendObj) {
  13011. _this3.hls.trigger(events["default"].BUFFER_APPENDING, appendObj);
  13012. });
  13013. this.appended = true;
  13014. this.pendingData = [];
  13015. this.state = State.PARSED;
  13016. } else {
  13017. // move to IDLE once flush complete. this should trigger new fragment loading
  13018. this.state = State.IDLE; // reset reference to frag
  13019. this.fragPrevious = null;
  13020. this.tick();
  13021. }
  13022. };
  13023. audio_stream_controller_createClass(AudioStreamController, [{
  13024. key: "state",
  13025. set: function set(nextState) {
  13026. if (this.state !== nextState) {
  13027. var previousState = this.state;
  13028. this._state = nextState;
  13029. logger["logger"].log("audio stream:" + previousState + "->" + nextState);
  13030. }
  13031. },
  13032. get: function get() {
  13033. return this._state;
  13034. }
  13035. }]);
  13036. return AudioStreamController;
  13037. }(base_stream_controller_BaseStreamController);
  13038. /* harmony default export */ var audio_stream_controller = (audio_stream_controller_AudioStreamController);
  13039. // CONCATENATED MODULE: ./src/utils/vttcue.js
  13040. /**
  13041. * Copyright 2013 vtt.js Contributors
  13042. *
  13043. * Licensed under the Apache License, Version 2.0 (the "License");
  13044. * you may not use this file except in compliance with the License.
  13045. * You may obtain a copy of the License at
  13046. *
  13047. * http://www.apache.org/licenses/LICENSE-2.0
  13048. *
  13049. * Unless required by applicable law or agreed to in writing, software
  13050. * distributed under the License is distributed on an "AS IS" BASIS,
  13051. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13052. * See the License for the specific language governing permissions and
  13053. * limitations under the License.
  13054. */
  13055. /* harmony default export */ var vttcue = ((function () {
  13056. if (typeof window !== 'undefined' && window.VTTCue) {
  13057. return window.VTTCue;
  13058. }
  13059. var autoKeyword = 'auto';
  13060. var directionSetting = {
  13061. '': true,
  13062. lr: true,
  13063. rl: true
  13064. };
  13065. var alignSetting = {
  13066. start: true,
  13067. middle: true,
  13068. end: true,
  13069. left: true,
  13070. right: true
  13071. };
  13072. function findDirectionSetting(value) {
  13073. if (typeof value !== 'string') {
  13074. return false;
  13075. }
  13076. var dir = directionSetting[value.toLowerCase()];
  13077. return dir ? value.toLowerCase() : false;
  13078. }
  13079. function findAlignSetting(value) {
  13080. if (typeof value !== 'string') {
  13081. return false;
  13082. }
  13083. var align = alignSetting[value.toLowerCase()];
  13084. return align ? value.toLowerCase() : false;
  13085. }
  13086. function extend(obj) {
  13087. var i = 1;
  13088. for (; i < arguments.length; i++) {
  13089. var cobj = arguments[i];
  13090. for (var p in cobj) {
  13091. obj[p] = cobj[p];
  13092. }
  13093. }
  13094. return obj;
  13095. }
  13096. function VTTCue(startTime, endTime, text) {
  13097. var cue = this;
  13098. var baseObj = {};
  13099. baseObj.enumerable = true;
  13100. /**
  13101. * Shim implementation specific properties. These properties are not in
  13102. * the spec.
  13103. */
  13104. // Lets us know when the VTTCue's data has changed in such a way that we need
  13105. // to recompute its display state. This lets us compute its display state
  13106. // lazily.
  13107. cue.hasBeenReset = false;
  13108. /**
  13109. * VTTCue and TextTrackCue properties
  13110. * http://dev.w3.org/html5/webvtt/#vttcue-interface
  13111. */
  13112. var _id = '';
  13113. var _pauseOnExit = false;
  13114. var _startTime = startTime;
  13115. var _endTime = endTime;
  13116. var _text = text;
  13117. var _region = null;
  13118. var _vertical = '';
  13119. var _snapToLines = true;
  13120. var _line = 'auto';
  13121. var _lineAlign = 'start';
  13122. var _position = 50;
  13123. var _positionAlign = 'middle';
  13124. var _size = 50;
  13125. var _align = 'middle';
  13126. Object.defineProperty(cue, 'id', extend({}, baseObj, {
  13127. get: function get() {
  13128. return _id;
  13129. },
  13130. set: function set(value) {
  13131. _id = '' + value;
  13132. }
  13133. }));
  13134. Object.defineProperty(cue, 'pauseOnExit', extend({}, baseObj, {
  13135. get: function get() {
  13136. return _pauseOnExit;
  13137. },
  13138. set: function set(value) {
  13139. _pauseOnExit = !!value;
  13140. }
  13141. }));
  13142. Object.defineProperty(cue, 'startTime', extend({}, baseObj, {
  13143. get: function get() {
  13144. return _startTime;
  13145. },
  13146. set: function set(value) {
  13147. if (typeof value !== 'number') {
  13148. throw new TypeError('Start time must be set to a number.');
  13149. }
  13150. _startTime = value;
  13151. this.hasBeenReset = true;
  13152. }
  13153. }));
  13154. Object.defineProperty(cue, 'endTime', extend({}, baseObj, {
  13155. get: function get() {
  13156. return _endTime;
  13157. },
  13158. set: function set(value) {
  13159. if (typeof value !== 'number') {
  13160. throw new TypeError('End time must be set to a number.');
  13161. }
  13162. _endTime = value;
  13163. this.hasBeenReset = true;
  13164. }
  13165. }));
  13166. Object.defineProperty(cue, 'text', extend({}, baseObj, {
  13167. get: function get() {
  13168. return _text;
  13169. },
  13170. set: function set(value) {
  13171. _text = '' + value;
  13172. this.hasBeenReset = true;
  13173. }
  13174. }));
  13175. Object.defineProperty(cue, 'region', extend({}, baseObj, {
  13176. get: function get() {
  13177. return _region;
  13178. },
  13179. set: function set(value) {
  13180. _region = value;
  13181. this.hasBeenReset = true;
  13182. }
  13183. }));
  13184. Object.defineProperty(cue, 'vertical', extend({}, baseObj, {
  13185. get: function get() {
  13186. return _vertical;
  13187. },
  13188. set: function set(value) {
  13189. var setting = findDirectionSetting(value); // Have to check for false because the setting an be an empty string.
  13190. if (setting === false) {
  13191. throw new SyntaxError('An invalid or illegal string was specified.');
  13192. }
  13193. _vertical = setting;
  13194. this.hasBeenReset = true;
  13195. }
  13196. }));
  13197. Object.defineProperty(cue, 'snapToLines', extend({}, baseObj, {
  13198. get: function get() {
  13199. return _snapToLines;
  13200. },
  13201. set: function set(value) {
  13202. _snapToLines = !!value;
  13203. this.hasBeenReset = true;
  13204. }
  13205. }));
  13206. Object.defineProperty(cue, 'line', extend({}, baseObj, {
  13207. get: function get() {
  13208. return _line;
  13209. },
  13210. set: function set(value) {
  13211. if (typeof value !== 'number' && value !== autoKeyword) {
  13212. throw new SyntaxError('An invalid number or illegal string was specified.');
  13213. }
  13214. _line = value;
  13215. this.hasBeenReset = true;
  13216. }
  13217. }));
  13218. Object.defineProperty(cue, 'lineAlign', extend({}, baseObj, {
  13219. get: function get() {
  13220. return _lineAlign;
  13221. },
  13222. set: function set(value) {
  13223. var setting = findAlignSetting(value);
  13224. if (!setting) {
  13225. throw new SyntaxError('An invalid or illegal string was specified.');
  13226. }
  13227. _lineAlign = setting;
  13228. this.hasBeenReset = true;
  13229. }
  13230. }));
  13231. Object.defineProperty(cue, 'position', extend({}, baseObj, {
  13232. get: function get() {
  13233. return _position;
  13234. },
  13235. set: function set(value) {
  13236. if (value < 0 || value > 100) {
  13237. throw new Error('Position must be between 0 and 100.');
  13238. }
  13239. _position = value;
  13240. this.hasBeenReset = true;
  13241. }
  13242. }));
  13243. Object.defineProperty(cue, 'positionAlign', extend({}, baseObj, {
  13244. get: function get() {
  13245. return _positionAlign;
  13246. },
  13247. set: function set(value) {
  13248. var setting = findAlignSetting(value);
  13249. if (!setting) {
  13250. throw new SyntaxError('An invalid or illegal string was specified.');
  13251. }
  13252. _positionAlign = setting;
  13253. this.hasBeenReset = true;
  13254. }
  13255. }));
  13256. Object.defineProperty(cue, 'size', extend({}, baseObj, {
  13257. get: function get() {
  13258. return _size;
  13259. },
  13260. set: function set(value) {
  13261. if (value < 0 || value > 100) {
  13262. throw new Error('Size must be between 0 and 100.');
  13263. }
  13264. _size = value;
  13265. this.hasBeenReset = true;
  13266. }
  13267. }));
  13268. Object.defineProperty(cue, 'align', extend({}, baseObj, {
  13269. get: function get() {
  13270. return _align;
  13271. },
  13272. set: function set(value) {
  13273. var setting = findAlignSetting(value);
  13274. if (!setting) {
  13275. throw new SyntaxError('An invalid or illegal string was specified.');
  13276. }
  13277. _align = setting;
  13278. this.hasBeenReset = true;
  13279. }
  13280. }));
  13281. /**
  13282. * Other <track> spec defined properties
  13283. */
  13284. // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state
  13285. cue.displayState = void 0;
  13286. }
  13287. /**
  13288. * VTTCue methods
  13289. */
  13290. VTTCue.prototype.getCueAsHTML = function () {
  13291. // Assume WebVTT.convertCueToDOMTree is on the global.
  13292. var WebVTT = window.WebVTT;
  13293. return WebVTT.convertCueToDOMTree(window, this.text);
  13294. };
  13295. return VTTCue;
  13296. })());
  13297. // CONCATENATED MODULE: ./src/utils/vttparser.js
  13298. /*
  13299. * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js#L1716
  13300. */
  13301. var StringDecoder = function StringDecoder() {
  13302. return {
  13303. decode: function decode(data) {
  13304. if (!data) {
  13305. return '';
  13306. }
  13307. if (typeof data !== 'string') {
  13308. throw new Error('Error - expected string data.');
  13309. }
  13310. return decodeURIComponent(encodeURIComponent(data));
  13311. }
  13312. };
  13313. };
  13314. function VTTParser() {
  13315. this.window = window;
  13316. this.state = 'INITIAL';
  13317. this.buffer = '';
  13318. this.decoder = new StringDecoder();
  13319. this.regionList = [];
  13320. } // Try to parse input as a time stamp.
  13321. function parseTimeStamp(input) {
  13322. function computeSeconds(h, m, s, f) {
  13323. return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000;
  13324. }
  13325. var m = input.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/);
  13326. if (!m) {
  13327. return null;
  13328. }
  13329. if (m[3]) {
  13330. // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds]
  13331. return computeSeconds(m[1], m[2], m[3].replace(':', ''), m[4]);
  13332. } else if (m[1] > 59) {
  13333. // Timestamp takes the form of [hours]:[minutes].[milliseconds]
  13334. // First position is hours as it's over 59.
  13335. return computeSeconds(m[1], m[2], 0, m[4]);
  13336. } else {
  13337. // Timestamp takes the form of [minutes]:[seconds].[milliseconds]
  13338. return computeSeconds(0, m[1], m[2], m[4]);
  13339. }
  13340. } // A settings object holds key/value pairs and will ignore anything but the first
  13341. // assignment to a specific key.
  13342. function Settings() {
  13343. this.values = Object.create(null);
  13344. }
  13345. Settings.prototype = {
  13346. // Only accept the first assignment to any key.
  13347. set: function set(k, v) {
  13348. if (!this.get(k) && v !== '') {
  13349. this.values[k] = v;
  13350. }
  13351. },
  13352. // Return the value for a key, or a default value.
  13353. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with
  13354. // a number of possible default values as properties where 'defaultKey' is
  13355. // the key of the property that will be chosen; otherwise it's assumed to be
  13356. // a single value.
  13357. get: function get(k, dflt, defaultKey) {
  13358. if (defaultKey) {
  13359. return this.has(k) ? this.values[k] : dflt[defaultKey];
  13360. }
  13361. return this.has(k) ? this.values[k] : dflt;
  13362. },
  13363. // Check whether we have a value for a key.
  13364. has: function has(k) {
  13365. return k in this.values;
  13366. },
  13367. // Accept a setting if its one of the given alternatives.
  13368. alt: function alt(k, v, a) {
  13369. for (var n = 0; n < a.length; ++n) {
  13370. if (v === a[n]) {
  13371. this.set(k, v);
  13372. break;
  13373. }
  13374. }
  13375. },
  13376. // Accept a setting if its a valid (signed) integer.
  13377. integer: function integer(k, v) {
  13378. if (/^-?\d+$/.test(v)) {
  13379. // integer
  13380. this.set(k, parseInt(v, 10));
  13381. }
  13382. },
  13383. // Accept a setting if its a valid percentage.
  13384. percent: function percent(k, v) {
  13385. var m;
  13386. if (m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/)) {
  13387. v = parseFloat(v);
  13388. if (v >= 0 && v <= 100) {
  13389. this.set(k, v);
  13390. return true;
  13391. }
  13392. }
  13393. return false;
  13394. }
  13395. }; // Helper function to parse input into groups separated by 'groupDelim', and
  13396. // interprete each group as a key/value pair separated by 'keyValueDelim'.
  13397. function parseOptions(input, callback, keyValueDelim, groupDelim) {
  13398. var groups = groupDelim ? input.split(groupDelim) : [input];
  13399. for (var i in groups) {
  13400. if (typeof groups[i] !== 'string') {
  13401. continue;
  13402. }
  13403. var kv = groups[i].split(keyValueDelim);
  13404. if (kv.length !== 2) {
  13405. continue;
  13406. }
  13407. var k = kv[0];
  13408. var v = kv[1];
  13409. callback(k, v);
  13410. }
  13411. }
  13412. var defaults = new vttcue(0, 0, 0); // 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244
  13413. // Safari doesn't yet support this change, but FF and Chrome do.
  13414. var center = defaults.align === 'middle' ? 'middle' : 'center';
  13415. function parseCue(input, cue, regionList) {
  13416. // Remember the original input if we need to throw an error.
  13417. var oInput = input; // 4.1 WebVTT timestamp
  13418. function consumeTimeStamp() {
  13419. var ts = parseTimeStamp(input);
  13420. if (ts === null) {
  13421. throw new Error('Malformed timestamp: ' + oInput);
  13422. } // Remove time stamp from input.
  13423. input = input.replace(/^[^\sa-zA-Z-]+/, '');
  13424. return ts;
  13425. } // 4.4.2 WebVTT cue settings
  13426. function consumeCueSettings(input, cue) {
  13427. var settings = new Settings();
  13428. parseOptions(input, function (k, v) {
  13429. switch (k) {
  13430. case 'region':
  13431. // Find the last region we parsed with the same region id.
  13432. for (var i = regionList.length - 1; i >= 0; i--) {
  13433. if (regionList[i].id === v) {
  13434. settings.set(k, regionList[i].region);
  13435. break;
  13436. }
  13437. }
  13438. break;
  13439. case 'vertical':
  13440. settings.alt(k, v, ['rl', 'lr']);
  13441. break;
  13442. case 'line':
  13443. var vals = v.split(','),
  13444. vals0 = vals[0];
  13445. settings.integer(k, vals0);
  13446. if (settings.percent(k, vals0)) {
  13447. settings.set('snapToLines', false);
  13448. }
  13449. settings.alt(k, vals0, ['auto']);
  13450. if (vals.length === 2) {
  13451. settings.alt('lineAlign', vals[1], ['start', center, 'end']);
  13452. }
  13453. break;
  13454. case 'position':
  13455. vals = v.split(',');
  13456. settings.percent(k, vals[0]);
  13457. if (vals.length === 2) {
  13458. settings.alt('positionAlign', vals[1], ['start', center, 'end', 'line-left', 'line-right', 'auto']);
  13459. }
  13460. break;
  13461. case 'size':
  13462. settings.percent(k, v);
  13463. break;
  13464. case 'align':
  13465. settings.alt(k, v, ['start', center, 'end', 'left', 'right']);
  13466. break;
  13467. }
  13468. }, /:/, /\s/); // Apply default values for any missing fields.
  13469. cue.region = settings.get('region', null);
  13470. cue.vertical = settings.get('vertical', '');
  13471. var line = settings.get('line', 'auto');
  13472. if (line === 'auto' && defaults.line === -1) {
  13473. // set numeric line number for Safari
  13474. line = -1;
  13475. }
  13476. cue.line = line;
  13477. cue.lineAlign = settings.get('lineAlign', 'start');
  13478. cue.snapToLines = settings.get('snapToLines', true);
  13479. cue.size = settings.get('size', 100);
  13480. cue.align = settings.get('align', center);
  13481. var position = settings.get('position', 'auto');
  13482. if (position === 'auto' && defaults.position === 50) {
  13483. // set numeric position for Safari
  13484. position = cue.align === 'start' || cue.align === 'left' ? 0 : cue.align === 'end' || cue.align === 'right' ? 100 : 50;
  13485. }
  13486. cue.position = position;
  13487. }
  13488. function skipWhitespace() {
  13489. input = input.replace(/^\s+/, '');
  13490. } // 4.1 WebVTT cue timings.
  13491. skipWhitespace();
  13492. cue.startTime = consumeTimeStamp(); // (1) collect cue start time
  13493. skipWhitespace();
  13494. if (input.substr(0, 3) !== '-->') {
  13495. // (3) next characters must match '-->'
  13496. throw new Error('Malformed time stamp (time stamps must be separated by \'-->\'): ' + oInput);
  13497. }
  13498. input = input.substr(3);
  13499. skipWhitespace();
  13500. cue.endTime = consumeTimeStamp(); // (5) collect cue end time
  13501. // 4.1 WebVTT cue settings list.
  13502. skipWhitespace();
  13503. consumeCueSettings(input, cue);
  13504. }
  13505. function fixLineBreaks(input) {
  13506. return input.replace(/<br(?: \/)?>/gi, '\n');
  13507. }
  13508. VTTParser.prototype = {
  13509. parse: function parse(data) {
  13510. var self = this; // If there is no data then we won't decode it, but will just try to parse
  13511. // whatever is in buffer already. This may occur in circumstances, for
  13512. // example when flush() is called.
  13513. if (data) {
  13514. // Try to decode the data that we received.
  13515. self.buffer += self.decoder.decode(data, {
  13516. stream: true
  13517. });
  13518. }
  13519. function collectNextLine() {
  13520. var buffer = self.buffer;
  13521. var pos = 0;
  13522. buffer = fixLineBreaks(buffer);
  13523. while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') {
  13524. ++pos;
  13525. }
  13526. var line = buffer.substr(0, pos); // Advance the buffer early in case we fail below.
  13527. if (buffer[pos] === '\r') {
  13528. ++pos;
  13529. }
  13530. if (buffer[pos] === '\n') {
  13531. ++pos;
  13532. }
  13533. self.buffer = buffer.substr(pos);
  13534. return line;
  13535. } // 3.2 WebVTT metadata header syntax
  13536. function parseHeader(input) {
  13537. parseOptions(input, function (k, v) {
  13538. switch (k) {
  13539. case 'Region':
  13540. // 3.3 WebVTT region metadata header syntax
  13541. // console.log('parse region', v);
  13542. // parseRegion(v);
  13543. break;
  13544. }
  13545. }, /:/);
  13546. } // 5.1 WebVTT file parsing.
  13547. try {
  13548. var line;
  13549. if (self.state === 'INITIAL') {
  13550. // We can't start parsing until we have the first line.
  13551. if (!/\r\n|\n/.test(self.buffer)) {
  13552. return this;
  13553. }
  13554. line = collectNextLine(); // strip of UTF-8 BOM if any
  13555. // https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8
  13556. var m = line.match(/^()?WEBVTT([ \t].*)?$/);
  13557. if (!m || !m[0]) {
  13558. throw new Error('Malformed WebVTT signature.');
  13559. }
  13560. self.state = 'HEADER';
  13561. }
  13562. var alreadyCollectedLine = false;
  13563. while (self.buffer) {
  13564. // We can't parse a line until we have the full line.
  13565. if (!/\r\n|\n/.test(self.buffer)) {
  13566. return this;
  13567. }
  13568. if (!alreadyCollectedLine) {
  13569. line = collectNextLine();
  13570. } else {
  13571. alreadyCollectedLine = false;
  13572. }
  13573. switch (self.state) {
  13574. case 'HEADER':
  13575. // 13-18 - Allow a header (metadata) under the WEBVTT line.
  13576. if (/:/.test(line)) {
  13577. parseHeader(line);
  13578. } else if (!line) {
  13579. // An empty line terminates the header and starts the body (cues).
  13580. self.state = 'ID';
  13581. }
  13582. continue;
  13583. case 'NOTE':
  13584. // Ignore NOTE blocks.
  13585. if (!line) {
  13586. self.state = 'ID';
  13587. }
  13588. continue;
  13589. case 'ID':
  13590. // Check for the start of NOTE blocks.
  13591. if (/^NOTE($|[ \t])/.test(line)) {
  13592. self.state = 'NOTE';
  13593. break;
  13594. } // 19-29 - Allow any number of line terminators, then initialize new cue values.
  13595. if (!line) {
  13596. continue;
  13597. }
  13598. self.cue = new vttcue(0, 0, '');
  13599. self.state = 'CUE'; // 30-39 - Check if self line contains an optional identifier or timing data.
  13600. if (line.indexOf('-->') === -1) {
  13601. self.cue.id = line;
  13602. continue;
  13603. }
  13604. // Process line as start of a cue.
  13605. /* falls through */
  13606. case 'CUE':
  13607. // 40 - Collect cue timings and settings.
  13608. try {
  13609. parseCue(line, self.cue, self.regionList);
  13610. } catch (e) {
  13611. // In case of an error ignore rest of the cue.
  13612. self.cue = null;
  13613. self.state = 'BADCUE';
  13614. continue;
  13615. }
  13616. self.state = 'CUETEXT';
  13617. continue;
  13618. case 'CUETEXT':
  13619. var hasSubstring = line.indexOf('-->') !== -1; // 34 - If we have an empty line then report the cue.
  13620. // 35 - If we have the special substring '-->' then report the cue,
  13621. // but do not collect the line as we need to process the current
  13622. // one as a new cue.
  13623. if (!line || hasSubstring && (alreadyCollectedLine = true)) {
  13624. // We are done parsing self cue.
  13625. if (self.oncue) {
  13626. self.oncue(self.cue);
  13627. }
  13628. self.cue = null;
  13629. self.state = 'ID';
  13630. continue;
  13631. }
  13632. if (self.cue.text) {
  13633. self.cue.text += '\n';
  13634. }
  13635. self.cue.text += line;
  13636. continue;
  13637. case 'BADCUE':
  13638. // BADCUE
  13639. // 54-62 - Collect and discard the remaining cue.
  13640. if (!line) {
  13641. self.state = 'ID';
  13642. }
  13643. continue;
  13644. }
  13645. }
  13646. } catch (e) {
  13647. // If we are currently parsing a cue, report what we have.
  13648. if (self.state === 'CUETEXT' && self.cue && self.oncue) {
  13649. self.oncue(self.cue);
  13650. }
  13651. self.cue = null; // Enter BADWEBVTT state if header was not parsed correctly otherwise
  13652. // another exception occurred so enter BADCUE state.
  13653. self.state = self.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE';
  13654. }
  13655. return this;
  13656. },
  13657. flush: function flush() {
  13658. var self = this;
  13659. try {
  13660. // Finish decoding the stream.
  13661. self.buffer += self.decoder.decode(); // Synthesize the end of the current cue or region.
  13662. if (self.cue || self.state === 'HEADER') {
  13663. self.buffer += '\n\n';
  13664. self.parse();
  13665. } // If we've flushed, parsed, and we're still on the INITIAL state then
  13666. // that means we don't have enough of the stream to parse the first
  13667. // line.
  13668. if (self.state === 'INITIAL') {
  13669. throw new Error('Malformed WebVTT signature.');
  13670. }
  13671. } catch (e) {
  13672. throw e;
  13673. }
  13674. if (self.onflush) {
  13675. self.onflush();
  13676. }
  13677. return this;
  13678. }
  13679. };
  13680. /* harmony default export */ var vttparser = (VTTParser);
  13681. // CONCATENATED MODULE: ./src/utils/cues.ts
  13682. function newCue(track, startTime, endTime, captionScreen) {
  13683. var result = [];
  13684. var row; // the type data states this is VTTCue, but it can potentially be a TextTrackCue on old browsers
  13685. var cue;
  13686. var indenting;
  13687. var indent;
  13688. var text;
  13689. var VTTCue = window.VTTCue || TextTrackCue;
  13690. for (var r = 0; r < captionScreen.rows.length; r++) {
  13691. row = captionScreen.rows[r];
  13692. indenting = true;
  13693. indent = 0;
  13694. text = '';
  13695. if (!row.isEmpty()) {
  13696. for (var c = 0; c < row.chars.length; c++) {
  13697. if (row.chars[c].uchar.match(/\s/) && indenting) {
  13698. indent++;
  13699. } else {
  13700. text += row.chars[c].uchar;
  13701. indenting = false;
  13702. }
  13703. } // To be used for cleaning-up orphaned roll-up captions
  13704. row.cueStartTime = startTime; // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE
  13705. if (startTime === endTime) {
  13706. endTime += 0.0001;
  13707. }
  13708. cue = new VTTCue(startTime, endTime, fixLineBreaks(text.trim()));
  13709. if (indent >= 16) {
  13710. indent--;
  13711. } else {
  13712. indent++;
  13713. } // VTTCue.line get's flakey when using controls, so let's now include line 13&14
  13714. // also, drop line 1 since it's to close to the top
  13715. if (navigator.userAgent.match(/Firefox\//)) {
  13716. cue.line = r + 1;
  13717. } else {
  13718. cue.line = r > 7 ? r - 2 : r + 1;
  13719. }
  13720. cue.align = 'left'; // Clamp the position between 0 and 100 - if out of these bounds, Firefox throws an exception and captions break
  13721. cue.position = Math.max(0, Math.min(100, 100 * (indent / 32)));
  13722. result.push(cue);
  13723. if (track) {
  13724. track.addCue(cue);
  13725. }
  13726. }
  13727. }
  13728. return result;
  13729. }
  13730. // CONCATENATED MODULE: ./src/utils/cea-608-parser.ts
  13731. /**
  13732. *
  13733. * This code was ported from the dash.js project at:
  13734. * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js
  13735. * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2
  13736. *
  13737. * The original copyright appears below:
  13738. *
  13739. * The copyright in this software is being made available under the BSD License,
  13740. * included below. This software may be subject to other third party and contributor
  13741. * rights, including patent rights, and no such rights are granted under this license.
  13742. *
  13743. * Copyright (c) 2015-2016, DASH Industry Forum.
  13744. * All rights reserved.
  13745. *
  13746. * Redistribution and use in source and binary forms, with or without modification,
  13747. * are permitted provided that the following conditions are met:
  13748. * 1. Redistributions of source code must retain the above copyright notice, this
  13749. * list of conditions and the following disclaimer.
  13750. * * Redistributions in binary form must reproduce the above copyright notice,
  13751. * this list of conditions and the following disclaimer in the documentation and/or
  13752. * other materials provided with the distribution.
  13753. * 2. Neither the name of Dash Industry Forum nor the names of its
  13754. * contributors may be used to endorse or promote products derived from this software
  13755. * without specific prior written permission.
  13756. *
  13757. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
  13758. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  13759. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  13760. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  13761. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  13762. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  13763. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  13764. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  13765. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  13766. * POSSIBILITY OF SUCH DAMAGE.
  13767. */
  13768. /**
  13769. * Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes
  13770. */
  13771. var specialCea608CharsCodes = {
  13772. 0x2a: 0xe1,
  13773. // lowercase a, acute accent
  13774. 0x5c: 0xe9,
  13775. // lowercase e, acute accent
  13776. 0x5e: 0xed,
  13777. // lowercase i, acute accent
  13778. 0x5f: 0xf3,
  13779. // lowercase o, acute accent
  13780. 0x60: 0xfa,
  13781. // lowercase u, acute accent
  13782. 0x7b: 0xe7,
  13783. // lowercase c with cedilla
  13784. 0x7c: 0xf7,
  13785. // division symbol
  13786. 0x7d: 0xd1,
  13787. // uppercase N tilde
  13788. 0x7e: 0xf1,
  13789. // lowercase n tilde
  13790. 0x7f: 0x2588,
  13791. // Full block
  13792. // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  13793. // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F
  13794. // THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES
  13795. 0x80: 0xae,
  13796. // Registered symbol (R)
  13797. 0x81: 0xb0,
  13798. // degree sign
  13799. 0x82: 0xbd,
  13800. // 1/2 symbol
  13801. 0x83: 0xbf,
  13802. // Inverted (open) question mark
  13803. 0x84: 0x2122,
  13804. // Trademark symbol (TM)
  13805. 0x85: 0xa2,
  13806. // Cents symbol
  13807. 0x86: 0xa3,
  13808. // Pounds sterling
  13809. 0x87: 0x266a,
  13810. // Music 8'th note
  13811. 0x88: 0xe0,
  13812. // lowercase a, grave accent
  13813. 0x89: 0x20,
  13814. // transparent space (regular)
  13815. 0x8a: 0xe8,
  13816. // lowercase e, grave accent
  13817. 0x8b: 0xe2,
  13818. // lowercase a, circumflex accent
  13819. 0x8c: 0xea,
  13820. // lowercase e, circumflex accent
  13821. 0x8d: 0xee,
  13822. // lowercase i, circumflex accent
  13823. 0x8e: 0xf4,
  13824. // lowercase o, circumflex accent
  13825. 0x8f: 0xfb,
  13826. // lowercase u, circumflex accent
  13827. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  13828. // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F
  13829. 0x90: 0xc1,
  13830. // capital letter A with acute
  13831. 0x91: 0xc9,
  13832. // capital letter E with acute
  13833. 0x92: 0xd3,
  13834. // capital letter O with acute
  13835. 0x93: 0xda,
  13836. // capital letter U with acute
  13837. 0x94: 0xdc,
  13838. // capital letter U with diaresis
  13839. 0x95: 0xfc,
  13840. // lowercase letter U with diaeresis
  13841. 0x96: 0x2018,
  13842. // opening single quote
  13843. 0x97: 0xa1,
  13844. // inverted exclamation mark
  13845. 0x98: 0x2a,
  13846. // asterisk
  13847. 0x99: 0x2019,
  13848. // closing single quote
  13849. 0x9a: 0x2501,
  13850. // box drawings heavy horizontal
  13851. 0x9b: 0xa9,
  13852. // copyright sign
  13853. 0x9c: 0x2120,
  13854. // Service mark
  13855. 0x9d: 0x2022,
  13856. // (round) bullet
  13857. 0x9e: 0x201c,
  13858. // Left double quotation mark
  13859. 0x9f: 0x201d,
  13860. // Right double quotation mark
  13861. 0xa0: 0xc0,
  13862. // uppercase A, grave accent
  13863. 0xa1: 0xc2,
  13864. // uppercase A, circumflex
  13865. 0xa2: 0xc7,
  13866. // uppercase C with cedilla
  13867. 0xa3: 0xc8,
  13868. // uppercase E, grave accent
  13869. 0xa4: 0xca,
  13870. // uppercase E, circumflex
  13871. 0xa5: 0xcb,
  13872. // capital letter E with diaresis
  13873. 0xa6: 0xeb,
  13874. // lowercase letter e with diaresis
  13875. 0xa7: 0xce,
  13876. // uppercase I, circumflex
  13877. 0xa8: 0xcf,
  13878. // uppercase I, with diaresis
  13879. 0xa9: 0xef,
  13880. // lowercase i, with diaresis
  13881. 0xaa: 0xd4,
  13882. // uppercase O, circumflex
  13883. 0xab: 0xd9,
  13884. // uppercase U, grave accent
  13885. 0xac: 0xf9,
  13886. // lowercase u, grave accent
  13887. 0xad: 0xdb,
  13888. // uppercase U, circumflex
  13889. 0xae: 0xab,
  13890. // left-pointing double angle quotation mark
  13891. 0xaf: 0xbb,
  13892. // right-pointing double angle quotation mark
  13893. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  13894. // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F
  13895. 0xb0: 0xc3,
  13896. // Uppercase A, tilde
  13897. 0xb1: 0xe3,
  13898. // Lowercase a, tilde
  13899. 0xb2: 0xcd,
  13900. // Uppercase I, acute accent
  13901. 0xb3: 0xcc,
  13902. // Uppercase I, grave accent
  13903. 0xb4: 0xec,
  13904. // Lowercase i, grave accent
  13905. 0xb5: 0xd2,
  13906. // Uppercase O, grave accent
  13907. 0xb6: 0xf2,
  13908. // Lowercase o, grave accent
  13909. 0xb7: 0xd5,
  13910. // Uppercase O, tilde
  13911. 0xb8: 0xf5,
  13912. // Lowercase o, tilde
  13913. 0xb9: 0x7b,
  13914. // Open curly brace
  13915. 0xba: 0x7d,
  13916. // Closing curly brace
  13917. 0xbb: 0x5c,
  13918. // Backslash
  13919. 0xbc: 0x5e,
  13920. // Caret
  13921. 0xbd: 0x5f,
  13922. // Underscore
  13923. 0xbe: 0x7c,
  13924. // Pipe (vertical line)
  13925. 0xbf: 0x223c,
  13926. // Tilde operator
  13927. 0xc0: 0xc4,
  13928. // Uppercase A, umlaut
  13929. 0xc1: 0xe4,
  13930. // Lowercase A, umlaut
  13931. 0xc2: 0xd6,
  13932. // Uppercase O, umlaut
  13933. 0xc3: 0xf6,
  13934. // Lowercase o, umlaut
  13935. 0xc4: 0xdf,
  13936. // Esszett (sharp S)
  13937. 0xc5: 0xa5,
  13938. // Yen symbol
  13939. 0xc6: 0xa4,
  13940. // Generic currency sign
  13941. 0xc7: 0x2503,
  13942. // Box drawings heavy vertical
  13943. 0xc8: 0xc5,
  13944. // Uppercase A, ring
  13945. 0xc9: 0xe5,
  13946. // Lowercase A, ring
  13947. 0xca: 0xd8,
  13948. // Uppercase O, stroke
  13949. 0xcb: 0xf8,
  13950. // Lowercase o, strok
  13951. 0xcc: 0x250f,
  13952. // Box drawings heavy down and right
  13953. 0xcd: 0x2513,
  13954. // Box drawings heavy down and left
  13955. 0xce: 0x2517,
  13956. // Box drawings heavy up and right
  13957. 0xcf: 0x251b // Box drawings heavy up and left
  13958. };
  13959. /**
  13960. * Utils
  13961. */
  13962. var getCharForByte = function getCharForByte(_byte) {
  13963. var charCode = _byte;
  13964. if (specialCea608CharsCodes.hasOwnProperty(_byte)) {
  13965. charCode = specialCea608CharsCodes[_byte];
  13966. }
  13967. return String.fromCharCode(charCode);
  13968. };
  13969. var NR_ROWS = 15;
  13970. var NR_COLS = 100; // Tables to look up row from PAC data
  13971. var rowsLowCh1 = {
  13972. 0x11: 1,
  13973. 0x12: 3,
  13974. 0x15: 5,
  13975. 0x16: 7,
  13976. 0x17: 9,
  13977. 0x10: 11,
  13978. 0x13: 12,
  13979. 0x14: 14
  13980. };
  13981. var rowsHighCh1 = {
  13982. 0x11: 2,
  13983. 0x12: 4,
  13984. 0x15: 6,
  13985. 0x16: 8,
  13986. 0x17: 10,
  13987. 0x13: 13,
  13988. 0x14: 15
  13989. };
  13990. var rowsLowCh2 = {
  13991. 0x19: 1,
  13992. 0x1A: 3,
  13993. 0x1D: 5,
  13994. 0x1E: 7,
  13995. 0x1F: 9,
  13996. 0x18: 11,
  13997. 0x1B: 12,
  13998. 0x1C: 14
  13999. };
  14000. var rowsHighCh2 = {
  14001. 0x19: 2,
  14002. 0x1A: 4,
  14003. 0x1D: 6,
  14004. 0x1E: 8,
  14005. 0x1F: 10,
  14006. 0x1B: 13,
  14007. 0x1C: 15
  14008. };
  14009. var backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent'];
  14010. var VerboseLevel;
  14011. (function (VerboseLevel) {
  14012. VerboseLevel[VerboseLevel["ERROR"] = 0] = "ERROR";
  14013. VerboseLevel[VerboseLevel["TEXT"] = 1] = "TEXT";
  14014. VerboseLevel[VerboseLevel["WARNING"] = 2] = "WARNING";
  14015. VerboseLevel[VerboseLevel["INFO"] = 2] = "INFO";
  14016. VerboseLevel[VerboseLevel["DEBUG"] = 3] = "DEBUG";
  14017. VerboseLevel[VerboseLevel["DATA"] = 3] = "DATA";
  14018. })(VerboseLevel || (VerboseLevel = {}));
  14019. var cea_608_parser_CaptionsLogger = /*#__PURE__*/function () {
  14020. function CaptionsLogger() {
  14021. this.time = null;
  14022. this.verboseLevel = VerboseLevel.ERROR;
  14023. }
  14024. var _proto = CaptionsLogger.prototype;
  14025. _proto.log = function log(severity, msg) {
  14026. if (this.verboseLevel >= severity) {
  14027. logger["logger"].log(this.time + " [" + severity + "] " + msg);
  14028. }
  14029. };
  14030. return CaptionsLogger;
  14031. }();
  14032. var numArrayToHexArray = function numArrayToHexArray(numArray) {
  14033. var hexArray = [];
  14034. for (var j = 0; j < numArray.length; j++) {
  14035. hexArray.push(numArray[j].toString(16));
  14036. }
  14037. return hexArray;
  14038. };
  14039. var PenState = /*#__PURE__*/function () {
  14040. function PenState(foreground, underline, italics, background, flash) {
  14041. this.foreground = void 0;
  14042. this.underline = void 0;
  14043. this.italics = void 0;
  14044. this.background = void 0;
  14045. this.flash = void 0;
  14046. this.foreground = foreground || 'white';
  14047. this.underline = underline || false;
  14048. this.italics = italics || false;
  14049. this.background = background || 'black';
  14050. this.flash = flash || false;
  14051. }
  14052. var _proto2 = PenState.prototype;
  14053. _proto2.reset = function reset() {
  14054. this.foreground = 'white';
  14055. this.underline = false;
  14056. this.italics = false;
  14057. this.background = 'black';
  14058. this.flash = false;
  14059. };
  14060. _proto2.setStyles = function setStyles(styles) {
  14061. var attribs = ['foreground', 'underline', 'italics', 'background', 'flash'];
  14062. for (var i = 0; i < attribs.length; i++) {
  14063. var style = attribs[i];
  14064. if (styles.hasOwnProperty(style)) {
  14065. this[style] = styles[style];
  14066. }
  14067. }
  14068. };
  14069. _proto2.isDefault = function isDefault() {
  14070. return this.foreground === 'white' && !this.underline && !this.italics && this.background === 'black' && !this.flash;
  14071. };
  14072. _proto2.equals = function equals(other) {
  14073. return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash;
  14074. };
  14075. _proto2.copy = function copy(newPenState) {
  14076. this.foreground = newPenState.foreground;
  14077. this.underline = newPenState.underline;
  14078. this.italics = newPenState.italics;
  14079. this.background = newPenState.background;
  14080. this.flash = newPenState.flash;
  14081. };
  14082. _proto2.toString = function toString() {
  14083. return 'color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics + ', background=' + this.background + ', flash=' + this.flash;
  14084. };
  14085. return PenState;
  14086. }();
  14087. /**
  14088. * Unicode character with styling and background.
  14089. * @constructor
  14090. */
  14091. var StyledUnicodeChar = /*#__PURE__*/function () {
  14092. function StyledUnicodeChar(uchar, foreground, underline, italics, background, flash) {
  14093. this.uchar = void 0;
  14094. this.penState = void 0;
  14095. this.uchar = uchar || ' '; // unicode character
  14096. this.penState = new PenState(foreground, underline, italics, background, flash);
  14097. }
  14098. var _proto3 = StyledUnicodeChar.prototype;
  14099. _proto3.reset = function reset() {
  14100. this.uchar = ' ';
  14101. this.penState.reset();
  14102. };
  14103. _proto3.setChar = function setChar(uchar, newPenState) {
  14104. this.uchar = uchar;
  14105. this.penState.copy(newPenState);
  14106. };
  14107. _proto3.setPenState = function setPenState(newPenState) {
  14108. this.penState.copy(newPenState);
  14109. };
  14110. _proto3.equals = function equals(other) {
  14111. return this.uchar === other.uchar && this.penState.equals(other.penState);
  14112. };
  14113. _proto3.copy = function copy(newChar) {
  14114. this.uchar = newChar.uchar;
  14115. this.penState.copy(newChar.penState);
  14116. };
  14117. _proto3.isEmpty = function isEmpty() {
  14118. return this.uchar === ' ' && this.penState.isDefault();
  14119. };
  14120. return StyledUnicodeChar;
  14121. }();
  14122. /**
  14123. * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.
  14124. * @constructor
  14125. */
  14126. var Row = /*#__PURE__*/function () {
  14127. function Row(logger) {
  14128. this.chars = void 0;
  14129. this.pos = void 0;
  14130. this.currPenState = void 0;
  14131. this.cueStartTime = void 0;
  14132. this.logger = void 0;
  14133. this.chars = [];
  14134. for (var i = 0; i < NR_COLS; i++) {
  14135. this.chars.push(new StyledUnicodeChar());
  14136. }
  14137. this.logger = logger;
  14138. this.pos = 0;
  14139. this.currPenState = new PenState();
  14140. }
  14141. var _proto4 = Row.prototype;
  14142. _proto4.equals = function equals(other) {
  14143. var equal = true;
  14144. for (var i = 0; i < NR_COLS; i++) {
  14145. if (!this.chars[i].equals(other.chars[i])) {
  14146. equal = false;
  14147. break;
  14148. }
  14149. }
  14150. return equal;
  14151. };
  14152. _proto4.copy = function copy(other) {
  14153. for (var i = 0; i < NR_COLS; i++) {
  14154. this.chars[i].copy(other.chars[i]);
  14155. }
  14156. };
  14157. _proto4.isEmpty = function isEmpty() {
  14158. var empty = true;
  14159. for (var i = 0; i < NR_COLS; i++) {
  14160. if (!this.chars[i].isEmpty()) {
  14161. empty = false;
  14162. break;
  14163. }
  14164. }
  14165. return empty;
  14166. }
  14167. /**
  14168. * Set the cursor to a valid column.
  14169. */
  14170. ;
  14171. _proto4.setCursor = function setCursor(absPos) {
  14172. if (this.pos !== absPos) {
  14173. this.pos = absPos;
  14174. }
  14175. if (this.pos < 0) {
  14176. this.logger.log(VerboseLevel.DEBUG, 'Negative cursor position ' + this.pos);
  14177. this.pos = 0;
  14178. } else if (this.pos > NR_COLS) {
  14179. this.logger.log(VerboseLevel.DEBUG, 'Too large cursor position ' + this.pos);
  14180. this.pos = NR_COLS;
  14181. }
  14182. }
  14183. /**
  14184. * Move the cursor relative to current position.
  14185. */
  14186. ;
  14187. _proto4.moveCursor = function moveCursor(relPos) {
  14188. var newPos = this.pos + relPos;
  14189. if (relPos > 1) {
  14190. for (var i = this.pos + 1; i < newPos + 1; i++) {
  14191. this.chars[i].setPenState(this.currPenState);
  14192. }
  14193. }
  14194. this.setCursor(newPos);
  14195. }
  14196. /**
  14197. * Backspace, move one step back and clear character.
  14198. */
  14199. ;
  14200. _proto4.backSpace = function backSpace() {
  14201. this.moveCursor(-1);
  14202. this.chars[this.pos].setChar(' ', this.currPenState);
  14203. };
  14204. _proto4.insertChar = function insertChar(_byte2) {
  14205. if (_byte2 >= 0x90) {
  14206. // Extended char
  14207. this.backSpace();
  14208. }
  14209. var _char = getCharForByte(_byte2);
  14210. if (this.pos >= NR_COLS) {
  14211. this.logger.log(VerboseLevel.ERROR, 'Cannot insert ' + _byte2.toString(16) + ' (' + _char + ') at position ' + this.pos + '. Skipping it!');
  14212. return;
  14213. }
  14214. this.chars[this.pos].setChar(_char, this.currPenState);
  14215. this.moveCursor(1);
  14216. };
  14217. _proto4.clearFromPos = function clearFromPos(startPos) {
  14218. var i;
  14219. for (i = startPos; i < NR_COLS; i++) {
  14220. this.chars[i].reset();
  14221. }
  14222. };
  14223. _proto4.clear = function clear() {
  14224. this.clearFromPos(0);
  14225. this.pos = 0;
  14226. this.currPenState.reset();
  14227. };
  14228. _proto4.clearToEndOfRow = function clearToEndOfRow() {
  14229. this.clearFromPos(this.pos);
  14230. };
  14231. _proto4.getTextString = function getTextString() {
  14232. var chars = [];
  14233. var empty = true;
  14234. for (var i = 0; i < NR_COLS; i++) {
  14235. var _char2 = this.chars[i].uchar;
  14236. if (_char2 !== ' ') {
  14237. empty = false;
  14238. }
  14239. chars.push(_char2);
  14240. }
  14241. if (empty) {
  14242. return '';
  14243. } else {
  14244. return chars.join('');
  14245. }
  14246. };
  14247. _proto4.setPenStyles = function setPenStyles(styles) {
  14248. this.currPenState.setStyles(styles);
  14249. var currChar = this.chars[this.pos];
  14250. currChar.setPenState(this.currPenState);
  14251. };
  14252. return Row;
  14253. }();
  14254. /**
  14255. * Keep a CEA-608 screen of 32x15 styled characters
  14256. * @constructor
  14257. */
  14258. var CaptionScreen = /*#__PURE__*/function () {
  14259. function CaptionScreen(logger) {
  14260. this.rows = void 0;
  14261. this.currRow = void 0;
  14262. this.nrRollUpRows = void 0;
  14263. this.lastOutputScreen = void 0;
  14264. this.logger = void 0;
  14265. this.rows = [];
  14266. for (var i = 0; i < NR_ROWS; i++) {
  14267. this.rows.push(new Row(logger));
  14268. } // Note that we use zero-based numbering (0-14)
  14269. this.logger = logger;
  14270. this.currRow = NR_ROWS - 1;
  14271. this.nrRollUpRows = null;
  14272. this.lastOutputScreen = null;
  14273. this.reset();
  14274. }
  14275. var _proto5 = CaptionScreen.prototype;
  14276. _proto5.reset = function reset() {
  14277. for (var i = 0; i < NR_ROWS; i++) {
  14278. this.rows[i].clear();
  14279. }
  14280. this.currRow = NR_ROWS - 1;
  14281. };
  14282. _proto5.equals = function equals(other) {
  14283. var equal = true;
  14284. for (var i = 0; i < NR_ROWS; i++) {
  14285. if (!this.rows[i].equals(other.rows[i])) {
  14286. equal = false;
  14287. break;
  14288. }
  14289. }
  14290. return equal;
  14291. };
  14292. _proto5.copy = function copy(other) {
  14293. for (var i = 0; i < NR_ROWS; i++) {
  14294. this.rows[i].copy(other.rows[i]);
  14295. }
  14296. };
  14297. _proto5.isEmpty = function isEmpty() {
  14298. var empty = true;
  14299. for (var i = 0; i < NR_ROWS; i++) {
  14300. if (!this.rows[i].isEmpty()) {
  14301. empty = false;
  14302. break;
  14303. }
  14304. }
  14305. return empty;
  14306. };
  14307. _proto5.backSpace = function backSpace() {
  14308. var row = this.rows[this.currRow];
  14309. row.backSpace();
  14310. };
  14311. _proto5.clearToEndOfRow = function clearToEndOfRow() {
  14312. var row = this.rows[this.currRow];
  14313. row.clearToEndOfRow();
  14314. }
  14315. /**
  14316. * Insert a character (without styling) in the current row.
  14317. */
  14318. ;
  14319. _proto5.insertChar = function insertChar(_char3) {
  14320. var row = this.rows[this.currRow];
  14321. row.insertChar(_char3);
  14322. };
  14323. _proto5.setPen = function setPen(styles) {
  14324. var row = this.rows[this.currRow];
  14325. row.setPenStyles(styles);
  14326. };
  14327. _proto5.moveCursor = function moveCursor(relPos) {
  14328. var row = this.rows[this.currRow];
  14329. row.moveCursor(relPos);
  14330. };
  14331. _proto5.setCursor = function setCursor(absPos) {
  14332. this.logger.log(VerboseLevel.INFO, 'setCursor: ' + absPos);
  14333. var row = this.rows[this.currRow];
  14334. row.setCursor(absPos);
  14335. };
  14336. _proto5.setPAC = function setPAC(pacData) {
  14337. this.logger.log(VerboseLevel.INFO, 'pacData = ' + JSON.stringify(pacData));
  14338. var newRow = pacData.row - 1;
  14339. if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {
  14340. newRow = this.nrRollUpRows - 1;
  14341. } // Make sure this only affects Roll-up Captions by checking this.nrRollUpRows
  14342. if (this.nrRollUpRows && this.currRow !== newRow) {
  14343. // clear all rows first
  14344. for (var i = 0; i < NR_ROWS; i++) {
  14345. this.rows[i].clear();
  14346. } // Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location
  14347. // topRowIndex - the start of rows to copy (inclusive index)
  14348. var topRowIndex = this.currRow + 1 - this.nrRollUpRows; // We only copy if the last position was already shown.
  14349. // We use the cueStartTime value to check this.
  14350. var lastOutputScreen = this.lastOutputScreen;
  14351. if (lastOutputScreen) {
  14352. var prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;
  14353. var time = this.logger.time;
  14354. if (prevLineTime && time !== null && prevLineTime < time) {
  14355. for (var _i = 0; _i < this.nrRollUpRows; _i++) {
  14356. this.rows[newRow - this.nrRollUpRows + _i + 1].copy(lastOutputScreen.rows[topRowIndex + _i]);
  14357. }
  14358. }
  14359. }
  14360. }
  14361. this.currRow = newRow;
  14362. var row = this.rows[this.currRow];
  14363. if (pacData.indent !== null) {
  14364. var indent = pacData.indent;
  14365. var prevPos = Math.max(indent - 1, 0);
  14366. row.setCursor(pacData.indent);
  14367. pacData.color = row.chars[prevPos].penState.foreground;
  14368. }
  14369. var styles = {
  14370. foreground: pacData.color,
  14371. underline: pacData.underline,
  14372. italics: pacData.italics,
  14373. background: 'black',
  14374. flash: false
  14375. };
  14376. this.setPen(styles);
  14377. }
  14378. /**
  14379. * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).
  14380. */
  14381. ;
  14382. _proto5.setBkgData = function setBkgData(bkgData) {
  14383. this.logger.log(VerboseLevel.INFO, 'bkgData = ' + JSON.stringify(bkgData));
  14384. this.backSpace();
  14385. this.setPen(bkgData);
  14386. this.insertChar(0x20); // Space
  14387. };
  14388. _proto5.setRollUpRows = function setRollUpRows(nrRows) {
  14389. this.nrRollUpRows = nrRows;
  14390. };
  14391. _proto5.rollUp = function rollUp() {
  14392. if (this.nrRollUpRows === null) {
  14393. this.logger.log(VerboseLevel.DEBUG, 'roll_up but nrRollUpRows not set yet');
  14394. return; // Not properly setup
  14395. }
  14396. this.logger.log(VerboseLevel.TEXT, this.getDisplayText());
  14397. var topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  14398. var topRow = this.rows.splice(topRowIndex, 1)[0];
  14399. topRow.clear();
  14400. this.rows.splice(this.currRow, 0, topRow);
  14401. this.logger.log(VerboseLevel.INFO, 'Rolling up'); // this.logger.log(VerboseLevel.TEXT, this.get_display_text())
  14402. }
  14403. /**
  14404. * Get all non-empty rows with as unicode text.
  14405. */
  14406. ;
  14407. _proto5.getDisplayText = function getDisplayText(asOneRow) {
  14408. asOneRow = asOneRow || false;
  14409. var displayText = [];
  14410. var text = '';
  14411. var rowNr = -1;
  14412. for (var i = 0; i < NR_ROWS; i++) {
  14413. var rowText = this.rows[i].getTextString();
  14414. if (rowText) {
  14415. rowNr = i + 1;
  14416. if (asOneRow) {
  14417. displayText.push('Row ' + rowNr + ': \'' + rowText + '\'');
  14418. } else {
  14419. displayText.push(rowText.trim());
  14420. }
  14421. }
  14422. }
  14423. if (displayText.length > 0) {
  14424. if (asOneRow) {
  14425. text = '[' + displayText.join(' | ') + ']';
  14426. } else {
  14427. text = displayText.join('\n');
  14428. }
  14429. }
  14430. return text;
  14431. };
  14432. _proto5.getTextAndFormat = function getTextAndFormat() {
  14433. return this.rows;
  14434. };
  14435. return CaptionScreen;
  14436. }(); // var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];
  14437. var Cea608Channel = /*#__PURE__*/function () {
  14438. function Cea608Channel(channelNumber, outputFilter, logger) {
  14439. this.chNr = void 0;
  14440. this.outputFilter = void 0;
  14441. this.mode = void 0;
  14442. this.verbose = void 0;
  14443. this.displayedMemory = void 0;
  14444. this.nonDisplayedMemory = void 0;
  14445. this.lastOutputScreen = void 0;
  14446. this.currRollUpRow = void 0;
  14447. this.writeScreen = void 0;
  14448. this.cueStartTime = void 0;
  14449. this.logger = void 0;
  14450. this.chNr = channelNumber;
  14451. this.outputFilter = outputFilter;
  14452. this.mode = null;
  14453. this.verbose = 0;
  14454. this.displayedMemory = new CaptionScreen(logger);
  14455. this.nonDisplayedMemory = new CaptionScreen(logger);
  14456. this.lastOutputScreen = new CaptionScreen(logger);
  14457. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  14458. this.writeScreen = this.displayedMemory;
  14459. this.mode = null;
  14460. this.cueStartTime = null; // Keeps track of where a cue started.
  14461. this.logger = logger;
  14462. }
  14463. var _proto6 = Cea608Channel.prototype;
  14464. _proto6.reset = function reset() {
  14465. this.mode = null;
  14466. this.displayedMemory.reset();
  14467. this.nonDisplayedMemory.reset();
  14468. this.lastOutputScreen.reset();
  14469. this.outputFilter.reset();
  14470. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  14471. this.writeScreen = this.displayedMemory;
  14472. this.mode = null;
  14473. this.cueStartTime = null;
  14474. };
  14475. _proto6.getHandler = function getHandler() {
  14476. return this.outputFilter;
  14477. };
  14478. _proto6.setHandler = function setHandler(newHandler) {
  14479. this.outputFilter = newHandler;
  14480. };
  14481. _proto6.setPAC = function setPAC(pacData) {
  14482. this.writeScreen.setPAC(pacData);
  14483. };
  14484. _proto6.setBkgData = function setBkgData(bkgData) {
  14485. this.writeScreen.setBkgData(bkgData);
  14486. };
  14487. _proto6.setMode = function setMode(newMode) {
  14488. if (newMode === this.mode) {
  14489. return;
  14490. }
  14491. this.mode = newMode;
  14492. this.logger.log(VerboseLevel.INFO, 'MODE=' + newMode);
  14493. if (this.mode === 'MODE_POP-ON') {
  14494. this.writeScreen = this.nonDisplayedMemory;
  14495. } else {
  14496. this.writeScreen = this.displayedMemory;
  14497. this.writeScreen.reset();
  14498. }
  14499. if (this.mode !== 'MODE_ROLL-UP') {
  14500. this.displayedMemory.nrRollUpRows = null;
  14501. this.nonDisplayedMemory.nrRollUpRows = null;
  14502. }
  14503. this.mode = newMode;
  14504. };
  14505. _proto6.insertChars = function insertChars(chars) {
  14506. for (var i = 0; i < chars.length; i++) {
  14507. this.writeScreen.insertChar(chars[i]);
  14508. }
  14509. var screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP';
  14510. this.logger.log(VerboseLevel.INFO, screen + ': ' + this.writeScreen.getDisplayText(true));
  14511. if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {
  14512. this.logger.log(VerboseLevel.TEXT, 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true));
  14513. this.outputDataUpdate();
  14514. }
  14515. };
  14516. _proto6.ccRCL = function ccRCL() {
  14517. // Resume Caption Loading (switch mode to Pop On)
  14518. this.logger.log(VerboseLevel.INFO, 'RCL - Resume Caption Loading');
  14519. this.setMode('MODE_POP-ON');
  14520. };
  14521. _proto6.ccBS = function ccBS() {
  14522. // BackSpace
  14523. this.logger.log(VerboseLevel.INFO, 'BS - BackSpace');
  14524. if (this.mode === 'MODE_TEXT') {
  14525. return;
  14526. }
  14527. this.writeScreen.backSpace();
  14528. if (this.writeScreen === this.displayedMemory) {
  14529. this.outputDataUpdate();
  14530. }
  14531. };
  14532. _proto6.ccAOF = function ccAOF() {// Reserved (formerly Alarm Off)
  14533. };
  14534. _proto6.ccAON = function ccAON() {// Reserved (formerly Alarm On)
  14535. };
  14536. _proto6.ccDER = function ccDER() {
  14537. // Delete to End of Row
  14538. this.logger.log(VerboseLevel.INFO, 'DER- Delete to End of Row');
  14539. this.writeScreen.clearToEndOfRow();
  14540. this.outputDataUpdate();
  14541. };
  14542. _proto6.ccRU = function ccRU(nrRows) {
  14543. // Roll-Up Captions-2,3,or 4 Rows
  14544. this.logger.log(VerboseLevel.INFO, 'RU(' + nrRows + ') - Roll Up');
  14545. this.writeScreen = this.displayedMemory;
  14546. this.setMode('MODE_ROLL-UP');
  14547. this.writeScreen.setRollUpRows(nrRows);
  14548. };
  14549. _proto6.ccFON = function ccFON() {
  14550. // Flash On
  14551. this.logger.log(VerboseLevel.INFO, 'FON - Flash On');
  14552. this.writeScreen.setPen({
  14553. flash: true
  14554. });
  14555. };
  14556. _proto6.ccRDC = function ccRDC() {
  14557. // Resume Direct Captioning (switch mode to PaintOn)
  14558. this.logger.log(VerboseLevel.INFO, 'RDC - Resume Direct Captioning');
  14559. this.setMode('MODE_PAINT-ON');
  14560. };
  14561. _proto6.ccTR = function ccTR() {
  14562. // Text Restart in text mode (not supported, however)
  14563. this.logger.log(VerboseLevel.INFO, 'TR');
  14564. this.setMode('MODE_TEXT');
  14565. };
  14566. _proto6.ccRTD = function ccRTD() {
  14567. // Resume Text Display in Text mode (not supported, however)
  14568. this.logger.log(VerboseLevel.INFO, 'RTD');
  14569. this.setMode('MODE_TEXT');
  14570. };
  14571. _proto6.ccEDM = function ccEDM() {
  14572. // Erase Displayed Memory
  14573. this.logger.log(VerboseLevel.INFO, 'EDM - Erase Displayed Memory');
  14574. this.displayedMemory.reset();
  14575. this.outputDataUpdate(true);
  14576. };
  14577. _proto6.ccCR = function ccCR() {
  14578. // Carriage Return
  14579. this.logger.log(VerboseLevel.INFO, 'CR - Carriage Return');
  14580. this.writeScreen.rollUp();
  14581. this.outputDataUpdate(true);
  14582. };
  14583. _proto6.ccENM = function ccENM() {
  14584. // Erase Non-Displayed Memory
  14585. this.logger.log(VerboseLevel.INFO, 'ENM - Erase Non-displayed Memory');
  14586. this.nonDisplayedMemory.reset();
  14587. };
  14588. _proto6.ccEOC = function ccEOC() {
  14589. // End of Caption (Flip Memories)
  14590. this.logger.log(VerboseLevel.INFO, 'EOC - End Of Caption');
  14591. if (this.mode === 'MODE_POP-ON') {
  14592. var tmp = this.displayedMemory;
  14593. this.displayedMemory = this.nonDisplayedMemory;
  14594. this.nonDisplayedMemory = tmp;
  14595. this.writeScreen = this.nonDisplayedMemory;
  14596. this.logger.log(VerboseLevel.TEXT, 'DISP: ' + this.displayedMemory.getDisplayText());
  14597. }
  14598. this.outputDataUpdate(true);
  14599. };
  14600. _proto6.ccTO = function ccTO(nrCols) {
  14601. // Tab Offset 1,2, or 3 columns
  14602. this.logger.log(VerboseLevel.INFO, 'TO(' + nrCols + ') - Tab Offset');
  14603. this.writeScreen.moveCursor(nrCols);
  14604. };
  14605. _proto6.ccMIDROW = function ccMIDROW(secondByte) {
  14606. // Parse MIDROW command
  14607. var styles = {
  14608. flash: false
  14609. };
  14610. styles.underline = secondByte % 2 === 1;
  14611. styles.italics = secondByte >= 0x2e;
  14612. if (!styles.italics) {
  14613. var colorIndex = Math.floor(secondByte / 2) - 0x10;
  14614. var colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta'];
  14615. styles.foreground = colors[colorIndex];
  14616. } else {
  14617. styles.foreground = 'white';
  14618. }
  14619. this.logger.log(VerboseLevel.INFO, 'MIDROW: ' + JSON.stringify(styles));
  14620. this.writeScreen.setPen(styles);
  14621. };
  14622. _proto6.outputDataUpdate = function outputDataUpdate(dispatch) {
  14623. if (dispatch === void 0) {
  14624. dispatch = false;
  14625. }
  14626. var time = this.logger.time;
  14627. if (time === null) {
  14628. return;
  14629. }
  14630. if (this.outputFilter) {
  14631. if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {
  14632. // Start of a new cue
  14633. this.cueStartTime = time;
  14634. } else {
  14635. if (!this.displayedMemory.equals(this.lastOutputScreen)) {
  14636. this.outputFilter.newCue(this.cueStartTime, time, this.lastOutputScreen);
  14637. if (dispatch && this.outputFilter.dispatchCue) {
  14638. this.outputFilter.dispatchCue();
  14639. }
  14640. this.cueStartTime = this.displayedMemory.isEmpty() ? null : time;
  14641. }
  14642. }
  14643. this.lastOutputScreen.copy(this.displayedMemory);
  14644. }
  14645. };
  14646. _proto6.cueSplitAtTime = function cueSplitAtTime(t) {
  14647. if (this.outputFilter) {
  14648. if (!this.displayedMemory.isEmpty()) {
  14649. if (this.outputFilter.newCue) {
  14650. this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory);
  14651. }
  14652. this.cueStartTime = t;
  14653. }
  14654. }
  14655. };
  14656. return Cea608Channel;
  14657. }();
  14658. var Cea608Parser = /*#__PURE__*/function () {
  14659. function Cea608Parser(field, out1, out2) {
  14660. this.channels = void 0;
  14661. this.currentChannel = 0;
  14662. this.cmdHistory = void 0;
  14663. this.logger = void 0;
  14664. var logger = new cea_608_parser_CaptionsLogger();
  14665. this.channels = [null, new Cea608Channel(field, out1, logger), new Cea608Channel(field + 1, out2, logger)];
  14666. this.cmdHistory = createCmdHistory();
  14667. this.logger = logger;
  14668. }
  14669. var _proto7 = Cea608Parser.prototype;
  14670. _proto7.getHandler = function getHandler(channel) {
  14671. return this.channels[channel].getHandler();
  14672. };
  14673. _proto7.setHandler = function setHandler(channel, newHandler) {
  14674. this.channels[channel].setHandler(newHandler);
  14675. }
  14676. /**
  14677. * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.
  14678. */
  14679. ;
  14680. _proto7.addData = function addData(time, byteList) {
  14681. var cmdFound;
  14682. var a;
  14683. var b;
  14684. var charsFound = false;
  14685. this.logger.time = time;
  14686. for (var i = 0; i < byteList.length; i += 2) {
  14687. a = byteList[i] & 0x7f;
  14688. b = byteList[i + 1] & 0x7f;
  14689. if (a === 0 && b === 0) {
  14690. continue;
  14691. } else {
  14692. this.logger.log(VerboseLevel.DATA, '[' + numArrayToHexArray([byteList[i], byteList[i + 1]]) + '] -> (' + numArrayToHexArray([a, b]) + ')');
  14693. }
  14694. cmdFound = this.parseCmd(a, b);
  14695. if (!cmdFound) {
  14696. cmdFound = this.parseMidrow(a, b);
  14697. }
  14698. if (!cmdFound) {
  14699. cmdFound = this.parsePAC(a, b);
  14700. }
  14701. if (!cmdFound) {
  14702. cmdFound = this.parseBackgroundAttributes(a, b);
  14703. }
  14704. if (!cmdFound) {
  14705. charsFound = this.parseChars(a, b);
  14706. if (charsFound) {
  14707. var currChNr = this.currentChannel;
  14708. if (currChNr && currChNr > 0) {
  14709. var channel = this.channels[currChNr];
  14710. channel.insertChars(charsFound);
  14711. } else {
  14712. this.logger.log(VerboseLevel.WARNING, 'No channel found yet. TEXT-MODE?');
  14713. }
  14714. }
  14715. }
  14716. if (!cmdFound && !charsFound) {
  14717. this.logger.log(VerboseLevel.WARNING, 'Couldn\'t parse cleaned data ' + numArrayToHexArray([a, b]) + ' orig: ' + numArrayToHexArray([byteList[i], byteList[i + 1]]));
  14718. }
  14719. }
  14720. }
  14721. /**
  14722. * Parse Command.
  14723. * @returns {Boolean} Tells if a command was found
  14724. */
  14725. ;
  14726. _proto7.parseCmd = function parseCmd(a, b) {
  14727. var cmdHistory = this.cmdHistory;
  14728. var cond1 = (a === 0x14 || a === 0x1C || a === 0x15 || a === 0x1D) && b >= 0x20 && b <= 0x2F;
  14729. var cond2 = (a === 0x17 || a === 0x1F) && b >= 0x21 && b <= 0x23;
  14730. if (!(cond1 || cond2)) {
  14731. return false;
  14732. }
  14733. if (hasCmdRepeated(a, b, cmdHistory)) {
  14734. setLastCmd(null, null, cmdHistory);
  14735. this.logger.log(VerboseLevel.DEBUG, 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped');
  14736. return true;
  14737. }
  14738. var chNr = a === 0x14 || a === 0x15 || a === 0x17 ? 1 : 2;
  14739. var channel = this.channels[chNr];
  14740. if (a === 0x14 || a === 0x15 || a === 0x1C || a === 0x1D) {
  14741. if (b === 0x20) {
  14742. channel.ccRCL();
  14743. } else if (b === 0x21) {
  14744. channel.ccBS();
  14745. } else if (b === 0x22) {
  14746. channel.ccAOF();
  14747. } else if (b === 0x23) {
  14748. channel.ccAON();
  14749. } else if (b === 0x24) {
  14750. channel.ccDER();
  14751. } else if (b === 0x25) {
  14752. channel.ccRU(2);
  14753. } else if (b === 0x26) {
  14754. channel.ccRU(3);
  14755. } else if (b === 0x27) {
  14756. channel.ccRU(4);
  14757. } else if (b === 0x28) {
  14758. channel.ccFON();
  14759. } else if (b === 0x29) {
  14760. channel.ccRDC();
  14761. } else if (b === 0x2A) {
  14762. channel.ccTR();
  14763. } else if (b === 0x2B) {
  14764. channel.ccRTD();
  14765. } else if (b === 0x2C) {
  14766. channel.ccEDM();
  14767. } else if (b === 0x2D) {
  14768. channel.ccCR();
  14769. } else if (b === 0x2E) {
  14770. channel.ccENM();
  14771. } else if (b === 0x2F) {
  14772. channel.ccEOC();
  14773. }
  14774. } else {
  14775. // a == 0x17 || a == 0x1F
  14776. channel.ccTO(b - 0x20);
  14777. }
  14778. setLastCmd(a, b, cmdHistory);
  14779. this.currentChannel = chNr;
  14780. return true;
  14781. }
  14782. /**
  14783. * Parse midrow styling command
  14784. * @returns {Boolean}
  14785. */
  14786. ;
  14787. _proto7.parseMidrow = function parseMidrow(a, b) {
  14788. var chNr = 0;
  14789. if ((a === 0x11 || a === 0x19) && b >= 0x20 && b <= 0x2f) {
  14790. if (a === 0x11) {
  14791. chNr = 1;
  14792. } else {
  14793. chNr = 2;
  14794. }
  14795. if (chNr !== this.currentChannel) {
  14796. this.logger.log(VerboseLevel.ERROR, 'Mismatch channel in midrow parsing');
  14797. return false;
  14798. }
  14799. var channel = this.channels[chNr];
  14800. if (!channel) {
  14801. return false;
  14802. }
  14803. channel.ccMIDROW(b);
  14804. this.logger.log(VerboseLevel.DEBUG, 'MIDROW (' + numArrayToHexArray([a, b]) + ')');
  14805. return true;
  14806. }
  14807. return false;
  14808. }
  14809. /**
  14810. * Parse Preable Access Codes (Table 53).
  14811. * @returns {Boolean} Tells if PAC found
  14812. */
  14813. ;
  14814. _proto7.parsePAC = function parsePAC(a, b) {
  14815. var row;
  14816. var cmdHistory = this.cmdHistory;
  14817. var case1 = (a >= 0x11 && a <= 0x17 || a >= 0x19 && a <= 0x1F) && b >= 0x40 && b <= 0x7F;
  14818. var case2 = (a === 0x10 || a === 0x18) && b >= 0x40 && b <= 0x5F;
  14819. if (!(case1 || case2)) {
  14820. return false;
  14821. }
  14822. if (hasCmdRepeated(a, b, cmdHistory)) {
  14823. setLastCmd(null, null, cmdHistory);
  14824. return true; // Repeated commands are dropped (once)
  14825. }
  14826. var chNr = a <= 0x17 ? 1 : 2;
  14827. if (b >= 0x40 && b <= 0x5F) {
  14828. row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];
  14829. } else {
  14830. // 0x60 <= b <= 0x7F
  14831. row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a];
  14832. }
  14833. var channel = this.channels[chNr];
  14834. if (!channel) {
  14835. return false;
  14836. }
  14837. channel.setPAC(this.interpretPAC(row, b));
  14838. setLastCmd(a, b, cmdHistory);
  14839. this.currentChannel = chNr;
  14840. return true;
  14841. }
  14842. /**
  14843. * Interpret the second byte of the pac, and return the information.
  14844. * @returns {Object} pacData with style parameters.
  14845. */
  14846. ;
  14847. _proto7.interpretPAC = function interpretPAC(row, _byte3) {
  14848. var pacIndex = _byte3;
  14849. var pacData = {
  14850. color: null,
  14851. italics: false,
  14852. indent: null,
  14853. underline: false,
  14854. row: row
  14855. };
  14856. if (_byte3 > 0x5F) {
  14857. pacIndex = _byte3 - 0x60;
  14858. } else {
  14859. pacIndex = _byte3 - 0x40;
  14860. }
  14861. pacData.underline = (pacIndex & 1) === 1;
  14862. if (pacIndex <= 0xd) {
  14863. pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex / 2)];
  14864. } else if (pacIndex <= 0xf) {
  14865. pacData.italics = true;
  14866. pacData.color = 'white';
  14867. } else {
  14868. pacData.indent = Math.floor((pacIndex - 0x10) / 2) * 4;
  14869. }
  14870. return pacData; // Note that row has zero offset. The spec uses 1.
  14871. }
  14872. /**
  14873. * Parse characters.
  14874. * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.
  14875. */
  14876. ;
  14877. _proto7.parseChars = function parseChars(a, b) {
  14878. var channelNr;
  14879. var charCodes = null;
  14880. var charCode1 = null;
  14881. if (a >= 0x19) {
  14882. channelNr = 2;
  14883. charCode1 = a - 8;
  14884. } else {
  14885. channelNr = 1;
  14886. charCode1 = a;
  14887. }
  14888. if (charCode1 >= 0x11 && charCode1 <= 0x13) {
  14889. // Special character
  14890. var oneCode = b;
  14891. if (charCode1 === 0x11) {
  14892. oneCode = b + 0x50;
  14893. } else if (charCode1 === 0x12) {
  14894. oneCode = b + 0x70;
  14895. } else {
  14896. oneCode = b + 0x90;
  14897. }
  14898. this.logger.log(VerboseLevel.INFO, 'Special char \'' + getCharForByte(oneCode) + '\' in channel ' + channelNr);
  14899. charCodes = [oneCode];
  14900. } else if (a >= 0x20 && a <= 0x7f) {
  14901. charCodes = b === 0 ? [a] : [a, b];
  14902. }
  14903. if (charCodes) {
  14904. var hexCodes = numArrayToHexArray(charCodes);
  14905. this.logger.log(VerboseLevel.DEBUG, 'Char codes = ' + hexCodes.join(','));
  14906. setLastCmd(a, b, this.cmdHistory);
  14907. }
  14908. return charCodes;
  14909. }
  14910. /**
  14911. * Parse extended background attributes as well as new foreground color black.
  14912. * @returns {Boolean} Tells if background attributes are found
  14913. */
  14914. ;
  14915. _proto7.parseBackgroundAttributes = function parseBackgroundAttributes(a, b) {
  14916. var case1 = (a === 0x10 || a === 0x18) && b >= 0x20 && b <= 0x2f;
  14917. var case2 = (a === 0x17 || a === 0x1f) && b >= 0x2d && b <= 0x2f;
  14918. if (!(case1 || case2)) {
  14919. return false;
  14920. }
  14921. var index;
  14922. var bkgData = {};
  14923. if (a === 0x10 || a === 0x18) {
  14924. index = Math.floor((b - 0x20) / 2);
  14925. bkgData.background = backgroundColors[index];
  14926. if (b % 2 === 1) {
  14927. bkgData.background = bkgData.background + '_semi';
  14928. }
  14929. } else if (b === 0x2d) {
  14930. bkgData.background = 'transparent';
  14931. } else {
  14932. bkgData.foreground = 'black';
  14933. if (b === 0x2f) {
  14934. bkgData.underline = true;
  14935. }
  14936. }
  14937. var chNr = a <= 0x17 ? 1 : 2;
  14938. var channel = this.channels[chNr];
  14939. channel.setBkgData(bkgData);
  14940. setLastCmd(a, b, this.cmdHistory);
  14941. return true;
  14942. }
  14943. /**
  14944. * Reset state of parser and its channels.
  14945. */
  14946. ;
  14947. _proto7.reset = function reset() {
  14948. for (var i = 0; i < Object.keys(this.channels).length; i++) {
  14949. var channel = this.channels[i];
  14950. if (channel) {
  14951. channel.reset();
  14952. }
  14953. }
  14954. this.cmdHistory = createCmdHistory();
  14955. }
  14956. /**
  14957. * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.
  14958. */
  14959. ;
  14960. _proto7.cueSplitAtTime = function cueSplitAtTime(t) {
  14961. for (var i = 0; i < this.channels.length; i++) {
  14962. var channel = this.channels[i];
  14963. if (channel) {
  14964. channel.cueSplitAtTime(t);
  14965. }
  14966. }
  14967. };
  14968. return Cea608Parser;
  14969. }();
  14970. function setLastCmd(a, b, cmdHistory) {
  14971. cmdHistory.a = a;
  14972. cmdHistory.b = b;
  14973. }
  14974. function hasCmdRepeated(a, b, cmdHistory) {
  14975. return cmdHistory.a === a && cmdHistory.b === b;
  14976. }
  14977. function createCmdHistory() {
  14978. return {
  14979. a: null,
  14980. b: null
  14981. };
  14982. }
  14983. /* harmony default export */ var cea_608_parser = (Cea608Parser);
  14984. // CONCATENATED MODULE: ./src/utils/output-filter.ts
  14985. var OutputFilter = /*#__PURE__*/function () {
  14986. function OutputFilter(timelineController, trackName) {
  14987. this.timelineController = void 0;
  14988. this.cueRanges = [];
  14989. this.trackName = void 0;
  14990. this.startTime = null;
  14991. this.endTime = null;
  14992. this.screen = null;
  14993. this.timelineController = timelineController;
  14994. this.trackName = trackName;
  14995. }
  14996. var _proto = OutputFilter.prototype;
  14997. _proto.dispatchCue = function dispatchCue() {
  14998. if (this.startTime === null) {
  14999. return;
  15000. }
  15001. this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen, this.cueRanges);
  15002. this.startTime = null;
  15003. };
  15004. _proto.newCue = function newCue(startTime, endTime, screen) {
  15005. if (this.startTime === null || this.startTime > startTime) {
  15006. this.startTime = startTime;
  15007. }
  15008. this.endTime = endTime;
  15009. this.screen = screen;
  15010. this.timelineController.createCaptionsTrack(this.trackName);
  15011. };
  15012. _proto.reset = function reset() {
  15013. this.cueRanges = [];
  15014. };
  15015. return OutputFilter;
  15016. }();
  15017. // CONCATENATED MODULE: ./src/utils/webvtt-parser.js
  15018. // String.prototype.startsWith is not supported in IE11
  15019. var startsWith = function startsWith(inputString, searchString, position) {
  15020. return inputString.substr(position || 0, searchString.length) === searchString;
  15021. };
  15022. var webvtt_parser_cueString2millis = function cueString2millis(timeString) {
  15023. var ts = parseInt(timeString.substr(-3));
  15024. var secs = parseInt(timeString.substr(-6, 2));
  15025. var mins = parseInt(timeString.substr(-9, 2));
  15026. var hours = timeString.length > 9 ? parseInt(timeString.substr(0, timeString.indexOf(':'))) : 0;
  15027. if (!Object(number["isFiniteNumber"])(ts) || !Object(number["isFiniteNumber"])(secs) || !Object(number["isFiniteNumber"])(mins) || !Object(number["isFiniteNumber"])(hours)) {
  15028. throw Error("Malformed X-TIMESTAMP-MAP: Local:" + timeString);
  15029. }
  15030. ts += 1000 * secs;
  15031. ts += 60 * 1000 * mins;
  15032. ts += 60 * 60 * 1000 * hours;
  15033. return ts;
  15034. }; // From https://github.com/darkskyapp/string-hash
  15035. var hash = function hash(text) {
  15036. var hash = 5381;
  15037. var i = text.length;
  15038. while (i) {
  15039. hash = hash * 33 ^ text.charCodeAt(--i);
  15040. }
  15041. return (hash >>> 0).toString();
  15042. };
  15043. var calculateOffset = function calculateOffset(vttCCs, cc, presentationTime) {
  15044. var currCC = vttCCs[cc];
  15045. var prevCC = vttCCs[currCC.prevCC]; // This is the first discontinuity or cues have been processed since the last discontinuity
  15046. // Offset = current discontinuity time
  15047. if (!prevCC || !prevCC.new && currCC.new) {
  15048. vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;
  15049. currCC.new = false;
  15050. return;
  15051. } // There have been discontinuities since cues were last parsed.
  15052. // Offset = time elapsed
  15053. while (prevCC && prevCC.new) {
  15054. vttCCs.ccOffset += currCC.start - prevCC.start;
  15055. currCC.new = false;
  15056. currCC = prevCC;
  15057. prevCC = vttCCs[currCC.prevCC];
  15058. }
  15059. vttCCs.presentationOffset = presentationTime;
  15060. };
  15061. var WebVTTParser = {
  15062. parse: function parse(vttByteArray, syncPTS, vttCCs, cc, callBack, errorCallBack) {
  15063. // Convert byteArray into string, replacing any somewhat exotic linefeeds with "\n", then split on that character.
  15064. var re = /\r\n|\n\r|\n|\r/g; // Uint8Array.prototype.reduce is not implemented in IE11
  15065. var vttLines = Object(id3["utf8ArrayToStr"])(new Uint8Array(vttByteArray)).trim().replace(re, '\n').split('\n');
  15066. var cueTime = '00:00.000';
  15067. var mpegTs = 0;
  15068. var localTime = 0;
  15069. var presentationTime = 0;
  15070. var cues = [];
  15071. var parsingError;
  15072. var inHeader = true;
  15073. var timestampMap = false; // let VTTCue = VTTCue || window.TextTrackCue;
  15074. // Create parser object using VTTCue with TextTrackCue fallback on certain browsers.
  15075. var parser = new vttparser();
  15076. parser.oncue = function (cue) {
  15077. // Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline.
  15078. var currCC = vttCCs[cc];
  15079. var cueOffset = vttCCs.ccOffset; // Update offsets for new discontinuities
  15080. if (currCC && currCC.new) {
  15081. if (localTime !== undefined) {
  15082. // When local time is provided, offset = discontinuity start time - local time
  15083. cueOffset = vttCCs.ccOffset = currCC.start;
  15084. } else {
  15085. calculateOffset(vttCCs, cc, presentationTime);
  15086. }
  15087. }
  15088. if (presentationTime) {
  15089. // If we have MPEGTS, offset = presentation time + discontinuity offset
  15090. cueOffset = presentationTime - vttCCs.presentationOffset;
  15091. }
  15092. if (timestampMap) {
  15093. cue.startTime += cueOffset - localTime;
  15094. cue.endTime += cueOffset - localTime;
  15095. } // Create a unique hash id for a cue based on start/end times and text.
  15096. // This helps timeline-controller to avoid showing repeated captions.
  15097. cue.id = hash(cue.startTime.toString()) + hash(cue.endTime.toString()) + hash(cue.text); // Fix encoding of special characters. TODO: Test with all sorts of weird characters.
  15098. cue.text = decodeURIComponent(encodeURIComponent(cue.text));
  15099. if (cue.endTime > 0) {
  15100. cues.push(cue);
  15101. }
  15102. };
  15103. parser.onparsingerror = function (e) {
  15104. parsingError = e;
  15105. };
  15106. parser.onflush = function () {
  15107. if (parsingError && errorCallBack) {
  15108. errorCallBack(parsingError);
  15109. return;
  15110. }
  15111. callBack(cues);
  15112. }; // Go through contents line by line.
  15113. vttLines.forEach(function (line) {
  15114. if (inHeader) {
  15115. // Look for X-TIMESTAMP-MAP in header.
  15116. if (startsWith(line, 'X-TIMESTAMP-MAP=')) {
  15117. // Once found, no more are allowed anyway, so stop searching.
  15118. inHeader = false;
  15119. timestampMap = true; // Extract LOCAL and MPEGTS.
  15120. line.substr(16).split(',').forEach(function (timestamp) {
  15121. if (startsWith(timestamp, 'LOCAL:')) {
  15122. cueTime = timestamp.substr(6);
  15123. } else if (startsWith(timestamp, 'MPEGTS:')) {
  15124. mpegTs = parseInt(timestamp.substr(7));
  15125. }
  15126. });
  15127. try {
  15128. // Calculate subtitle offset in milliseconds.
  15129. if (syncPTS + (vttCCs[cc].start * 90000 || 0) < 0) {
  15130. syncPTS += 8589934592;
  15131. } // Adjust MPEGTS by sync PTS.
  15132. mpegTs -= syncPTS; // Convert cue time to seconds
  15133. localTime = webvtt_parser_cueString2millis(cueTime) / 1000; // Convert MPEGTS to seconds from 90kHz.
  15134. presentationTime = mpegTs / 90000;
  15135. } catch (e) {
  15136. timestampMap = false;
  15137. parsingError = e;
  15138. } // Return without parsing X-TIMESTAMP-MAP line.
  15139. return;
  15140. } else if (line === '') {
  15141. inHeader = false;
  15142. }
  15143. } // Parse line by default.
  15144. parser.parse(line + '\n');
  15145. });
  15146. parser.flush();
  15147. }
  15148. };
  15149. /* harmony default export */ var webvtt_parser = (WebVTTParser);
  15150. // CONCATENATED MODULE: ./src/controller/timeline-controller.ts
  15151. function timeline_controller_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  15152. function timeline_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  15153. var timeline_controller_TimelineController = /*#__PURE__*/function (_EventHandler) {
  15154. timeline_controller_inheritsLoose(TimelineController, _EventHandler);
  15155. function TimelineController(hls) {
  15156. var _this;
  15157. _this = _EventHandler.call(this, hls, events["default"].MEDIA_ATTACHING, events["default"].MEDIA_DETACHING, events["default"].FRAG_PARSING_USERDATA, events["default"].FRAG_DECRYPTED, events["default"].MANIFEST_LOADING, events["default"].MANIFEST_LOADED, events["default"].FRAG_LOADED, events["default"].INIT_PTS_FOUND) || this;
  15158. _this.media = null;
  15159. _this.config = void 0;
  15160. _this.enabled = true;
  15161. _this.Cues = void 0;
  15162. _this.textTracks = [];
  15163. _this.tracks = [];
  15164. _this.initPTS = [];
  15165. _this.unparsedVttFrags = [];
  15166. _this.captionsTracks = {};
  15167. _this.nonNativeCaptionsTracks = {};
  15168. _this.captionsProperties = void 0;
  15169. _this.cea608Parser1 = void 0;
  15170. _this.cea608Parser2 = void 0;
  15171. _this.lastSn = -1;
  15172. _this.prevCC = -1;
  15173. _this.vttCCs = newVTTCCs();
  15174. _this.hls = hls;
  15175. _this.config = hls.config;
  15176. _this.Cues = hls.config.cueHandler;
  15177. _this.captionsProperties = {
  15178. textTrack1: {
  15179. label: _this.config.captionsTextTrack1Label,
  15180. languageCode: _this.config.captionsTextTrack1LanguageCode
  15181. },
  15182. textTrack2: {
  15183. label: _this.config.captionsTextTrack2Label,
  15184. languageCode: _this.config.captionsTextTrack2LanguageCode
  15185. },
  15186. textTrack3: {
  15187. label: _this.config.captionsTextTrack3Label,
  15188. languageCode: _this.config.captionsTextTrack3LanguageCode
  15189. },
  15190. textTrack4: {
  15191. label: _this.config.captionsTextTrack4Label,
  15192. languageCode: _this.config.captionsTextTrack4LanguageCode
  15193. }
  15194. };
  15195. if (_this.config.enableCEA708Captions) {
  15196. var channel1 = new OutputFilter(timeline_controller_assertThisInitialized(_this), 'textTrack1');
  15197. var channel2 = new OutputFilter(timeline_controller_assertThisInitialized(_this), 'textTrack2');
  15198. var channel3 = new OutputFilter(timeline_controller_assertThisInitialized(_this), 'textTrack3');
  15199. var channel4 = new OutputFilter(timeline_controller_assertThisInitialized(_this), 'textTrack4');
  15200. _this.cea608Parser1 = new cea_608_parser(1, channel1, channel2);
  15201. _this.cea608Parser2 = new cea_608_parser(3, channel3, channel4);
  15202. }
  15203. return _this;
  15204. }
  15205. var _proto = TimelineController.prototype;
  15206. _proto.addCues = function addCues(trackName, startTime, endTime, screen, cueRanges) {
  15207. // skip cues which overlap more than 50% with previously parsed time ranges
  15208. var merged = false;
  15209. for (var i = cueRanges.length; i--;) {
  15210. var cueRange = cueRanges[i];
  15211. var overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);
  15212. if (overlap >= 0) {
  15213. cueRange[0] = Math.min(cueRange[0], startTime);
  15214. cueRange[1] = Math.max(cueRange[1], endTime);
  15215. merged = true;
  15216. if (overlap / (endTime - startTime) > 0.5) {
  15217. return;
  15218. }
  15219. }
  15220. }
  15221. if (!merged) {
  15222. cueRanges.push([startTime, endTime]);
  15223. }
  15224. if (this.config.renderTextTracksNatively) {
  15225. this.Cues.newCue(this.captionsTracks[trackName], startTime, endTime, screen);
  15226. } else {
  15227. var cues = this.Cues.newCue(null, startTime, endTime, screen);
  15228. this.hls.trigger(events["default"].CUES_PARSED, {
  15229. type: 'captions',
  15230. cues: cues,
  15231. track: trackName
  15232. });
  15233. }
  15234. } // Triggered when an initial PTS is found; used for synchronisation of WebVTT.
  15235. ;
  15236. _proto.onInitPtsFound = function onInitPtsFound(data) {
  15237. var _this2 = this;
  15238. var frag = data.frag,
  15239. id = data.id,
  15240. initPTS = data.initPTS;
  15241. var unparsedVttFrags = this.unparsedVttFrags;
  15242. if (id === 'main') {
  15243. this.initPTS[frag.cc] = initPTS;
  15244. } // Due to asynchronous processing, initial PTS may arrive later than the first VTT fragments are loaded.
  15245. // Parse any unparsed fragments upon receiving the initial PTS.
  15246. if (unparsedVttFrags.length) {
  15247. this.unparsedVttFrags = [];
  15248. unparsedVttFrags.forEach(function (frag) {
  15249. _this2.onFragLoaded(frag);
  15250. });
  15251. }
  15252. };
  15253. _proto.getExistingTrack = function getExistingTrack(trackName) {
  15254. var media = this.media;
  15255. if (media) {
  15256. for (var i = 0; i < media.textTracks.length; i++) {
  15257. var textTrack = media.textTracks[i];
  15258. if (textTrack[trackName]) {
  15259. return textTrack;
  15260. }
  15261. }
  15262. }
  15263. return null;
  15264. };
  15265. _proto.createCaptionsTrack = function createCaptionsTrack(trackName) {
  15266. if (this.config.renderTextTracksNatively) {
  15267. this.createNativeTrack(trackName);
  15268. } else {
  15269. this.createNonNativeTrack(trackName);
  15270. }
  15271. };
  15272. _proto.createNativeTrack = function createNativeTrack(trackName) {
  15273. if (this.captionsTracks[trackName]) {
  15274. return;
  15275. }
  15276. var captionsProperties = this.captionsProperties,
  15277. captionsTracks = this.captionsTracks,
  15278. media = this.media;
  15279. var _captionsProperties$t = captionsProperties[trackName],
  15280. label = _captionsProperties$t.label,
  15281. languageCode = _captionsProperties$t.languageCode; // Enable reuse of existing text track.
  15282. var existingTrack = this.getExistingTrack(trackName);
  15283. if (!existingTrack) {
  15284. var textTrack = this.createTextTrack('captions', label, languageCode);
  15285. if (textTrack) {
  15286. // Set a special property on the track so we know it's managed by Hls.js
  15287. textTrack[trackName] = true;
  15288. captionsTracks[trackName] = textTrack;
  15289. }
  15290. } else {
  15291. captionsTracks[trackName] = existingTrack;
  15292. clearCurrentCues(captionsTracks[trackName]);
  15293. sendAddTrackEvent(captionsTracks[trackName], media);
  15294. }
  15295. };
  15296. _proto.createNonNativeTrack = function createNonNativeTrack(trackName) {
  15297. if (this.nonNativeCaptionsTracks[trackName]) {
  15298. return;
  15299. } // Create a list of a single track for the provider to consume
  15300. var trackProperties = this.captionsProperties[trackName];
  15301. if (!trackProperties) {
  15302. return;
  15303. }
  15304. var label = trackProperties.label;
  15305. var track = {
  15306. _id: trackName,
  15307. label: label,
  15308. kind: 'captions',
  15309. default: trackProperties.media ? !!trackProperties.media.default : false,
  15310. closedCaptions: trackProperties.media
  15311. };
  15312. this.nonNativeCaptionsTracks[trackName] = track;
  15313. this.hls.trigger(events["default"].NON_NATIVE_TEXT_TRACKS_FOUND, {
  15314. tracks: [track]
  15315. });
  15316. };
  15317. _proto.createTextTrack = function createTextTrack(kind, label, lang) {
  15318. var media = this.media;
  15319. if (!media) {
  15320. return;
  15321. }
  15322. return media.addTextTrack(kind, label, lang);
  15323. };
  15324. _proto.destroy = function destroy() {
  15325. _EventHandler.prototype.destroy.call(this);
  15326. };
  15327. _proto.onMediaAttaching = function onMediaAttaching(data) {
  15328. this.media = data.media;
  15329. this._cleanTracks();
  15330. };
  15331. _proto.onMediaDetaching = function onMediaDetaching() {
  15332. var captionsTracks = this.captionsTracks;
  15333. Object.keys(captionsTracks).forEach(function (trackName) {
  15334. clearCurrentCues(captionsTracks[trackName]);
  15335. delete captionsTracks[trackName];
  15336. });
  15337. this.nonNativeCaptionsTracks = {};
  15338. };
  15339. _proto.onManifestLoading = function onManifestLoading() {
  15340. this.lastSn = -1; // Detect discontiguity in fragment parsing
  15341. this.prevCC = -1;
  15342. this.vttCCs = newVTTCCs(); // Detect discontinuity in subtitle manifests
  15343. this._cleanTracks();
  15344. this.tracks = [];
  15345. this.captionsTracks = {};
  15346. this.nonNativeCaptionsTracks = {};
  15347. };
  15348. _proto._cleanTracks = function _cleanTracks() {
  15349. // clear outdated subtitles
  15350. var media = this.media;
  15351. if (!media) {
  15352. return;
  15353. }
  15354. var textTracks = media.textTracks;
  15355. if (textTracks) {
  15356. for (var i = 0; i < textTracks.length; i++) {
  15357. clearCurrentCues(textTracks[i]);
  15358. }
  15359. }
  15360. };
  15361. _proto.onManifestLoaded = function onManifestLoaded(data) {
  15362. var _this3 = this;
  15363. this.textTracks = [];
  15364. this.unparsedVttFrags = this.unparsedVttFrags || [];
  15365. this.initPTS = [];
  15366. if (this.cea608Parser1 && this.cea608Parser2) {
  15367. this.cea608Parser1.reset();
  15368. this.cea608Parser2.reset();
  15369. }
  15370. if (this.config.enableWebVTT) {
  15371. var tracks = data.subtitles || [];
  15372. var sameTracks = this.tracks && tracks && this.tracks.length === tracks.length;
  15373. this.tracks = data.subtitles || [];
  15374. if (this.config.renderTextTracksNatively) {
  15375. var inUseTracks = this.media ? this.media.textTracks : [];
  15376. this.tracks.forEach(function (track, index) {
  15377. var textTrack;
  15378. if (index < inUseTracks.length) {
  15379. var inUseTrack = null;
  15380. for (var i = 0; i < inUseTracks.length; i++) {
  15381. if (canReuseVttTextTrack(inUseTracks[i], track)) {
  15382. inUseTrack = inUseTracks[i];
  15383. break;
  15384. }
  15385. } // Reuse tracks with the same label, but do not reuse 608/708 tracks
  15386. if (inUseTrack) {
  15387. textTrack = inUseTrack;
  15388. }
  15389. }
  15390. if (!textTrack) {
  15391. textTrack = _this3.createTextTrack('subtitles', track.name, track.lang);
  15392. }
  15393. if (track.default) {
  15394. textTrack.mode = _this3.hls.subtitleDisplay ? 'showing' : 'hidden';
  15395. } else {
  15396. textTrack.mode = 'disabled';
  15397. }
  15398. _this3.textTracks.push(textTrack);
  15399. });
  15400. } else if (!sameTracks && this.tracks && this.tracks.length) {
  15401. // Create a list of tracks for the provider to consume
  15402. var tracksList = this.tracks.map(function (track) {
  15403. return {
  15404. label: track.name,
  15405. kind: track.type.toLowerCase(),
  15406. default: track.default,
  15407. subtitleTrack: track
  15408. };
  15409. });
  15410. this.hls.trigger(events["default"].NON_NATIVE_TEXT_TRACKS_FOUND, {
  15411. tracks: tracksList
  15412. });
  15413. }
  15414. }
  15415. if (this.config.enableCEA708Captions && data.captions) {
  15416. data.captions.forEach(function (captionsTrack) {
  15417. var instreamIdMatch = /(?:CC|SERVICE)([1-4])/.exec(captionsTrack.instreamId);
  15418. if (!instreamIdMatch) {
  15419. return;
  15420. }
  15421. var trackName = "textTrack" + instreamIdMatch[1];
  15422. var trackProperties = _this3.captionsProperties[trackName];
  15423. if (!trackProperties) {
  15424. return;
  15425. }
  15426. trackProperties.label = captionsTrack.name;
  15427. if (captionsTrack.lang) {
  15428. // optional attribute
  15429. trackProperties.languageCode = captionsTrack.lang;
  15430. }
  15431. trackProperties.media = captionsTrack;
  15432. });
  15433. }
  15434. };
  15435. _proto.onFragLoaded = function onFragLoaded(data) {
  15436. var frag = data.frag,
  15437. payload = data.payload;
  15438. var cea608Parser1 = this.cea608Parser1,
  15439. cea608Parser2 = this.cea608Parser2,
  15440. initPTS = this.initPTS,
  15441. lastSn = this.lastSn,
  15442. unparsedVttFrags = this.unparsedVttFrags;
  15443. if (frag.type === 'main') {
  15444. var sn = frag.sn; // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack
  15445. if (frag.sn !== lastSn + 1) {
  15446. if (cea608Parser1 && cea608Parser2) {
  15447. cea608Parser1.reset();
  15448. cea608Parser2.reset();
  15449. }
  15450. }
  15451. this.lastSn = sn;
  15452. } // eslint-disable-line brace-style
  15453. // If fragment is subtitle type, parse as WebVTT.
  15454. else if (frag.type === 'subtitle') {
  15455. if (payload.byteLength) {
  15456. // We need an initial synchronisation PTS. Store fragments as long as none has arrived.
  15457. if (!Object(number["isFiniteNumber"])(initPTS[frag.cc])) {
  15458. unparsedVttFrags.push(data);
  15459. if (initPTS.length) {
  15460. // finish unsuccessfully, otherwise the subtitle-stream-controller could be blocked from loading new frags.
  15461. this.hls.trigger(events["default"].SUBTITLE_FRAG_PROCESSED, {
  15462. success: false,
  15463. frag: frag
  15464. });
  15465. }
  15466. return;
  15467. }
  15468. var decryptData = frag.decryptdata; // If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait.
  15469. if (decryptData == null || decryptData.key == null || decryptData.method !== 'AES-128') {
  15470. this._parseVTTs(frag, payload);
  15471. }
  15472. } else {
  15473. // In case there is no payload, finish unsuccessfully.
  15474. this.hls.trigger(events["default"].SUBTITLE_FRAG_PROCESSED, {
  15475. success: false,
  15476. frag: frag
  15477. });
  15478. }
  15479. }
  15480. };
  15481. _proto._parseVTTs = function _parseVTTs(frag, payload) {
  15482. var _this4 = this;
  15483. var hls = this.hls,
  15484. prevCC = this.prevCC,
  15485. textTracks = this.textTracks,
  15486. vttCCs = this.vttCCs;
  15487. if (!vttCCs[frag.cc]) {
  15488. vttCCs[frag.cc] = {
  15489. start: frag.start,
  15490. prevCC: prevCC,
  15491. new: true
  15492. };
  15493. this.prevCC = frag.cc;
  15494. } // Parse the WebVTT file contents.
  15495. webvtt_parser.parse(payload, this.initPTS[frag.cc], vttCCs, frag.cc, function (cues) {
  15496. if (_this4.config.renderTextTracksNatively) {
  15497. var currentTrack = textTracks[frag.level]; // WebVTTParser.parse is an async method and if the currently selected text track mode is set to "disabled"
  15498. // before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null
  15499. // and trying to access getCueById method of cues will throw an exception
  15500. // Because we check if the mode is diabled, we can force check `cues` below. They can't be null.
  15501. if (currentTrack.mode === 'disabled') {
  15502. hls.trigger(events["default"].SUBTITLE_FRAG_PROCESSED, {
  15503. success: false,
  15504. frag: frag
  15505. });
  15506. return;
  15507. } // Add cues and trigger event with success true.
  15508. cues.forEach(function (cue) {
  15509. // Sometimes there are cue overlaps on segmented vtts so the same
  15510. // cue can appear more than once in different vtt files.
  15511. // This avoid showing duplicated cues with same timecode and text.
  15512. if (!currentTrack.cues.getCueById(cue.id)) {
  15513. try {
  15514. currentTrack.addCue(cue);
  15515. if (!currentTrack.cues.getCueById(cue.id)) {
  15516. throw new Error("addCue is failed for: " + cue);
  15517. }
  15518. } catch (err) {
  15519. logger["logger"].debug("Failed occurred on adding cues: " + err);
  15520. var textTrackCue = new window.TextTrackCue(cue.startTime, cue.endTime, cue.text);
  15521. textTrackCue.id = cue.id;
  15522. currentTrack.addCue(textTrackCue);
  15523. }
  15524. }
  15525. });
  15526. } else {
  15527. var trackId = _this4.tracks[frag.level].default ? 'default' : 'subtitles' + frag.level;
  15528. hls.trigger(events["default"].CUES_PARSED, {
  15529. type: 'subtitles',
  15530. cues: cues,
  15531. track: trackId
  15532. });
  15533. }
  15534. hls.trigger(events["default"].SUBTITLE_FRAG_PROCESSED, {
  15535. success: true,
  15536. frag: frag
  15537. });
  15538. }, function (e) {
  15539. // Something went wrong while parsing. Trigger event with success false.
  15540. logger["logger"].log("Failed to parse VTT cue: " + e);
  15541. hls.trigger(events["default"].SUBTITLE_FRAG_PROCESSED, {
  15542. success: false,
  15543. frag: frag
  15544. });
  15545. });
  15546. };
  15547. _proto.onFragDecrypted = function onFragDecrypted(data) {
  15548. var frag = data.frag,
  15549. payload = data.payload;
  15550. if (frag.type === 'subtitle') {
  15551. if (!Object(number["isFiniteNumber"])(this.initPTS[frag.cc])) {
  15552. this.unparsedVttFrags.push(data);
  15553. return;
  15554. }
  15555. this._parseVTTs(frag, payload);
  15556. }
  15557. };
  15558. _proto.onFragParsingUserdata = function onFragParsingUserdata(data) {
  15559. var cea608Parser1 = this.cea608Parser1,
  15560. cea608Parser2 = this.cea608Parser2;
  15561. if (!this.enabled || !(cea608Parser1 && cea608Parser2)) {
  15562. return;
  15563. } // If the event contains captions (found in the bytes property), push all bytes into the parser immediately
  15564. // It will create the proper timestamps based on the PTS value
  15565. for (var i = 0; i < data.samples.length; i++) {
  15566. var ccBytes = data.samples[i].bytes;
  15567. if (ccBytes) {
  15568. var ccdatas = this.extractCea608Data(ccBytes);
  15569. cea608Parser1.addData(data.samples[i].pts, ccdatas[0]);
  15570. cea608Parser2.addData(data.samples[i].pts, ccdatas[1]);
  15571. }
  15572. }
  15573. };
  15574. _proto.extractCea608Data = function extractCea608Data(byteArray) {
  15575. var count = byteArray[0] & 31;
  15576. var position = 2;
  15577. var actualCCBytes = [[], []];
  15578. for (var j = 0; j < count; j++) {
  15579. var tmpByte = byteArray[position++];
  15580. var ccbyte1 = 0x7F & byteArray[position++];
  15581. var ccbyte2 = 0x7F & byteArray[position++];
  15582. var ccValid = (4 & tmpByte) !== 0;
  15583. var ccType = 3 & tmpByte;
  15584. if (ccbyte1 === 0 && ccbyte2 === 0) {
  15585. continue;
  15586. }
  15587. if (ccValid) {
  15588. if (ccType === 0 || ccType === 1) {
  15589. actualCCBytes[ccType].push(ccbyte1);
  15590. actualCCBytes[ccType].push(ccbyte2);
  15591. }
  15592. }
  15593. }
  15594. return actualCCBytes;
  15595. };
  15596. return TimelineController;
  15597. }(event_handler);
  15598. function canReuseVttTextTrack(inUseTrack, manifestTrack) {
  15599. return inUseTrack && inUseTrack.label === manifestTrack.name && !(inUseTrack.textTrack1 || inUseTrack.textTrack2);
  15600. }
  15601. function intersection(x1, x2, y1, y2) {
  15602. return Math.min(x2, y2) - Math.max(x1, y1);
  15603. }
  15604. function newVTTCCs() {
  15605. return {
  15606. ccOffset: 0,
  15607. presentationOffset: 0,
  15608. 0: {
  15609. start: 0,
  15610. prevCC: -1,
  15611. new: false
  15612. }
  15613. };
  15614. }
  15615. /* harmony default export */ var timeline_controller = (timeline_controller_TimelineController);
  15616. // CONCATENATED MODULE: ./src/controller/subtitle-track-controller.js
  15617. function subtitle_track_controller_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  15618. function subtitle_track_controller_createClass(Constructor, protoProps, staticProps) { if (protoProps) subtitle_track_controller_defineProperties(Constructor.prototype, protoProps); if (staticProps) subtitle_track_controller_defineProperties(Constructor, staticProps); return Constructor; }
  15619. function subtitle_track_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  15620. var subtitle_track_controller_SubtitleTrackController = /*#__PURE__*/function (_EventHandler) {
  15621. subtitle_track_controller_inheritsLoose(SubtitleTrackController, _EventHandler);
  15622. function SubtitleTrackController(hls) {
  15623. var _this;
  15624. _this = _EventHandler.call(this, hls, events["default"].MEDIA_ATTACHED, events["default"].MEDIA_DETACHING, events["default"].MANIFEST_LOADED, events["default"].SUBTITLE_TRACK_LOADED) || this;
  15625. _this.tracks = [];
  15626. _this.trackId = -1;
  15627. _this.media = null;
  15628. _this.stopped = true;
  15629. /**
  15630. * @member {boolean} subtitleDisplay Enable/disable subtitle display rendering
  15631. */
  15632. _this.subtitleDisplay = true;
  15633. /**
  15634. * Keeps reference to a default track id when media has not been attached yet
  15635. * @member {number}
  15636. */
  15637. _this.queuedDefaultTrack = null;
  15638. return _this;
  15639. }
  15640. var _proto = SubtitleTrackController.prototype;
  15641. _proto.destroy = function destroy() {
  15642. event_handler.prototype.destroy.call(this);
  15643. } // Listen for subtitle track change, then extract the current track ID.
  15644. ;
  15645. _proto.onMediaAttached = function onMediaAttached(data) {
  15646. var _this2 = this;
  15647. this.media = data.media;
  15648. if (!this.media) {
  15649. return;
  15650. }
  15651. if (Object(number["isFiniteNumber"])(this.queuedDefaultTrack)) {
  15652. this.subtitleTrack = this.queuedDefaultTrack;
  15653. this.queuedDefaultTrack = null;
  15654. }
  15655. this.trackChangeListener = this._onTextTracksChanged.bind(this);
  15656. this.useTextTrackPolling = !(this.media.textTracks && 'onchange' in this.media.textTracks);
  15657. if (this.useTextTrackPolling) {
  15658. this.subtitlePollingInterval = setInterval(function () {
  15659. _this2.trackChangeListener();
  15660. }, 500);
  15661. } else {
  15662. this.media.textTracks.addEventListener('change', this.trackChangeListener);
  15663. }
  15664. };
  15665. _proto.onMediaDetaching = function onMediaDetaching() {
  15666. if (!this.media) {
  15667. return;
  15668. }
  15669. if (this.useTextTrackPolling) {
  15670. clearInterval(this.subtitlePollingInterval);
  15671. } else {
  15672. this.media.textTracks.removeEventListener('change', this.trackChangeListener);
  15673. }
  15674. if (Object(number["isFiniteNumber"])(this.subtitleTrack)) {
  15675. this.queuedDefaultTrack = this.subtitleTrack;
  15676. }
  15677. var textTracks = filterSubtitleTracks(this.media.textTracks); // Clear loaded cues on media detachment from tracks
  15678. textTracks.forEach(function (track) {
  15679. clearCurrentCues(track);
  15680. }); // Disable all subtitle tracks before detachment so when reattached only tracks in that content are enabled.
  15681. this.subtitleTrack = -1;
  15682. this.media = null;
  15683. } // Fired whenever a new manifest is loaded.
  15684. ;
  15685. _proto.onManifestLoaded = function onManifestLoaded(data) {
  15686. var _this3 = this;
  15687. var tracks = data.subtitles || [];
  15688. this.tracks = tracks;
  15689. this.hls.trigger(events["default"].SUBTITLE_TRACKS_UPDATED, {
  15690. subtitleTracks: tracks
  15691. }); // loop through available subtitle tracks and autoselect default if needed
  15692. // TODO: improve selection logic to handle forced, etc
  15693. tracks.forEach(function (track) {
  15694. if (track.default) {
  15695. // setting this.subtitleTrack will trigger internal logic
  15696. // if media has not been attached yet, it will fail
  15697. // we keep a reference to the default track id
  15698. // and we'll set subtitleTrack when onMediaAttached is triggered
  15699. if (_this3.media) {
  15700. _this3.subtitleTrack = track.id;
  15701. } else {
  15702. _this3.queuedDefaultTrack = track.id;
  15703. }
  15704. }
  15705. });
  15706. };
  15707. _proto.onSubtitleTrackLoaded = function onSubtitleTrackLoaded(data) {
  15708. var _this4 = this;
  15709. var id = data.id,
  15710. details = data.details;
  15711. var trackId = this.trackId,
  15712. tracks = this.tracks;
  15713. var currentTrack = tracks[trackId];
  15714. if (id >= tracks.length || id !== trackId || !currentTrack || this.stopped) {
  15715. this._clearReloadTimer();
  15716. return;
  15717. }
  15718. logger["logger"].log("subtitle track " + id + " loaded");
  15719. if (details.live) {
  15720. var reloadInterval = computeReloadInterval(currentTrack.details, details, data.stats.trequest);
  15721. logger["logger"].log("Reloading live subtitle playlist in " + reloadInterval + "ms");
  15722. this.timer = setTimeout(function () {
  15723. _this4._loadCurrentTrack();
  15724. }, reloadInterval);
  15725. } else {
  15726. this._clearReloadTimer();
  15727. }
  15728. };
  15729. _proto.startLoad = function startLoad() {
  15730. this.stopped = false;
  15731. this._loadCurrentTrack();
  15732. };
  15733. _proto.stopLoad = function stopLoad() {
  15734. this.stopped = true;
  15735. this._clearReloadTimer();
  15736. }
  15737. /** get alternate subtitle tracks list from playlist **/
  15738. ;
  15739. _proto._clearReloadTimer = function _clearReloadTimer() {
  15740. if (this.timer) {
  15741. clearTimeout(this.timer);
  15742. this.timer = null;
  15743. }
  15744. };
  15745. _proto._loadCurrentTrack = function _loadCurrentTrack() {
  15746. var trackId = this.trackId,
  15747. tracks = this.tracks,
  15748. hls = this.hls;
  15749. var currentTrack = tracks[trackId];
  15750. if (trackId < 0 || !currentTrack || currentTrack.details && !currentTrack.details.live) {
  15751. return;
  15752. }
  15753. logger["logger"].log("Loading subtitle track " + trackId);
  15754. hls.trigger(events["default"].SUBTITLE_TRACK_LOADING, {
  15755. url: currentTrack.url,
  15756. id: trackId
  15757. });
  15758. }
  15759. /**
  15760. * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.
  15761. * This operates on the DOM textTracks.
  15762. * A value of -1 will disable all subtitle tracks.
  15763. * @param newId - The id of the next track to enable
  15764. * @private
  15765. */
  15766. ;
  15767. _proto._toggleTrackModes = function _toggleTrackModes(newId) {
  15768. var media = this.media,
  15769. subtitleDisplay = this.subtitleDisplay,
  15770. trackId = this.trackId;
  15771. if (!media) {
  15772. return;
  15773. }
  15774. var textTracks = filterSubtitleTracks(media.textTracks);
  15775. if (newId === -1) {
  15776. [].slice.call(textTracks).forEach(function (track) {
  15777. track.mode = 'disabled';
  15778. });
  15779. } else {
  15780. var oldTrack = textTracks[trackId];
  15781. if (oldTrack) {
  15782. oldTrack.mode = 'disabled';
  15783. }
  15784. }
  15785. var nextTrack = textTracks[newId];
  15786. if (nextTrack) {
  15787. nextTrack.mode = subtitleDisplay ? 'showing' : 'hidden';
  15788. }
  15789. }
  15790. /**
  15791. * This method is responsible for validating the subtitle index and periodically reloading if live.
  15792. * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.
  15793. * @param newId - The id of the subtitle track to activate.
  15794. */
  15795. ;
  15796. _proto._setSubtitleTrackInternal = function _setSubtitleTrackInternal(newId) {
  15797. var hls = this.hls,
  15798. tracks = this.tracks;
  15799. if (!Object(number["isFiniteNumber"])(newId) || newId < -1 || newId >= tracks.length) {
  15800. return;
  15801. }
  15802. this.trackId = newId;
  15803. logger["logger"].log("Switching to subtitle track " + newId);
  15804. hls.trigger(events["default"].SUBTITLE_TRACK_SWITCH, {
  15805. id: newId
  15806. });
  15807. this._loadCurrentTrack();
  15808. };
  15809. _proto._onTextTracksChanged = function _onTextTracksChanged() {
  15810. // Media is undefined when switching streams via loadSource()
  15811. if (!this.media || !this.hls.config.renderTextTracksNatively) {
  15812. return;
  15813. }
  15814. var trackId = -1;
  15815. var tracks = filterSubtitleTracks(this.media.textTracks);
  15816. for (var id = 0; id < tracks.length; id++) {
  15817. if (tracks[id].mode === 'hidden') {
  15818. // Do not break in case there is a following track with showing.
  15819. trackId = id;
  15820. } else if (tracks[id].mode === 'showing') {
  15821. trackId = id;
  15822. break;
  15823. }
  15824. } // Setting current subtitleTrack will invoke code.
  15825. this.subtitleTrack = trackId;
  15826. };
  15827. subtitle_track_controller_createClass(SubtitleTrackController, [{
  15828. key: "subtitleTracks",
  15829. get: function get() {
  15830. return this.tracks;
  15831. }
  15832. /** get index of the selected subtitle track (index in subtitle track lists) **/
  15833. }, {
  15834. key: "subtitleTrack",
  15835. get: function get() {
  15836. return this.trackId;
  15837. }
  15838. /** select a subtitle track, based on its index in subtitle track lists**/
  15839. ,
  15840. set: function set(subtitleTrackId) {
  15841. if (this.trackId !== subtitleTrackId) {
  15842. this._toggleTrackModes(subtitleTrackId);
  15843. this._setSubtitleTrackInternal(subtitleTrackId);
  15844. }
  15845. }
  15846. }]);
  15847. return SubtitleTrackController;
  15848. }(event_handler);
  15849. function filterSubtitleTracks(textTrackList) {
  15850. var tracks = [];
  15851. for (var i = 0; i < textTrackList.length; i++) {
  15852. var track = textTrackList[i]; // Edge adds a track without a label; we don't want to use it
  15853. if (track.kind === 'subtitles' && track.label) {
  15854. tracks.push(textTrackList[i]);
  15855. }
  15856. }
  15857. return tracks;
  15858. }
  15859. /* harmony default export */ var subtitle_track_controller = (subtitle_track_controller_SubtitleTrackController);
  15860. // EXTERNAL MODULE: ./src/crypt/decrypter.js + 3 modules
  15861. var decrypter = __webpack_require__("./src/crypt/decrypter.js");
  15862. // CONCATENATED MODULE: ./src/controller/subtitle-stream-controller.js
  15863. function subtitle_stream_controller_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  15864. function subtitle_stream_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  15865. /**
  15866. * @class SubtitleStreamController
  15867. */
  15868. var subtitle_stream_controller_window = window,
  15869. subtitle_stream_controller_performance = subtitle_stream_controller_window.performance;
  15870. var subtitle_stream_controller_TICK_INTERVAL = 500; // how often to tick in ms
  15871. var subtitle_stream_controller_SubtitleStreamController = /*#__PURE__*/function (_BaseStreamController) {
  15872. subtitle_stream_controller_inheritsLoose(SubtitleStreamController, _BaseStreamController);
  15873. function SubtitleStreamController(hls, fragmentTracker) {
  15874. var _this;
  15875. _this = _BaseStreamController.call(this, hls, events["default"].MEDIA_ATTACHED, events["default"].MEDIA_DETACHING, events["default"].ERROR, events["default"].KEY_LOADED, events["default"].FRAG_LOADED, events["default"].SUBTITLE_TRACKS_UPDATED, events["default"].SUBTITLE_TRACK_SWITCH, events["default"].SUBTITLE_TRACK_LOADED, events["default"].SUBTITLE_FRAG_PROCESSED, events["default"].LEVEL_UPDATED) || this;
  15876. _this.fragmentTracker = fragmentTracker;
  15877. _this.config = hls.config;
  15878. _this.state = State.STOPPED;
  15879. _this.tracks = [];
  15880. _this.tracksBuffered = [];
  15881. _this.currentTrackId = -1;
  15882. _this.decrypter = new decrypter["default"](hls, hls.config); // lastAVStart stores the time in seconds for the start time of a level load
  15883. _this.lastAVStart = 0;
  15884. _this._onMediaSeeking = _this.onMediaSeeking.bind(subtitle_stream_controller_assertThisInitialized(_this));
  15885. return _this;
  15886. }
  15887. var _proto = SubtitleStreamController.prototype;
  15888. _proto.startLoad = function startLoad() {
  15889. this.stopLoad();
  15890. this.state = State.IDLE; // Check if we already have a track with necessary details to load fragments
  15891. var currentTrack = this.tracks[this.currentTrackId];
  15892. if (currentTrack && currentTrack.details) {
  15893. this.setInterval(subtitle_stream_controller_TICK_INTERVAL);
  15894. this.tick();
  15895. }
  15896. };
  15897. _proto.onSubtitleFragProcessed = function onSubtitleFragProcessed(data) {
  15898. var frag = data.frag,
  15899. success = data.success;
  15900. this.fragPrevious = frag;
  15901. this.state = State.IDLE;
  15902. if (!success) {
  15903. return;
  15904. }
  15905. var buffered = this.tracksBuffered[this.currentTrackId];
  15906. if (!buffered) {
  15907. return;
  15908. } // Create/update a buffered array matching the interface used by BufferHelper.bufferedInfo
  15909. // so we can re-use the logic used to detect how much have been buffered
  15910. var timeRange;
  15911. var fragStart = frag.start;
  15912. for (var i = 0; i < buffered.length; i++) {
  15913. if (fragStart >= buffered[i].start && fragStart <= buffered[i].end) {
  15914. timeRange = buffered[i];
  15915. break;
  15916. }
  15917. }
  15918. var fragEnd = frag.start + frag.duration;
  15919. if (timeRange) {
  15920. timeRange.end = fragEnd;
  15921. } else {
  15922. timeRange = {
  15923. start: fragStart,
  15924. end: fragEnd
  15925. };
  15926. buffered.push(timeRange);
  15927. }
  15928. };
  15929. _proto.onMediaAttached = function onMediaAttached(_ref) {
  15930. var media = _ref.media;
  15931. this.media = media;
  15932. media.addEventListener('seeking', this._onMediaSeeking);
  15933. this.state = State.IDLE;
  15934. };
  15935. _proto.onMediaDetaching = function onMediaDetaching() {
  15936. var _this2 = this;
  15937. if (!this.media) {
  15938. return;
  15939. }
  15940. this.media.removeEventListener('seeking', this._onMediaSeeking);
  15941. this.fragmentTracker.removeAllFragments();
  15942. this.currentTrackId = -1;
  15943. this.tracks.forEach(function (track) {
  15944. _this2.tracksBuffered[track.id] = [];
  15945. });
  15946. this.media = null;
  15947. this.state = State.STOPPED;
  15948. } // If something goes wrong, proceed to next frag, if we were processing one.
  15949. ;
  15950. _proto.onError = function onError(data) {
  15951. var frag = data.frag; // don't handle error not related to subtitle fragment
  15952. if (!frag || frag.type !== 'subtitle') {
  15953. return;
  15954. }
  15955. if (this.fragCurrent && this.fragCurrent.loader) {
  15956. this.fragCurrent.loader.abort();
  15957. }
  15958. this.state = State.IDLE;
  15959. } // Got all new subtitle tracks.
  15960. ;
  15961. _proto.onSubtitleTracksUpdated = function onSubtitleTracksUpdated(data) {
  15962. var _this3 = this;
  15963. logger["logger"].log('subtitle tracks updated');
  15964. this.tracksBuffered = [];
  15965. this.tracks = data.subtitleTracks;
  15966. this.tracks.forEach(function (track) {
  15967. _this3.tracksBuffered[track.id] = [];
  15968. });
  15969. };
  15970. _proto.onSubtitleTrackSwitch = function onSubtitleTrackSwitch(data) {
  15971. this.currentTrackId = data.id;
  15972. if (!this.tracks || !this.tracks.length || this.currentTrackId === -1) {
  15973. this.clearInterval();
  15974. return;
  15975. } // Check if track has the necessary details to load fragments
  15976. var currentTrack = this.tracks[this.currentTrackId];
  15977. if (currentTrack && currentTrack.details) {
  15978. this.setInterval(subtitle_stream_controller_TICK_INTERVAL);
  15979. }
  15980. } // Got a new set of subtitle fragments.
  15981. ;
  15982. _proto.onSubtitleTrackLoaded = function onSubtitleTrackLoaded(data) {
  15983. var id = data.id,
  15984. details = data.details;
  15985. var currentTrackId = this.currentTrackId,
  15986. tracks = this.tracks;
  15987. var currentTrack = tracks[currentTrackId];
  15988. if (id >= tracks.length || id !== currentTrackId || !currentTrack) {
  15989. return;
  15990. }
  15991. if (details.live) {
  15992. mergeSubtitlePlaylists(currentTrack.details, details, this.lastAVStart);
  15993. }
  15994. currentTrack.details = details;
  15995. this.setInterval(subtitle_stream_controller_TICK_INTERVAL);
  15996. };
  15997. _proto.onKeyLoaded = function onKeyLoaded() {
  15998. if (this.state === State.KEY_LOADING) {
  15999. this.state = State.IDLE;
  16000. }
  16001. };
  16002. _proto.onFragLoaded = function onFragLoaded(data) {
  16003. var fragCurrent = this.fragCurrent;
  16004. var decryptData = data.frag.decryptdata;
  16005. var fragLoaded = data.frag;
  16006. var hls = this.hls;
  16007. if (this.state === State.FRAG_LOADING && fragCurrent && data.frag.type === 'subtitle' && fragCurrent.sn === data.frag.sn) {
  16008. // check to see if the payload needs to be decrypted
  16009. if (data.payload.byteLength > 0 && decryptData && decryptData.key && decryptData.method === 'AES-128') {
  16010. var startTime = subtitle_stream_controller_performance.now(); // decrypt the subtitles
  16011. this.decrypter.decrypt(data.payload, decryptData.key.buffer, decryptData.iv.buffer, function (decryptedData) {
  16012. var endTime = subtitle_stream_controller_performance.now();
  16013. hls.trigger(events["default"].FRAG_DECRYPTED, {
  16014. frag: fragLoaded,
  16015. payload: decryptedData,
  16016. stats: {
  16017. tstart: startTime,
  16018. tdecrypt: endTime
  16019. }
  16020. });
  16021. });
  16022. }
  16023. }
  16024. };
  16025. _proto.onLevelUpdated = function onLevelUpdated(_ref2) {
  16026. var details = _ref2.details;
  16027. var frags = details.fragments;
  16028. this.lastAVStart = frags.length ? frags[0].start : 0;
  16029. };
  16030. _proto.doTick = function doTick() {
  16031. if (!this.media) {
  16032. this.state = State.IDLE;
  16033. return;
  16034. }
  16035. switch (this.state) {
  16036. case State.IDLE:
  16037. {
  16038. var config = this.config,
  16039. currentTrackId = this.currentTrackId,
  16040. fragmentTracker = this.fragmentTracker,
  16041. media = this.media,
  16042. tracks = this.tracks;
  16043. if (!tracks || !tracks[currentTrackId] || !tracks[currentTrackId].details) {
  16044. break;
  16045. }
  16046. var maxBufferHole = config.maxBufferHole,
  16047. maxFragLookUpTolerance = config.maxFragLookUpTolerance;
  16048. var maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength);
  16049. var bufferedInfo = BufferHelper.bufferedInfo(this._getBuffered(), media.currentTime, maxBufferHole);
  16050. var bufferEnd = bufferedInfo.end,
  16051. bufferLen = bufferedInfo.len;
  16052. var trackDetails = tracks[currentTrackId].details;
  16053. var fragments = trackDetails.fragments;
  16054. var fragLen = fragments.length;
  16055. var end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration;
  16056. if (bufferLen > maxConfigBuffer) {
  16057. return;
  16058. }
  16059. var foundFrag;
  16060. var fragPrevious = this.fragPrevious;
  16061. if (bufferEnd < end) {
  16062. if (fragPrevious && trackDetails.hasProgramDateTime) {
  16063. foundFrag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, maxFragLookUpTolerance);
  16064. }
  16065. if (!foundFrag) {
  16066. foundFrag = findFragmentByPTS(fragPrevious, fragments, bufferEnd, maxFragLookUpTolerance);
  16067. }
  16068. } else {
  16069. foundFrag = fragments[fragLen - 1];
  16070. }
  16071. if (foundFrag && foundFrag.encrypted) {
  16072. logger["logger"].log("Loading key for " + foundFrag.sn);
  16073. this.state = State.KEY_LOADING;
  16074. this.hls.trigger(events["default"].KEY_LOADING, {
  16075. frag: foundFrag
  16076. });
  16077. } else if (foundFrag && fragmentTracker.getState(foundFrag) === FragmentState.NOT_LOADED) {
  16078. // only load if fragment is not loaded
  16079. this.fragCurrent = foundFrag;
  16080. this.state = State.FRAG_LOADING;
  16081. this.hls.trigger(events["default"].FRAG_LOADING, {
  16082. frag: foundFrag
  16083. });
  16084. }
  16085. }
  16086. }
  16087. };
  16088. _proto.stopLoad = function stopLoad() {
  16089. this.lastAVStart = 0;
  16090. this.fragPrevious = null;
  16091. _BaseStreamController.prototype.stopLoad.call(this);
  16092. };
  16093. _proto._getBuffered = function _getBuffered() {
  16094. return this.tracksBuffered[this.currentTrackId] || [];
  16095. };
  16096. _proto.onMediaSeeking = function onMediaSeeking() {
  16097. if (this.fragCurrent) {
  16098. var currentTime = this.media ? this.media.currentTime : 0;
  16099. var tolerance = this.config.maxFragLookUpTolerance;
  16100. var fragStartOffset = this.fragCurrent.start - tolerance;
  16101. var fragEndOffset = this.fragCurrent.start + this.fragCurrent.duration + tolerance; // check if position will be out of currently loaded frag range after seeking : if out, cancel frag load, if in, don't do anything
  16102. if (currentTime < fragStartOffset || currentTime > fragEndOffset) {
  16103. if (this.fragCurrent.loader) {
  16104. this.fragCurrent.loader.abort();
  16105. }
  16106. this.fragmentTracker.removeFragment(this.fragCurrent);
  16107. this.fragCurrent = null;
  16108. this.fragPrevious = null; // switch to IDLE state to load new fragment
  16109. this.state = State.IDLE; // speed up things
  16110. this.tick();
  16111. }
  16112. }
  16113. };
  16114. return SubtitleStreamController;
  16115. }(base_stream_controller_BaseStreamController);
  16116. // CONCATENATED MODULE: ./src/utils/mediakeys-helper.ts
  16117. /**
  16118. * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess
  16119. */
  16120. var KeySystems;
  16121. (function (KeySystems) {
  16122. KeySystems["WIDEVINE"] = "com.widevine.alpha";
  16123. KeySystems["PLAYREADY"] = "com.microsoft.playready";
  16124. })(KeySystems || (KeySystems = {}));
  16125. var requestMediaKeySystemAccess = function () {
  16126. if (typeof window !== 'undefined' && window.navigator && window.navigator.requestMediaKeySystemAccess) {
  16127. return window.navigator.requestMediaKeySystemAccess.bind(window.navigator);
  16128. } else {
  16129. return null;
  16130. }
  16131. }();
  16132. // CONCATENATED MODULE: ./src/controller/eme-controller.ts
  16133. function eme_controller_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  16134. function eme_controller_createClass(Constructor, protoProps, staticProps) { if (protoProps) eme_controller_defineProperties(Constructor.prototype, protoProps); if (staticProps) eme_controller_defineProperties(Constructor, staticProps); return Constructor; }
  16135. function eme_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  16136. /**
  16137. * @author Stephan Hesse <disparat@gmail.com> | <tchakabam@gmail.com>
  16138. *
  16139. * DRM support for Hls.js
  16140. */
  16141. var MAX_LICENSE_REQUEST_FAILURES = 3;
  16142. /**
  16143. * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration
  16144. * @param {Array<string>} audioCodecs List of required audio codecs to support
  16145. * @param {Array<string>} videoCodecs List of required video codecs to support
  16146. * @param {object} drmSystemOptions Optional parameters/requirements for the key-system
  16147. * @returns {Array<MediaSystemConfiguration>} An array of supported configurations
  16148. */
  16149. var createWidevineMediaKeySystemConfigurations = function createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs, drmSystemOptions) {
  16150. /* jshint ignore:line */
  16151. var baseConfig = {
  16152. // initDataTypes: ['keyids', 'mp4'],
  16153. // label: "",
  16154. // persistentState: "not-allowed", // or "required" ?
  16155. // distinctiveIdentifier: "not-allowed", // or "required" ?
  16156. // sessionTypes: ['temporary'],
  16157. audioCapabilities: [],
  16158. // { contentType: 'audio/mp4; codecs="mp4a.40.2"' }
  16159. videoCapabilities: [] // { contentType: 'video/mp4; codecs="avc1.42E01E"' }
  16160. };
  16161. audioCodecs.forEach(function (codec) {
  16162. baseConfig.audioCapabilities.push({
  16163. contentType: "audio/mp4; codecs=\"" + codec + "\"",
  16164. robustness: drmSystemOptions.audioRobustness || ''
  16165. });
  16166. });
  16167. videoCodecs.forEach(function (codec) {
  16168. baseConfig.videoCapabilities.push({
  16169. contentType: "video/mp4; codecs=\"" + codec + "\"",
  16170. robustness: drmSystemOptions.videoRobustness || ''
  16171. });
  16172. });
  16173. return [baseConfig];
  16174. };
  16175. /**
  16176. * The idea here is to handle key-system (and their respective platforms) specific configuration differences
  16177. * in order to work with the local requestMediaKeySystemAccess method.
  16178. *
  16179. * We can also rule-out platform-related key-system support at this point by throwing an error.
  16180. *
  16181. * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum
  16182. * @param {Array<string>} audioCodecs List of required audio codecs to support
  16183. * @param {Array<string>} videoCodecs List of required video codecs to support
  16184. * @throws will throw an error if a unknown key system is passed
  16185. * @returns {Array<MediaSystemConfiguration>} A non-empty Array of MediaKeySystemConfiguration objects
  16186. */
  16187. var eme_controller_getSupportedMediaKeySystemConfigurations = function getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, drmSystemOptions) {
  16188. switch (keySystem) {
  16189. case KeySystems.WIDEVINE:
  16190. return createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs, drmSystemOptions);
  16191. default:
  16192. throw new Error("Unknown key-system: " + keySystem);
  16193. }
  16194. };
  16195. /**
  16196. * Controller to deal with encrypted media extensions (EME)
  16197. * @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API
  16198. *
  16199. * @class
  16200. * @constructor
  16201. */
  16202. var eme_controller_EMEController = /*#__PURE__*/function (_EventHandler) {
  16203. eme_controller_inheritsLoose(EMEController, _EventHandler);
  16204. /**
  16205. * @constructs
  16206. * @param {Hls} hls Our Hls.js instance
  16207. */
  16208. function EMEController(hls) {
  16209. var _this;
  16210. _this = _EventHandler.call(this, hls, events["default"].MEDIA_ATTACHED, events["default"].MEDIA_DETACHED, events["default"].MANIFEST_PARSED) || this;
  16211. _this._widevineLicenseUrl = void 0;
  16212. _this._licenseXhrSetup = void 0;
  16213. _this._emeEnabled = void 0;
  16214. _this._requestMediaKeySystemAccess = void 0;
  16215. _this._drmSystemOptions = void 0;
  16216. _this._config = void 0;
  16217. _this._mediaKeysList = [];
  16218. _this._media = null;
  16219. _this._hasSetMediaKeys = false;
  16220. _this._requestLicenseFailureCount = 0;
  16221. _this.mediaKeysPromise = null;
  16222. _this._onMediaEncrypted = function (e) {
  16223. logger["logger"].log("Media is encrypted using \"" + e.initDataType + "\" init data type");
  16224. if (!_this.mediaKeysPromise) {
  16225. logger["logger"].error('Fatal: Media is encrypted but no CDM access or no keys have been requested');
  16226. _this.hls.trigger(events["default"].ERROR, {
  16227. type: errors["ErrorTypes"].KEY_SYSTEM_ERROR,
  16228. details: errors["ErrorDetails"].KEY_SYSTEM_NO_KEYS,
  16229. fatal: true
  16230. });
  16231. return;
  16232. }
  16233. var finallySetKeyAndStartSession = function finallySetKeyAndStartSession(mediaKeys) {
  16234. if (!_this._media) {
  16235. return;
  16236. }
  16237. _this._attemptSetMediaKeys(mediaKeys);
  16238. _this._generateRequestWithPreferredKeySession(e.initDataType, e.initData);
  16239. }; // Could use `Promise.finally` but some Promise polyfills are missing it
  16240. _this.mediaKeysPromise.then(finallySetKeyAndStartSession).catch(finallySetKeyAndStartSession);
  16241. };
  16242. _this._config = hls.config;
  16243. _this._widevineLicenseUrl = _this._config.widevineLicenseUrl;
  16244. _this._licenseXhrSetup = _this._config.licenseXhrSetup;
  16245. _this._emeEnabled = _this._config.emeEnabled;
  16246. _this._requestMediaKeySystemAccess = _this._config.requestMediaKeySystemAccessFunc;
  16247. _this._drmSystemOptions = hls.config.drmSystemOptions;
  16248. return _this;
  16249. }
  16250. /**
  16251. * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum
  16252. * @returns {string} License server URL for key-system (if any configured, otherwise causes error)
  16253. * @throws if a unsupported keysystem is passed
  16254. */
  16255. var _proto = EMEController.prototype;
  16256. _proto.getLicenseServerUrl = function getLicenseServerUrl(keySystem) {
  16257. switch (keySystem) {
  16258. case KeySystems.WIDEVINE:
  16259. if (!this._widevineLicenseUrl) {
  16260. break;
  16261. }
  16262. return this._widevineLicenseUrl;
  16263. }
  16264. throw new Error("no license server URL configured for key-system \"" + keySystem + "\"");
  16265. }
  16266. /**
  16267. * Requests access object and adds it to our list upon success
  16268. * @private
  16269. * @param {string} keySystem System ID (see `KeySystems`)
  16270. * @param {Array<string>} audioCodecs List of required audio codecs to support
  16271. * @param {Array<string>} videoCodecs List of required video codecs to support
  16272. * @throws When a unsupported KeySystem is passed
  16273. */
  16274. ;
  16275. _proto._attemptKeySystemAccess = function _attemptKeySystemAccess(keySystem, audioCodecs, videoCodecs) {
  16276. var _this2 = this;
  16277. // This can throw, but is caught in event handler callpath
  16278. var mediaKeySystemConfigs = eme_controller_getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, this._drmSystemOptions);
  16279. logger["logger"].log('Requesting encrypted media key-system access'); // expecting interface like window.navigator.requestMediaKeySystemAccess
  16280. var keySystemAccessPromise = this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs);
  16281. this.mediaKeysPromise = keySystemAccessPromise.then(function (mediaKeySystemAccess) {
  16282. return _this2._onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess);
  16283. });
  16284. keySystemAccessPromise.catch(function (err) {
  16285. logger["logger"].error("Failed to obtain key-system \"" + keySystem + "\" access:", err);
  16286. });
  16287. };
  16288. /**
  16289. * Handles obtaining access to a key-system
  16290. * @private
  16291. * @param {string} keySystem
  16292. * @param {MediaKeySystemAccess} mediaKeySystemAccess https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemAccess
  16293. */
  16294. _proto._onMediaKeySystemAccessObtained = function _onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess) {
  16295. var _this3 = this;
  16296. logger["logger"].log("Access for key-system \"" + keySystem + "\" obtained");
  16297. var mediaKeysListItem = {
  16298. mediaKeysSessionInitialized: false,
  16299. mediaKeySystemAccess: mediaKeySystemAccess,
  16300. mediaKeySystemDomain: keySystem
  16301. };
  16302. this._mediaKeysList.push(mediaKeysListItem);
  16303. var mediaKeysPromise = Promise.resolve().then(function () {
  16304. return mediaKeySystemAccess.createMediaKeys();
  16305. }).then(function (mediaKeys) {
  16306. mediaKeysListItem.mediaKeys = mediaKeys;
  16307. logger["logger"].log("Media-keys created for key-system \"" + keySystem + "\"");
  16308. _this3._onMediaKeysCreated();
  16309. return mediaKeys;
  16310. });
  16311. mediaKeysPromise.catch(function (err) {
  16312. logger["logger"].error('Failed to create media-keys:', err);
  16313. });
  16314. return mediaKeysPromise;
  16315. }
  16316. /**
  16317. * Handles key-creation (represents access to CDM). We are going to create key-sessions upon this
  16318. * for all existing keys where no session exists yet.
  16319. *
  16320. * @private
  16321. */
  16322. ;
  16323. _proto._onMediaKeysCreated = function _onMediaKeysCreated() {
  16324. var _this4 = this;
  16325. // check for all key-list items if a session exists, otherwise, create one
  16326. this._mediaKeysList.forEach(function (mediaKeysListItem) {
  16327. if (!mediaKeysListItem.mediaKeysSession) {
  16328. // mediaKeys is definitely initialized here
  16329. mediaKeysListItem.mediaKeysSession = mediaKeysListItem.mediaKeys.createSession();
  16330. _this4._onNewMediaKeySession(mediaKeysListItem.mediaKeysSession);
  16331. }
  16332. });
  16333. }
  16334. /**
  16335. * @private
  16336. * @param {*} keySession
  16337. */
  16338. ;
  16339. _proto._onNewMediaKeySession = function _onNewMediaKeySession(keySession) {
  16340. var _this5 = this;
  16341. logger["logger"].log("New key-system session " + keySession.sessionId);
  16342. keySession.addEventListener('message', function (event) {
  16343. _this5._onKeySessionMessage(keySession, event.message);
  16344. }, false);
  16345. }
  16346. /**
  16347. * @private
  16348. * @param {MediaKeySession} keySession
  16349. * @param {ArrayBuffer} message
  16350. */
  16351. ;
  16352. _proto._onKeySessionMessage = function _onKeySessionMessage(keySession, message) {
  16353. logger["logger"].log('Got EME message event, creating license request');
  16354. this._requestLicense(message, function (data) {
  16355. logger["logger"].log("Received license data (length: " + (data ? data.byteLength : data) + "), updating key-session");
  16356. keySession.update(data);
  16357. });
  16358. }
  16359. /**
  16360. * @private
  16361. * @param e {MediaEncryptedEvent}
  16362. */
  16363. ;
  16364. /**
  16365. * @private
  16366. */
  16367. _proto._attemptSetMediaKeys = function _attemptSetMediaKeys(mediaKeys) {
  16368. if (!this._media) {
  16369. throw new Error('Attempted to set mediaKeys without first attaching a media element');
  16370. }
  16371. if (!this._hasSetMediaKeys) {
  16372. // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?
  16373. var keysListItem = this._mediaKeysList[0];
  16374. if (!keysListItem || !keysListItem.mediaKeys) {
  16375. logger["logger"].error('Fatal: Media is encrypted but no CDM access or no keys have been obtained yet');
  16376. this.hls.trigger(events["default"].ERROR, {
  16377. type: errors["ErrorTypes"].KEY_SYSTEM_ERROR,
  16378. details: errors["ErrorDetails"].KEY_SYSTEM_NO_KEYS,
  16379. fatal: true
  16380. });
  16381. return;
  16382. }
  16383. logger["logger"].log('Setting keys for encrypted media');
  16384. this._media.setMediaKeys(keysListItem.mediaKeys);
  16385. this._hasSetMediaKeys = true;
  16386. }
  16387. }
  16388. /**
  16389. * @private
  16390. */
  16391. ;
  16392. _proto._generateRequestWithPreferredKeySession = function _generateRequestWithPreferredKeySession(initDataType, initData) {
  16393. var _this6 = this;
  16394. // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?
  16395. var keysListItem = this._mediaKeysList[0];
  16396. if (!keysListItem) {
  16397. logger["logger"].error('Fatal: Media is encrypted but not any key-system access has been obtained yet');
  16398. this.hls.trigger(events["default"].ERROR, {
  16399. type: errors["ErrorTypes"].KEY_SYSTEM_ERROR,
  16400. details: errors["ErrorDetails"].KEY_SYSTEM_NO_ACCESS,
  16401. fatal: true
  16402. });
  16403. return;
  16404. }
  16405. if (keysListItem.mediaKeysSessionInitialized) {
  16406. logger["logger"].warn('Key-Session already initialized but requested again');
  16407. return;
  16408. }
  16409. var keySession = keysListItem.mediaKeysSession;
  16410. if (!keySession) {
  16411. logger["logger"].error('Fatal: Media is encrypted but no key-session existing');
  16412. this.hls.trigger(events["default"].ERROR, {
  16413. type: errors["ErrorTypes"].KEY_SYSTEM_ERROR,
  16414. details: errors["ErrorDetails"].KEY_SYSTEM_NO_SESSION,
  16415. fatal: true
  16416. });
  16417. return;
  16418. } // initData is null if the media is not CORS-same-origin
  16419. if (!initData) {
  16420. logger["logger"].warn('Fatal: initData required for generating a key session is null');
  16421. this.hls.trigger(events["default"].ERROR, {
  16422. type: errors["ErrorTypes"].KEY_SYSTEM_ERROR,
  16423. details: errors["ErrorDetails"].KEY_SYSTEM_NO_INIT_DATA,
  16424. fatal: true
  16425. });
  16426. return;
  16427. }
  16428. logger["logger"].log("Generating key-session request for \"" + initDataType + "\" init data type");
  16429. keysListItem.mediaKeysSessionInitialized = true;
  16430. keySession.generateRequest(initDataType, initData).then(function () {
  16431. logger["logger"].debug('Key-session generation succeeded');
  16432. }).catch(function (err) {
  16433. logger["logger"].error('Error generating key-session request:', err);
  16434. _this6.hls.trigger(events["default"].ERROR, {
  16435. type: errors["ErrorTypes"].KEY_SYSTEM_ERROR,
  16436. details: errors["ErrorDetails"].KEY_SYSTEM_NO_SESSION,
  16437. fatal: false
  16438. });
  16439. });
  16440. }
  16441. /**
  16442. * @private
  16443. * @param {string} url License server URL
  16444. * @param {ArrayBuffer} keyMessage Message data issued by key-system
  16445. * @param {function} callback Called when XHR has succeeded
  16446. * @returns {XMLHttpRequest} Unsent (but opened state) XHR object
  16447. * @throws if XMLHttpRequest construction failed
  16448. */
  16449. ;
  16450. _proto._createLicenseXhr = function _createLicenseXhr(url, keyMessage, callback) {
  16451. var xhr = new XMLHttpRequest();
  16452. var licenseXhrSetup = this._licenseXhrSetup;
  16453. try {
  16454. if (licenseXhrSetup) {
  16455. try {
  16456. licenseXhrSetup(xhr, url);
  16457. } catch (e) {
  16458. // let's try to open before running setup
  16459. xhr.open('POST', url, true);
  16460. licenseXhrSetup(xhr, url);
  16461. }
  16462. } // if licenseXhrSetup did not yet call open, let's do it now
  16463. if (!xhr.readyState) {
  16464. xhr.open('POST', url, true);
  16465. }
  16466. } catch (e) {
  16467. // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
  16468. throw new Error("issue setting up KeySystem license XHR " + e);
  16469. } // Because we set responseType to ArrayBuffer here, callback is typed as handling only array buffers
  16470. xhr.responseType = 'arraybuffer';
  16471. xhr.onreadystatechange = this._onLicenseRequestReadyStageChange.bind(this, xhr, url, keyMessage, callback);
  16472. return xhr;
  16473. }
  16474. /**
  16475. * @private
  16476. * @param {XMLHttpRequest} xhr
  16477. * @param {string} url License server URL
  16478. * @param {ArrayBuffer} keyMessage Message data issued by key-system
  16479. * @param {function} callback Called when XHR has succeeded
  16480. */
  16481. ;
  16482. _proto._onLicenseRequestReadyStageChange = function _onLicenseRequestReadyStageChange(xhr, url, keyMessage, callback) {
  16483. switch (xhr.readyState) {
  16484. case 4:
  16485. if (xhr.status === 200) {
  16486. this._requestLicenseFailureCount = 0;
  16487. logger["logger"].log('License request succeeded');
  16488. if (xhr.responseType !== 'arraybuffer') {
  16489. logger["logger"].warn('xhr response type was not set to the expected arraybuffer for license request');
  16490. }
  16491. callback(xhr.response);
  16492. } else {
  16493. logger["logger"].error("License Request XHR failed (" + url + "). Status: " + xhr.status + " (" + xhr.statusText + ")");
  16494. this._requestLicenseFailureCount++;
  16495. if (this._requestLicenseFailureCount > MAX_LICENSE_REQUEST_FAILURES) {
  16496. this.hls.trigger(events["default"].ERROR, {
  16497. type: errors["ErrorTypes"].KEY_SYSTEM_ERROR,
  16498. details: errors["ErrorDetails"].KEY_SYSTEM_LICENSE_REQUEST_FAILED,
  16499. fatal: true
  16500. });
  16501. return;
  16502. }
  16503. var attemptsLeft = MAX_LICENSE_REQUEST_FAILURES - this._requestLicenseFailureCount + 1;
  16504. logger["logger"].warn("Retrying license request, " + attemptsLeft + " attempts left");
  16505. this._requestLicense(keyMessage, callback);
  16506. }
  16507. break;
  16508. }
  16509. }
  16510. /**
  16511. * @private
  16512. * @param {MediaKeysListItem} keysListItem
  16513. * @param {ArrayBuffer} keyMessage
  16514. * @returns {ArrayBuffer} Challenge data posted to license server
  16515. * @throws if KeySystem is unsupported
  16516. */
  16517. ;
  16518. _proto._generateLicenseRequestChallenge = function _generateLicenseRequestChallenge(keysListItem, keyMessage) {
  16519. switch (keysListItem.mediaKeySystemDomain) {
  16520. // case KeySystems.PLAYREADY:
  16521. // from https://github.com/MicrosoftEdge/Demos/blob/master/eme/scripts/demo.js
  16522. /*
  16523. if (this.licenseType !== this.LICENSE_TYPE_WIDEVINE) {
  16524. // For PlayReady CDMs, we need to dig the Challenge out of the XML.
  16525. var keyMessageXml = new DOMParser().parseFromString(String.fromCharCode.apply(null, new Uint16Array(keyMessage)), 'application/xml');
  16526. if (keyMessageXml.getElementsByTagName('Challenge')[0]) {
  16527. challenge = atob(keyMessageXml.getElementsByTagName('Challenge')[0].childNodes[0].nodeValue);
  16528. } else {
  16529. throw 'Cannot find <Challenge> in key message';
  16530. }
  16531. var headerNames = keyMessageXml.getElementsByTagName('name');
  16532. var headerValues = keyMessageXml.getElementsByTagName('value');
  16533. if (headerNames.length !== headerValues.length) {
  16534. throw 'Mismatched header <name>/<value> pair in key message';
  16535. }
  16536. for (var i = 0; i < headerNames.length; i++) {
  16537. xhr.setRequestHeader(headerNames[i].childNodes[0].nodeValue, headerValues[i].childNodes[0].nodeValue);
  16538. }
  16539. }
  16540. break;
  16541. */
  16542. case KeySystems.WIDEVINE:
  16543. // For Widevine CDMs, the challenge is the keyMessage.
  16544. return keyMessage;
  16545. }
  16546. throw new Error("unsupported key-system: " + keysListItem.mediaKeySystemDomain);
  16547. }
  16548. /**
  16549. * @private
  16550. * @param keyMessage
  16551. * @param callback
  16552. */
  16553. ;
  16554. _proto._requestLicense = function _requestLicense(keyMessage, callback) {
  16555. logger["logger"].log('Requesting content license for key-system');
  16556. var keysListItem = this._mediaKeysList[0];
  16557. if (!keysListItem) {
  16558. logger["logger"].error('Fatal error: Media is encrypted but no key-system access has been obtained yet');
  16559. this.hls.trigger(events["default"].ERROR, {
  16560. type: errors["ErrorTypes"].KEY_SYSTEM_ERROR,
  16561. details: errors["ErrorDetails"].KEY_SYSTEM_NO_ACCESS,
  16562. fatal: true
  16563. });
  16564. return;
  16565. }
  16566. try {
  16567. var _url = this.getLicenseServerUrl(keysListItem.mediaKeySystemDomain);
  16568. var _xhr = this._createLicenseXhr(_url, keyMessage, callback);
  16569. logger["logger"].log("Sending license request to URL: " + _url);
  16570. var challenge = this._generateLicenseRequestChallenge(keysListItem, keyMessage);
  16571. _xhr.send(challenge);
  16572. } catch (e) {
  16573. logger["logger"].error("Failure requesting DRM license: " + e);
  16574. this.hls.trigger(events["default"].ERROR, {
  16575. type: errors["ErrorTypes"].KEY_SYSTEM_ERROR,
  16576. details: errors["ErrorDetails"].KEY_SYSTEM_LICENSE_REQUEST_FAILED,
  16577. fatal: true
  16578. });
  16579. }
  16580. };
  16581. _proto.onMediaAttached = function onMediaAttached(data) {
  16582. if (!this._emeEnabled) {
  16583. return;
  16584. }
  16585. var media = data.media; // keep reference of media
  16586. this._media = media;
  16587. media.addEventListener('encrypted', this._onMediaEncrypted);
  16588. };
  16589. _proto.onMediaDetached = function onMediaDetached() {
  16590. var media = this._media;
  16591. var mediaKeysList = this._mediaKeysList;
  16592. if (!media) {
  16593. return;
  16594. }
  16595. media.removeEventListener('encrypted', this._onMediaEncrypted);
  16596. this._media = null;
  16597. this._mediaKeysList = []; // Close all sessions and remove media keys from the video element.
  16598. Promise.all(mediaKeysList.map(function (mediaKeysListItem) {
  16599. if (mediaKeysListItem.mediaKeysSession) {
  16600. return mediaKeysListItem.mediaKeysSession.close().catch(function () {// Ignore errors when closing the sessions. Closing a session that
  16601. // generated no key requests will throw an error.
  16602. });
  16603. }
  16604. })).then(function () {
  16605. return media.setMediaKeys(null);
  16606. }).catch(function () {// Ignore any failures while removing media keys from the video element.
  16607. });
  16608. } // TODO: Use manifest types here when they are defined
  16609. ;
  16610. _proto.onManifestParsed = function onManifestParsed(data) {
  16611. if (!this._emeEnabled) {
  16612. return;
  16613. }
  16614. var audioCodecs = data.levels.map(function (level) {
  16615. return level.audioCodec;
  16616. });
  16617. var videoCodecs = data.levels.map(function (level) {
  16618. return level.videoCodec;
  16619. });
  16620. this._attemptKeySystemAccess(KeySystems.WIDEVINE, audioCodecs, videoCodecs);
  16621. };
  16622. eme_controller_createClass(EMEController, [{
  16623. key: "requestMediaKeySystemAccess",
  16624. get: function get() {
  16625. if (!this._requestMediaKeySystemAccess) {
  16626. throw new Error('No requestMediaKeySystemAccess function configured');
  16627. }
  16628. return this._requestMediaKeySystemAccess;
  16629. }
  16630. }]);
  16631. return EMEController;
  16632. }(event_handler);
  16633. /* harmony default export */ var eme_controller = (eme_controller_EMEController);
  16634. // CONCATENATED MODULE: ./src/config.ts
  16635. function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  16636. function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  16637. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  16638. /**
  16639. * HLS config
  16640. */
  16641. // import FetchLoader from './utils/fetch-loader';
  16642. // If possible, keep hlsDefaultConfig shallow
  16643. // It is cloned whenever a new Hls instance is created, by keeping the config
  16644. // shallow the properties are cloned, and we don't end up manipulating the default
  16645. var hlsDefaultConfig = _objectSpread(_objectSpread({
  16646. autoStartLoad: true,
  16647. // used by stream-controller
  16648. startPosition: -1,
  16649. // used by stream-controller
  16650. defaultAudioCodec: void 0,
  16651. // used by stream-controller
  16652. debug: false,
  16653. // used by logger
  16654. capLevelOnFPSDrop: false,
  16655. // used by fps-controller
  16656. capLevelToPlayerSize: false,
  16657. // used by cap-level-controller
  16658. initialLiveManifestSize: 1,
  16659. // used by stream-controller
  16660. maxBufferLength: 30,
  16661. // used by stream-controller
  16662. maxBufferSize: 60 * 1000 * 1000,
  16663. // used by stream-controller
  16664. maxBufferHole: 0.5,
  16665. // used by stream-controller
  16666. lowBufferWatchdogPeriod: 0.5,
  16667. // used by stream-controller
  16668. highBufferWatchdogPeriod: 3,
  16669. // used by stream-controller
  16670. nudgeOffset: 0.1,
  16671. // used by stream-controller
  16672. nudgeMaxRetry: 3,
  16673. // used by stream-controller
  16674. maxFragLookUpTolerance: 0.25,
  16675. // used by stream-controller
  16676. liveSyncDurationCount: 3,
  16677. // used by stream-controller
  16678. liveMaxLatencyDurationCount: Infinity,
  16679. // used by stream-controller
  16680. liveSyncDuration: void 0,
  16681. // used by stream-controller
  16682. liveMaxLatencyDuration: void 0,
  16683. // used by stream-controller
  16684. liveDurationInfinity: false,
  16685. // used by buffer-controller
  16686. liveBackBufferLength: Infinity,
  16687. // used by buffer-controller
  16688. maxMaxBufferLength: 600,
  16689. // used by stream-controller
  16690. enableWorker: true,
  16691. // used by demuxer
  16692. enableSoftwareAES: true,
  16693. // used by decrypter
  16694. manifestLoadingTimeOut: 10000,
  16695. // used by playlist-loader
  16696. manifestLoadingMaxRetry: 1,
  16697. // used by playlist-loader
  16698. manifestLoadingRetryDelay: 1000,
  16699. // used by playlist-loader
  16700. manifestLoadingMaxRetryTimeout: 64000,
  16701. // used by playlist-loader
  16702. startLevel: void 0,
  16703. // used by level-controller
  16704. levelLoadingTimeOut: 10000,
  16705. // used by playlist-loader
  16706. levelLoadingMaxRetry: 4,
  16707. // used by playlist-loader
  16708. levelLoadingRetryDelay: 1000,
  16709. // used by playlist-loader
  16710. levelLoadingMaxRetryTimeout: 64000,
  16711. // used by playlist-loader
  16712. fragLoadingTimeOut: 20000,
  16713. // used by fragment-loader
  16714. fragLoadingMaxRetry: 6,
  16715. // used by fragment-loader
  16716. fragLoadingRetryDelay: 1000,
  16717. // used by fragment-loader
  16718. fragLoadingMaxRetryTimeout: 64000,
  16719. // used by fragment-loader
  16720. startFragPrefetch: false,
  16721. // used by stream-controller
  16722. fpsDroppedMonitoringPeriod: 5000,
  16723. // used by fps-controller
  16724. fpsDroppedMonitoringThreshold: 0.2,
  16725. // used by fps-controller
  16726. appendErrorMaxRetry: 3,
  16727. // used by buffer-controller
  16728. loader: xhr_loader,
  16729. // loader: FetchLoader,
  16730. fLoader: void 0,
  16731. // used by fragment-loader
  16732. pLoader: void 0,
  16733. // used by playlist-loader
  16734. xhrSetup: void 0,
  16735. // used by xhr-loader
  16736. licenseXhrSetup: void 0,
  16737. // used by eme-controller
  16738. // fetchSetup: void 0,
  16739. abrController: abr_controller,
  16740. bufferController: buffer_controller,
  16741. capLevelController: cap_level_controller,
  16742. fpsController: fps_controller,
  16743. stretchShortVideoTrack: false,
  16744. // used by mp4-remuxer
  16745. maxAudioFramesDrift: 1,
  16746. // used by mp4-remuxer
  16747. forceKeyFrameOnDiscontinuity: true,
  16748. // used by ts-demuxer
  16749. abrEwmaFastLive: 3,
  16750. // used by abr-controller
  16751. abrEwmaSlowLive: 9,
  16752. // used by abr-controller
  16753. abrEwmaFastVoD: 3,
  16754. // used by abr-controller
  16755. abrEwmaSlowVoD: 9,
  16756. // used by abr-controller
  16757. abrEwmaDefaultEstimate: 5e5,
  16758. // 500 kbps // used by abr-controller
  16759. abrBandWidthFactor: 0.95,
  16760. // used by abr-controller
  16761. abrBandWidthUpFactor: 0.7,
  16762. // used by abr-controller
  16763. abrMaxWithRealBitrate: false,
  16764. // used by abr-controller
  16765. maxStarvationDelay: 4,
  16766. // used by abr-controller
  16767. maxLoadingDelay: 4,
  16768. // used by abr-controller
  16769. minAutoBitrate: 0,
  16770. // used by hls
  16771. emeEnabled: false,
  16772. // used by eme-controller
  16773. widevineLicenseUrl: void 0,
  16774. // used by eme-controller
  16775. drmSystemOptions: {},
  16776. // used by eme-controller
  16777. requestMediaKeySystemAccessFunc: requestMediaKeySystemAccess,
  16778. // used by eme-controller
  16779. testBandwidth: true
  16780. }, timelineConfig()), {}, {
  16781. subtitleStreamController: true ? subtitle_stream_controller_SubtitleStreamController : undefined,
  16782. subtitleTrackController: true ? subtitle_track_controller : undefined,
  16783. timelineController: true ? timeline_controller : undefined,
  16784. audioStreamController: true ? audio_stream_controller : undefined,
  16785. audioTrackController: true ? audio_track_controller : undefined,
  16786. emeController: true ? eme_controller : undefined
  16787. });
  16788. function timelineConfig() {
  16789. return {
  16790. cueHandler: cues_namespaceObject,
  16791. // used by timeline-controller
  16792. enableCEA708Captions: true,
  16793. // used by timeline-controller
  16794. enableWebVTT: true,
  16795. // used by timeline-controller
  16796. captionsTextTrack1Label: 'English',
  16797. // used by timeline-controller
  16798. captionsTextTrack1LanguageCode: 'en',
  16799. // used by timeline-controller
  16800. captionsTextTrack2Label: 'Spanish',
  16801. // used by timeline-controller
  16802. captionsTextTrack2LanguageCode: 'es',
  16803. // used by timeline-controller
  16804. captionsTextTrack3Label: 'Unknown CC',
  16805. // used by timeline-controller
  16806. captionsTextTrack3LanguageCode: '',
  16807. // used by timeline-controller
  16808. captionsTextTrack4Label: 'Unknown CC',
  16809. // used by timeline-controller
  16810. captionsTextTrack4LanguageCode: '',
  16811. // used by timeline-controller
  16812. renderTextTracksNatively: true
  16813. };
  16814. }
  16815. // CONCATENATED MODULE: ./src/hls.ts
  16816. function hls_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  16817. function hls_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { hls_ownKeys(Object(source), true).forEach(function (key) { hls_defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { hls_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  16818. function hls_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  16819. function hls_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  16820. function hls_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  16821. function hls_createClass(Constructor, protoProps, staticProps) { if (protoProps) hls_defineProperties(Constructor.prototype, protoProps); if (staticProps) hls_defineProperties(Constructor, staticProps); return Constructor; }
  16822. function hls_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  16823. /**
  16824. * @module Hls
  16825. * @class
  16826. * @constructor
  16827. */
  16828. var hls_Hls = /*#__PURE__*/function (_Observer) {
  16829. hls_inheritsLoose(Hls, _Observer);
  16830. /**
  16831. * @type {boolean}
  16832. */
  16833. Hls.isSupported = function isSupported() {
  16834. return is_supported_isSupported();
  16835. }
  16836. /**
  16837. * @type {HlsEvents}
  16838. */
  16839. ;
  16840. hls_createClass(Hls, null, [{
  16841. key: "version",
  16842. /**
  16843. * @type {string}
  16844. */
  16845. get: function get() {
  16846. return "0.14.17";
  16847. }
  16848. }, {
  16849. key: "Events",
  16850. get: function get() {
  16851. return events["default"];
  16852. }
  16853. /**
  16854. * @type {HlsErrorTypes}
  16855. */
  16856. }, {
  16857. key: "ErrorTypes",
  16858. get: function get() {
  16859. return errors["ErrorTypes"];
  16860. }
  16861. /**
  16862. * @type {HlsErrorDetails}
  16863. */
  16864. }, {
  16865. key: "ErrorDetails",
  16866. get: function get() {
  16867. return errors["ErrorDetails"];
  16868. }
  16869. /**
  16870. * @type {HlsConfig}
  16871. */
  16872. }, {
  16873. key: "DefaultConfig",
  16874. get: function get() {
  16875. if (!Hls.defaultConfig) {
  16876. return hlsDefaultConfig;
  16877. }
  16878. return Hls.defaultConfig;
  16879. }
  16880. /**
  16881. * @type {HlsConfig}
  16882. */
  16883. ,
  16884. set: function set(defaultConfig) {
  16885. Hls.defaultConfig = defaultConfig;
  16886. }
  16887. /**
  16888. * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
  16889. *
  16890. * @constructs Hls
  16891. * @param {HlsConfig} config
  16892. */
  16893. }]);
  16894. function Hls(userConfig) {
  16895. var _this;
  16896. if (userConfig === void 0) {
  16897. userConfig = {};
  16898. }
  16899. _this = _Observer.call(this) || this;
  16900. _this.config = void 0;
  16901. _this._autoLevelCapping = void 0;
  16902. _this.abrController = void 0;
  16903. _this.capLevelController = void 0;
  16904. _this.levelController = void 0;
  16905. _this.streamController = void 0;
  16906. _this.networkControllers = void 0;
  16907. _this.audioTrackController = void 0;
  16908. _this.subtitleTrackController = void 0;
  16909. _this.emeController = void 0;
  16910. _this.coreComponents = void 0;
  16911. _this.media = null;
  16912. _this.url = null;
  16913. var defaultConfig = Hls.DefaultConfig;
  16914. if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {
  16915. throw new Error('Illegal hls.js config: don\'t mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration');
  16916. } // Shallow clone
  16917. _this.config = hls_objectSpread(hls_objectSpread({}, defaultConfig), userConfig);
  16918. var _assertThisInitialize = hls_assertThisInitialized(_this),
  16919. config = _assertThisInitialize.config;
  16920. if (config.liveMaxLatencyDurationCount !== void 0 && config.liveMaxLatencyDurationCount <= config.liveSyncDurationCount) {
  16921. throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be gt "liveSyncDurationCount"');
  16922. }
  16923. if (config.liveMaxLatencyDuration !== void 0 && (config.liveSyncDuration === void 0 || config.liveMaxLatencyDuration <= config.liveSyncDuration)) {
  16924. throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be gt "liveSyncDuration"');
  16925. }
  16926. Object(logger["enableLogs"])(config.debug);
  16927. _this._autoLevelCapping = -1; // core controllers and network loaders
  16928. /**
  16929. * @member {AbrController} abrController
  16930. */
  16931. var abrController = _this.abrController = new config.abrController(hls_assertThisInitialized(_this)); // eslint-disable-line new-cap
  16932. var bufferController = new config.bufferController(hls_assertThisInitialized(_this)); // eslint-disable-line new-cap
  16933. var capLevelController = _this.capLevelController = new config.capLevelController(hls_assertThisInitialized(_this)); // eslint-disable-line new-cap
  16934. var fpsController = new config.fpsController(hls_assertThisInitialized(_this)); // eslint-disable-line new-cap
  16935. var playListLoader = new playlist_loader(hls_assertThisInitialized(_this));
  16936. var fragmentLoader = new fragment_loader(hls_assertThisInitialized(_this));
  16937. var keyLoader = new key_loader(hls_assertThisInitialized(_this));
  16938. var id3TrackController = new id3_track_controller(hls_assertThisInitialized(_this)); // network controllers
  16939. /**
  16940. * @member {LevelController} levelController
  16941. */
  16942. var levelController = _this.levelController = new level_controller_LevelController(hls_assertThisInitialized(_this)); // FIXME: FragmentTracker must be defined before StreamController because the order of event handling is important
  16943. var fragmentTracker = new fragment_tracker_FragmentTracker(hls_assertThisInitialized(_this));
  16944. /**
  16945. * @member {StreamController} streamController
  16946. */
  16947. var streamController = _this.streamController = new stream_controller(hls_assertThisInitialized(_this), fragmentTracker);
  16948. var networkControllers = [levelController, streamController]; // optional audio stream controller
  16949. /**
  16950. * @var {ICoreComponent | Controller}
  16951. */
  16952. var Controller = config.audioStreamController;
  16953. if (Controller) {
  16954. networkControllers.push(new Controller(hls_assertThisInitialized(_this), fragmentTracker));
  16955. }
  16956. /**
  16957. * @member {INetworkController[]} networkControllers
  16958. */
  16959. _this.networkControllers = networkControllers;
  16960. /**
  16961. * @var {ICoreComponent[]}
  16962. */
  16963. var coreComponents = [playListLoader, fragmentLoader, keyLoader, abrController, bufferController, capLevelController, fpsController, id3TrackController, fragmentTracker]; // optional audio track and subtitle controller
  16964. Controller = config.audioTrackController;
  16965. if (Controller) {
  16966. var audioTrackController = new Controller(hls_assertThisInitialized(_this));
  16967. /**
  16968. * @member {AudioTrackController} audioTrackController
  16969. */
  16970. _this.audioTrackController = audioTrackController;
  16971. coreComponents.push(audioTrackController);
  16972. }
  16973. Controller = config.subtitleTrackController;
  16974. if (Controller) {
  16975. var subtitleTrackController = new Controller(hls_assertThisInitialized(_this));
  16976. /**
  16977. * @member {SubtitleTrackController} subtitleTrackController
  16978. */
  16979. _this.subtitleTrackController = subtitleTrackController;
  16980. networkControllers.push(subtitleTrackController);
  16981. }
  16982. Controller = config.emeController;
  16983. if (Controller) {
  16984. var emeController = new Controller(hls_assertThisInitialized(_this));
  16985. /**
  16986. * @member {EMEController} emeController
  16987. */
  16988. _this.emeController = emeController;
  16989. coreComponents.push(emeController);
  16990. } // optional subtitle controllers
  16991. Controller = config.subtitleStreamController;
  16992. if (Controller) {
  16993. networkControllers.push(new Controller(hls_assertThisInitialized(_this), fragmentTracker));
  16994. }
  16995. Controller = config.timelineController;
  16996. if (Controller) {
  16997. coreComponents.push(new Controller(hls_assertThisInitialized(_this)));
  16998. }
  16999. /**
  17000. * @member {ICoreComponent[]}
  17001. */
  17002. _this.coreComponents = coreComponents;
  17003. return _this;
  17004. }
  17005. /**
  17006. * Dispose of the instance
  17007. */
  17008. var _proto = Hls.prototype;
  17009. _proto.destroy = function destroy() {
  17010. logger["logger"].log('destroy');
  17011. this.trigger(events["default"].DESTROYING);
  17012. this.detachMedia();
  17013. this.coreComponents.concat(this.networkControllers).forEach(function (component) {
  17014. component.destroy();
  17015. });
  17016. this.url = null;
  17017. this.removeAllListeners();
  17018. this._autoLevelCapping = -1;
  17019. }
  17020. /**
  17021. * Attach a media element
  17022. * @param {HTMLMediaElement} media
  17023. */
  17024. ;
  17025. _proto.attachMedia = function attachMedia(media) {
  17026. logger["logger"].log('attachMedia');
  17027. this.media = media;
  17028. this.trigger(events["default"].MEDIA_ATTACHING, {
  17029. media: media
  17030. });
  17031. }
  17032. /**
  17033. * Detach from the media
  17034. */
  17035. ;
  17036. _proto.detachMedia = function detachMedia() {
  17037. logger["logger"].log('detachMedia');
  17038. this.trigger(events["default"].MEDIA_DETACHING);
  17039. this.media = null;
  17040. }
  17041. /**
  17042. * Set the source URL. Can be relative or absolute.
  17043. * @param {string} url
  17044. */
  17045. ;
  17046. _proto.loadSource = function loadSource(url) {
  17047. url = url_toolkit["buildAbsoluteURL"](window.location.href, url, {
  17048. alwaysNormalize: true
  17049. });
  17050. logger["logger"].log("loadSource:" + url);
  17051. this.url = url; // when attaching to a source URL, trigger a playlist load
  17052. this.trigger(events["default"].MANIFEST_LOADING, {
  17053. url: url
  17054. });
  17055. }
  17056. /**
  17057. * Start loading data from the stream source.
  17058. * Depending on default config, client starts loading automatically when a source is set.
  17059. *
  17060. * @param {number} startPosition Set the start position to stream from
  17061. * @default -1 None (from earliest point)
  17062. */
  17063. ;
  17064. _proto.startLoad = function startLoad(startPosition) {
  17065. if (startPosition === void 0) {
  17066. startPosition = -1;
  17067. }
  17068. logger["logger"].log("startLoad(" + startPosition + ")");
  17069. this.networkControllers.forEach(function (controller) {
  17070. controller.startLoad(startPosition);
  17071. });
  17072. }
  17073. /**
  17074. * Stop loading of any stream data.
  17075. */
  17076. ;
  17077. _proto.stopLoad = function stopLoad() {
  17078. logger["logger"].log('stopLoad');
  17079. this.networkControllers.forEach(function (controller) {
  17080. controller.stopLoad();
  17081. });
  17082. }
  17083. /**
  17084. * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
  17085. */
  17086. ;
  17087. _proto.swapAudioCodec = function swapAudioCodec() {
  17088. logger["logger"].log('swapAudioCodec');
  17089. this.streamController.swapAudioCodec();
  17090. }
  17091. /**
  17092. * When the media-element fails, this allows to detach and then re-attach it
  17093. * as one call (convenience method).
  17094. *
  17095. * Automatic recovery of media-errors by this process is configurable.
  17096. */
  17097. ;
  17098. _proto.recoverMediaError = function recoverMediaError() {
  17099. logger["logger"].log('recoverMediaError');
  17100. var media = this.media;
  17101. this.detachMedia();
  17102. if (media) {
  17103. this.attachMedia(media);
  17104. }
  17105. }
  17106. /**
  17107. * Remove a loaded level from the list of levels, or a level url in from a list of redundant level urls.
  17108. * This can be used to remove a rendition or playlist url that errors frequently from the list of levels that a user
  17109. * or hls.js can choose from.
  17110. *
  17111. * @param levelIndex {number} The quality level index to of the level to remove
  17112. * @param urlId {number} The quality level url index in the case that fallback levels are available. Defaults to 0.
  17113. */
  17114. ;
  17115. _proto.removeLevel = function removeLevel(levelIndex, urlId) {
  17116. if (urlId === void 0) {
  17117. urlId = 0;
  17118. }
  17119. this.levelController.removeLevel(levelIndex, urlId);
  17120. }
  17121. /**
  17122. * @type {QualityLevel[]}
  17123. */
  17124. // todo(typescript-levelController)
  17125. ;
  17126. hls_createClass(Hls, [{
  17127. key: "levels",
  17128. get: function get() {
  17129. return this.levelController.levels;
  17130. }
  17131. /**
  17132. * Index of quality level currently played
  17133. * @type {number}
  17134. */
  17135. }, {
  17136. key: "currentLevel",
  17137. get: function get() {
  17138. return this.streamController.currentLevel;
  17139. }
  17140. /**
  17141. * Set quality level index immediately .
  17142. * This will flush the current buffer to replace the quality asap.
  17143. * That means playback will interrupt at least shortly to re-buffer and re-sync eventually.
  17144. * @param newLevel {number} -1 for automatic level selection
  17145. */
  17146. ,
  17147. set: function set(newLevel) {
  17148. logger["logger"].log("set currentLevel:" + newLevel);
  17149. this.loadLevel = newLevel;
  17150. this.streamController.immediateLevelSwitch();
  17151. }
  17152. /**
  17153. * Index of next quality level loaded as scheduled by stream controller.
  17154. * @type {number}
  17155. */
  17156. }, {
  17157. key: "nextLevel",
  17158. get: function get() {
  17159. return this.streamController.nextLevel;
  17160. }
  17161. /**
  17162. * Set quality level index for next loaded data.
  17163. * This will switch the video quality asap, without interrupting playback.
  17164. * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
  17165. * @type {number} -1 for automatic level selection
  17166. */
  17167. ,
  17168. set: function set(newLevel) {
  17169. logger["logger"].log("set nextLevel:" + newLevel);
  17170. this.levelController.manualLevel = newLevel;
  17171. this.streamController.nextLevelSwitch();
  17172. }
  17173. /**
  17174. * Return the quality level of the currently or last (of none is loaded currently) segment
  17175. * @type {number}
  17176. */
  17177. }, {
  17178. key: "loadLevel",
  17179. get: function get() {
  17180. return this.levelController.level;
  17181. }
  17182. /**
  17183. * Set quality level index for next loaded data in a conservative way.
  17184. * This will switch the quality without flushing, but interrupt current loading.
  17185. * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
  17186. * @type {number} newLevel -1 for automatic level selection
  17187. */
  17188. ,
  17189. set: function set(newLevel) {
  17190. logger["logger"].log("set loadLevel:" + newLevel);
  17191. this.levelController.manualLevel = newLevel;
  17192. }
  17193. /**
  17194. * get next quality level loaded
  17195. * @type {number}
  17196. */
  17197. }, {
  17198. key: "nextLoadLevel",
  17199. get: function get() {
  17200. return this.levelController.nextLoadLevel;
  17201. }
  17202. /**
  17203. * Set quality level of next loaded segment in a fully "non-destructive" way.
  17204. * Same as `loadLevel` but will wait for next switch (until current loading is done).
  17205. * @type {number} level
  17206. */
  17207. ,
  17208. set: function set(level) {
  17209. this.levelController.nextLoadLevel = level;
  17210. }
  17211. /**
  17212. * Return "first level": like a default level, if not set,
  17213. * falls back to index of first level referenced in manifest
  17214. * @type {number}
  17215. */
  17216. }, {
  17217. key: "firstLevel",
  17218. get: function get() {
  17219. return Math.max(this.levelController.firstLevel, this.minAutoLevel);
  17220. }
  17221. /**
  17222. * Sets "first-level", see getter.
  17223. * @type {number}
  17224. */
  17225. ,
  17226. set: function set(newLevel) {
  17227. logger["logger"].log("set firstLevel:" + newLevel);
  17228. this.levelController.firstLevel = newLevel;
  17229. }
  17230. /**
  17231. * Return start level (level of first fragment that will be played back)
  17232. * if not overrided by user, first level appearing in manifest will be used as start level
  17233. * if -1 : automatic start level selection, playback will start from level matching download bandwidth
  17234. * (determined from download of first segment)
  17235. * @type {number}
  17236. */
  17237. }, {
  17238. key: "startLevel",
  17239. get: function get() {
  17240. return this.levelController.startLevel;
  17241. }
  17242. /**
  17243. * set start level (level of first fragment that will be played back)
  17244. * if not overrided by user, first level appearing in manifest will be used as start level
  17245. * if -1 : automatic start level selection, playback will start from level matching download bandwidth
  17246. * (determined from download of first segment)
  17247. * @type {number} newLevel
  17248. */
  17249. ,
  17250. set: function set(newLevel) {
  17251. logger["logger"].log("set startLevel:" + newLevel); // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel
  17252. if (newLevel !== -1) {
  17253. newLevel = Math.max(newLevel, this.minAutoLevel);
  17254. }
  17255. this.levelController.startLevel = newLevel;
  17256. }
  17257. /**
  17258. * set dynamically set capLevelToPlayerSize against (`CapLevelController`)
  17259. *
  17260. * @type {boolean}
  17261. */
  17262. }, {
  17263. key: "capLevelToPlayerSize",
  17264. set: function set(shouldStartCapping) {
  17265. var newCapLevelToPlayerSize = !!shouldStartCapping;
  17266. if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {
  17267. if (newCapLevelToPlayerSize) {
  17268. this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size.
  17269. } else {
  17270. this.capLevelController.stopCapping();
  17271. this.autoLevelCapping = -1;
  17272. this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap.
  17273. }
  17274. this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;
  17275. }
  17276. }
  17277. /**
  17278. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  17279. * @type {number}
  17280. */
  17281. }, {
  17282. key: "autoLevelCapping",
  17283. get: function get() {
  17284. return this._autoLevelCapping;
  17285. }
  17286. /**
  17287. * get bandwidth estimate
  17288. * @type {number}
  17289. */
  17290. ,
  17291. /**
  17292. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  17293. * @type {number}
  17294. */
  17295. set: function set(newLevel) {
  17296. logger["logger"].log("set autoLevelCapping:" + newLevel);
  17297. this._autoLevelCapping = newLevel;
  17298. }
  17299. /**
  17300. * True when automatic level selection enabled
  17301. * @type {boolean}
  17302. */
  17303. }, {
  17304. key: "bandwidthEstimate",
  17305. get: function get() {
  17306. var bwEstimator = this.abrController._bwEstimator;
  17307. return bwEstimator ? bwEstimator.getEstimate() : NaN;
  17308. }
  17309. }, {
  17310. key: "autoLevelEnabled",
  17311. get: function get() {
  17312. return this.levelController.manualLevel === -1;
  17313. }
  17314. /**
  17315. * Level set manually (if any)
  17316. * @type {number}
  17317. */
  17318. }, {
  17319. key: "manualLevel",
  17320. get: function get() {
  17321. return this.levelController.manualLevel;
  17322. }
  17323. /**
  17324. * min level selectable in auto mode according to config.minAutoBitrate
  17325. * @type {number}
  17326. */
  17327. }, {
  17328. key: "minAutoLevel",
  17329. get: function get() {
  17330. var levels = this.levels,
  17331. minAutoBitrate = this.config.minAutoBitrate;
  17332. var len = levels ? levels.length : 0;
  17333. for (var i = 0; i < len; i++) {
  17334. var levelNextBitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate;
  17335. if (levelNextBitrate > minAutoBitrate) {
  17336. return i;
  17337. }
  17338. }
  17339. return 0;
  17340. }
  17341. /**
  17342. * max level selectable in auto mode according to autoLevelCapping
  17343. * @type {number}
  17344. */
  17345. }, {
  17346. key: "maxAutoLevel",
  17347. get: function get() {
  17348. var levels = this.levels,
  17349. autoLevelCapping = this.autoLevelCapping;
  17350. var maxAutoLevel;
  17351. if (autoLevelCapping === -1 && levels && levels.length) {
  17352. maxAutoLevel = levels.length - 1;
  17353. } else {
  17354. maxAutoLevel = autoLevelCapping;
  17355. }
  17356. return maxAutoLevel;
  17357. }
  17358. /**
  17359. * next automatically selected quality level
  17360. * @type {number}
  17361. */
  17362. }, {
  17363. key: "nextAutoLevel",
  17364. get: function get() {
  17365. // ensure next auto level is between min and max auto level
  17366. return Math.min(Math.max(this.abrController.nextAutoLevel, this.minAutoLevel), this.maxAutoLevel);
  17367. }
  17368. /**
  17369. * this setter is used to force next auto level.
  17370. * this is useful to force a switch down in auto mode:
  17371. * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
  17372. * forced value is valid for one fragment. upon succesful frag loading at forced level,
  17373. * this value will be resetted to -1 by ABR controller.
  17374. * @type {number}
  17375. */
  17376. ,
  17377. set: function set(nextLevel) {
  17378. this.abrController.nextAutoLevel = Math.max(this.minAutoLevel, nextLevel);
  17379. }
  17380. /**
  17381. * @type {AudioTrack[]}
  17382. */
  17383. // todo(typescript-audioTrackController)
  17384. }, {
  17385. key: "audioTracks",
  17386. get: function get() {
  17387. var audioTrackController = this.audioTrackController;
  17388. return audioTrackController ? audioTrackController.audioTracks : [];
  17389. }
  17390. /**
  17391. * index of the selected audio track (index in audio track lists)
  17392. * @type {number}
  17393. */
  17394. }, {
  17395. key: "audioTrack",
  17396. get: function get() {
  17397. var audioTrackController = this.audioTrackController;
  17398. return audioTrackController ? audioTrackController.audioTrack : -1;
  17399. }
  17400. /**
  17401. * selects an audio track, based on its index in audio track lists
  17402. * @type {number}
  17403. */
  17404. ,
  17405. set: function set(audioTrackId) {
  17406. var audioTrackController = this.audioTrackController;
  17407. if (audioTrackController) {
  17408. audioTrackController.audioTrack = audioTrackId;
  17409. }
  17410. }
  17411. /**
  17412. * @type {Seconds}
  17413. */
  17414. }, {
  17415. key: "liveSyncPosition",
  17416. get: function get() {
  17417. return this.streamController.liveSyncPosition;
  17418. }
  17419. /**
  17420. * get alternate subtitle tracks list from playlist
  17421. * @type {SubtitleTrack[]}
  17422. */
  17423. // todo(typescript-subtitleTrackController)
  17424. }, {
  17425. key: "subtitleTracks",
  17426. get: function get() {
  17427. var subtitleTrackController = this.subtitleTrackController;
  17428. return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
  17429. }
  17430. /**
  17431. * index of the selected subtitle track (index in subtitle track lists)
  17432. * @type {number}
  17433. */
  17434. }, {
  17435. key: "subtitleTrack",
  17436. get: function get() {
  17437. var subtitleTrackController = this.subtitleTrackController;
  17438. return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
  17439. }
  17440. /**
  17441. * select an subtitle track, based on its index in subtitle track lists
  17442. * @type {number}
  17443. */
  17444. ,
  17445. set: function set(subtitleTrackId) {
  17446. var subtitleTrackController = this.subtitleTrackController;
  17447. if (subtitleTrackController) {
  17448. subtitleTrackController.subtitleTrack = subtitleTrackId;
  17449. }
  17450. }
  17451. /**
  17452. * @type {boolean}
  17453. */
  17454. }, {
  17455. key: "subtitleDisplay",
  17456. get: function get() {
  17457. var subtitleTrackController = this.subtitleTrackController;
  17458. return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
  17459. }
  17460. /**
  17461. * Enable/disable subtitle display rendering
  17462. * @type {boolean}
  17463. */
  17464. ,
  17465. set: function set(value) {
  17466. var subtitleTrackController = this.subtitleTrackController;
  17467. if (subtitleTrackController) {
  17468. subtitleTrackController.subtitleDisplay = value;
  17469. }
  17470. }
  17471. }]);
  17472. return Hls;
  17473. }(Observer);
  17474. hls_Hls.defaultConfig = void 0;
  17475. /***/ }),
  17476. /***/ "./src/polyfills/number.js":
  17477. /*!*********************************!*\
  17478. !*** ./src/polyfills/number.js ***!
  17479. \*********************************/
  17480. /*! exports provided: isFiniteNumber, MAX_SAFE_INTEGER */
  17481. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  17482. "use strict";
  17483. __webpack_require__.r(__webpack_exports__);
  17484. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFiniteNumber", function() { return isFiniteNumber; });
  17485. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MAX_SAFE_INTEGER", function() { return MAX_SAFE_INTEGER; });
  17486. var isFiniteNumber = Number.isFinite || function (value) {
  17487. return typeof value === 'number' && isFinite(value);
  17488. };
  17489. var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  17490. /***/ }),
  17491. /***/ "./src/utils/get-self-scope.js":
  17492. /*!*************************************!*\
  17493. !*** ./src/utils/get-self-scope.js ***!
  17494. \*************************************/
  17495. /*! exports provided: getSelfScope */
  17496. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  17497. "use strict";
  17498. __webpack_require__.r(__webpack_exports__);
  17499. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getSelfScope", function() { return getSelfScope; });
  17500. function getSelfScope() {
  17501. // see https://stackoverflow.com/a/11237259/589493
  17502. if (typeof window === 'undefined') {
  17503. /* eslint-disable-next-line no-undef */
  17504. return self;
  17505. } else {
  17506. return window;
  17507. }
  17508. }
  17509. /***/ }),
  17510. /***/ "./src/utils/logger.js":
  17511. /*!*****************************!*\
  17512. !*** ./src/utils/logger.js ***!
  17513. \*****************************/
  17514. /*! exports provided: enableLogs, logger */
  17515. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  17516. "use strict";
  17517. __webpack_require__.r(__webpack_exports__);
  17518. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableLogs", function() { return enableLogs; });
  17519. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logger", function() { return logger; });
  17520. /* harmony import */ var _get_self_scope__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./get-self-scope */ "./src/utils/get-self-scope.js");
  17521. function noop() {}
  17522. var fakeLogger = {
  17523. trace: noop,
  17524. debug: noop,
  17525. log: noop,
  17526. warn: noop,
  17527. info: noop,
  17528. error: noop
  17529. };
  17530. var exportedLogger = fakeLogger; // let lastCallTime;
  17531. // function formatMsgWithTimeInfo(type, msg) {
  17532. // const now = Date.now();
  17533. // const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';
  17534. // lastCallTime = now;
  17535. // msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';
  17536. // return msg;
  17537. // }
  17538. function formatMsg(type, msg) {
  17539. msg = '[' + type + '] > ' + msg;
  17540. return msg;
  17541. }
  17542. var global = Object(_get_self_scope__WEBPACK_IMPORTED_MODULE_0__["getSelfScope"])();
  17543. function consolePrintFn(type) {
  17544. var func = global.console[type];
  17545. if (func) {
  17546. return function () {
  17547. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  17548. args[_key] = arguments[_key];
  17549. }
  17550. if (args[0]) {
  17551. args[0] = formatMsg(type, args[0]);
  17552. }
  17553. func.apply(global.console, args);
  17554. };
  17555. }
  17556. return noop;
  17557. }
  17558. function exportLoggerFunctions(debugConfig) {
  17559. for (var _len2 = arguments.length, functions = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  17560. functions[_key2 - 1] = arguments[_key2];
  17561. }
  17562. functions.forEach(function (type) {
  17563. exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);
  17564. });
  17565. }
  17566. var enableLogs = function enableLogs(debugConfig) {
  17567. // check that console is available
  17568. if (global.console && debugConfig === true || typeof debugConfig === 'object') {
  17569. exportLoggerFunctions(debugConfig, // Remove out from list here to hard-disable a log-level
  17570. // 'trace',
  17571. 'debug', 'log', 'info', 'warn', 'error'); // Some browsers don't allow to use bind on console object anyway
  17572. // fallback to default if needed
  17573. try {
  17574. exportedLogger.log();
  17575. } catch (e) {
  17576. exportedLogger = fakeLogger;
  17577. }
  17578. } else {
  17579. exportedLogger = fakeLogger;
  17580. }
  17581. };
  17582. var logger = exportedLogger;
  17583. /***/ })
  17584. /******/ })["default"];
  17585. });
  17586. //# sourceMappingURL=hls.js.map