hls.light.js 787 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783
  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, () => {
  12. return /******/ (() => { // webpackBootstrap
  13. /******/ var __webpack_modules__ = ({
  14. /***/ "./src/config.ts":
  15. /*!***********************!*\
  16. !*** ./src/config.ts ***!
  17. \***********************/
  18. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  19. "use strict";
  20. __webpack_require__.r(__webpack_exports__);
  21. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  22. /* harmony export */ "enableStreamingMode": () => (/* binding */ enableStreamingMode),
  23. /* harmony export */ "hlsDefaultConfig": () => (/* binding */ hlsDefaultConfig),
  24. /* harmony export */ "mergeConfig": () => (/* binding */ mergeConfig)
  25. /* harmony export */ });
  26. /* harmony import */ var _controller_abr_controller__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./controller/abr-controller */ "./src/controller/abr-controller.ts");
  27. /* harmony import */ var _controller_audio_stream_controller__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils/cues */ "./src/empty.js");
  28. /* harmony import */ var _controller_audio_stream_controller__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_controller_audio_stream_controller__WEBPACK_IMPORTED_MODULE_1__);
  29. /* harmony import */ var _controller_buffer_controller__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./controller/buffer-controller */ "./src/controller/buffer-controller.ts");
  30. /* harmony import */ var _controller_cap_level_controller__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./controller/cap-level-controller */ "./src/controller/cap-level-controller.ts");
  31. /* harmony import */ var _controller_fps_controller__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./controller/fps-controller */ "./src/controller/fps-controller.ts");
  32. /* harmony import */ var _utils_xhr_loader__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./utils/xhr-loader */ "./src/utils/xhr-loader.ts");
  33. /* harmony import */ var _utils_fetch_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./utils/fetch-loader */ "./src/utils/fetch-loader.ts");
  34. /* harmony import */ var _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./utils/mediakeys-helper */ "./src/utils/mediakeys-helper.ts");
  35. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./utils/logger */ "./src/utils/logger.ts");
  36. function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
  37. function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
  38. function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
  39. function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  40. function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
  41. function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
  42. // If possible, keep hlsDefaultConfig shallow
  43. // It is cloned whenever a new Hls instance is created, by keeping the config
  44. // shallow the properties are cloned, and we don't end up manipulating the default
  45. var hlsDefaultConfig = _objectSpread(_objectSpread({
  46. autoStartLoad: true,
  47. // used by stream-controller
  48. startPosition: -1,
  49. // used by stream-controller
  50. defaultAudioCodec: undefined,
  51. // used by stream-controller
  52. debug: false,
  53. // used by logger
  54. capLevelOnFPSDrop: false,
  55. // used by fps-controller
  56. capLevelToPlayerSize: false,
  57. // used by cap-level-controller
  58. ignoreDevicePixelRatio: false,
  59. // used by cap-level-controller
  60. initialLiveManifestSize: 1,
  61. // used by stream-controller
  62. maxBufferLength: 30,
  63. // used by stream-controller
  64. backBufferLength: Infinity,
  65. // used by buffer-controller
  66. maxBufferSize: 60 * 1000 * 1000,
  67. // used by stream-controller
  68. maxBufferHole: 0.1,
  69. // used by stream-controller
  70. highBufferWatchdogPeriod: 2,
  71. // used by stream-controller
  72. nudgeOffset: 0.1,
  73. // used by stream-controller
  74. nudgeMaxRetry: 3,
  75. // used by stream-controller
  76. maxFragLookUpTolerance: 0.25,
  77. // used by stream-controller
  78. liveSyncDurationCount: 3,
  79. // used by latency-controller
  80. liveMaxLatencyDurationCount: Infinity,
  81. // used by latency-controller
  82. liveSyncDuration: undefined,
  83. // used by latency-controller
  84. liveMaxLatencyDuration: undefined,
  85. // used by latency-controller
  86. maxLiveSyncPlaybackRate: 1,
  87. // used by latency-controller
  88. liveDurationInfinity: false,
  89. // used by buffer-controller
  90. liveBackBufferLength: null,
  91. // used by buffer-controller
  92. maxMaxBufferLength: 600,
  93. // used by stream-controller
  94. enableWorker: true,
  95. // used by demuxer
  96. enableSoftwareAES: true,
  97. // used by decrypter
  98. manifestLoadingTimeOut: 10000,
  99. // used by playlist-loader
  100. manifestLoadingMaxRetry: 1,
  101. // used by playlist-loader
  102. manifestLoadingRetryDelay: 1000,
  103. // used by playlist-loader
  104. manifestLoadingMaxRetryTimeout: 64000,
  105. // used by playlist-loader
  106. startLevel: undefined,
  107. // used by level-controller
  108. levelLoadingTimeOut: 10000,
  109. // used by playlist-loader
  110. levelLoadingMaxRetry: 4,
  111. // used by playlist-loader
  112. levelLoadingRetryDelay: 1000,
  113. // used by playlist-loader
  114. levelLoadingMaxRetryTimeout: 64000,
  115. // used by playlist-loader
  116. fragLoadingTimeOut: 20000,
  117. // used by fragment-loader
  118. fragLoadingMaxRetry: 6,
  119. // used by fragment-loader
  120. fragLoadingRetryDelay: 1000,
  121. // used by fragment-loader
  122. fragLoadingMaxRetryTimeout: 64000,
  123. // used by fragment-loader
  124. startFragPrefetch: false,
  125. // used by stream-controller
  126. fpsDroppedMonitoringPeriod: 5000,
  127. // used by fps-controller
  128. fpsDroppedMonitoringThreshold: 0.2,
  129. // used by fps-controller
  130. appendErrorMaxRetry: 3,
  131. // used by buffer-controller
  132. loader: _utils_xhr_loader__WEBPACK_IMPORTED_MODULE_5__["default"],
  133. // loader: FetchLoader,
  134. fLoader: undefined,
  135. // used by fragment-loader
  136. pLoader: undefined,
  137. // used by playlist-loader
  138. xhrSetup: undefined,
  139. // used by xhr-loader
  140. licenseXhrSetup: undefined,
  141. // used by eme-controller
  142. licenseResponseCallback: undefined,
  143. // used by eme-controller
  144. abrController: _controller_abr_controller__WEBPACK_IMPORTED_MODULE_0__["default"],
  145. bufferController: _controller_buffer_controller__WEBPACK_IMPORTED_MODULE_2__["default"],
  146. capLevelController: _controller_cap_level_controller__WEBPACK_IMPORTED_MODULE_3__["default"],
  147. fpsController: _controller_fps_controller__WEBPACK_IMPORTED_MODULE_4__["default"],
  148. stretchShortVideoTrack: false,
  149. // used by mp4-remuxer
  150. maxAudioFramesDrift: 1,
  151. // used by mp4-remuxer
  152. forceKeyFrameOnDiscontinuity: true,
  153. // used by ts-demuxer
  154. abrEwmaFastLive: 3,
  155. // used by abr-controller
  156. abrEwmaSlowLive: 9,
  157. // used by abr-controller
  158. abrEwmaFastVoD: 3,
  159. // used by abr-controller
  160. abrEwmaSlowVoD: 9,
  161. // used by abr-controller
  162. abrEwmaDefaultEstimate: 5e5,
  163. // 500 kbps // used by abr-controller
  164. abrBandWidthFactor: 0.95,
  165. // used by abr-controller
  166. abrBandWidthUpFactor: 0.7,
  167. // used by abr-controller
  168. abrMaxWithRealBitrate: false,
  169. // used by abr-controller
  170. maxStarvationDelay: 4,
  171. // used by abr-controller
  172. maxLoadingDelay: 4,
  173. // used by abr-controller
  174. minAutoBitrate: 0,
  175. // used by hls
  176. emeEnabled: false,
  177. // used by eme-controller
  178. widevineLicenseUrl: undefined,
  179. // used by eme-controller
  180. drmSystemOptions: {},
  181. // used by eme-controller
  182. requestMediaKeySystemAccessFunc: _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_7__.requestMediaKeySystemAccess,
  183. // used by eme-controller
  184. testBandwidth: true,
  185. progressive: false,
  186. lowLatencyMode: true,
  187. cmcd: undefined,
  188. enableDateRangeMetadataCues: true,
  189. enableEmsgMetadataCues: true,
  190. enableID3MetadataCues: true
  191. }, timelineConfig()), {}, {
  192. subtitleStreamController: false ? 0 : undefined,
  193. subtitleTrackController: false ? 0 : undefined,
  194. timelineController: false ? 0 : undefined,
  195. audioStreamController: false ? 0 : undefined,
  196. audioTrackController: false ? 0 : undefined,
  197. emeController: false ? 0 : undefined,
  198. cmcdController: false ? 0 : undefined
  199. });
  200. function timelineConfig() {
  201. return {
  202. cueHandler: (_controller_audio_stream_controller__WEBPACK_IMPORTED_MODULE_1___default()),
  203. // used by timeline-controller
  204. enableWebVTT: false,
  205. // used by timeline-controller
  206. enableIMSC1: false,
  207. // used by timeline-controller
  208. enableCEA708Captions: false,
  209. // used by timeline-controller
  210. captionsTextTrack1Label: 'English',
  211. // used by timeline-controller
  212. captionsTextTrack1LanguageCode: 'en',
  213. // used by timeline-controller
  214. captionsTextTrack2Label: 'Spanish',
  215. // used by timeline-controller
  216. captionsTextTrack2LanguageCode: 'es',
  217. // used by timeline-controller
  218. captionsTextTrack3Label: 'Unknown CC',
  219. // used by timeline-controller
  220. captionsTextTrack3LanguageCode: '',
  221. // used by timeline-controller
  222. captionsTextTrack4Label: 'Unknown CC',
  223. // used by timeline-controller
  224. captionsTextTrack4LanguageCode: '',
  225. // used by timeline-controller
  226. renderTextTracksNatively: true
  227. };
  228. }
  229. function mergeConfig(defaultConfig, userConfig) {
  230. if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {
  231. throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");
  232. }
  233. if (userConfig.liveMaxLatencyDurationCount !== undefined && (userConfig.liveSyncDurationCount === undefined || userConfig.liveMaxLatencyDurationCount <= userConfig.liveSyncDurationCount)) {
  234. throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');
  235. }
  236. if (userConfig.liveMaxLatencyDuration !== undefined && (userConfig.liveSyncDuration === undefined || userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)) {
  237. throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');
  238. }
  239. return _extends({}, defaultConfig, userConfig);
  240. }
  241. function enableStreamingMode(config) {
  242. var currentLoader = config.loader;
  243. if (currentLoader !== _utils_fetch_loader__WEBPACK_IMPORTED_MODULE_6__["default"] && currentLoader !== _utils_xhr_loader__WEBPACK_IMPORTED_MODULE_5__["default"]) {
  244. // If a developer has configured their own loader, respect that choice
  245. _utils_logger__WEBPACK_IMPORTED_MODULE_8__.logger.log('[config]: Custom loader detected, cannot enable progressive streaming');
  246. config.progressive = false;
  247. } else {
  248. var canStreamProgressively = (0,_utils_fetch_loader__WEBPACK_IMPORTED_MODULE_6__.fetchSupported)();
  249. if (canStreamProgressively) {
  250. config.loader = _utils_fetch_loader__WEBPACK_IMPORTED_MODULE_6__["default"];
  251. config.progressive = true;
  252. config.enableSoftwareAES = true;
  253. _utils_logger__WEBPACK_IMPORTED_MODULE_8__.logger.log('[config]: Progressive streaming enabled, using FetchLoader');
  254. }
  255. }
  256. }
  257. /***/ }),
  258. /***/ "./src/controller/abr-controller.ts":
  259. /*!******************************************!*\
  260. !*** ./src/controller/abr-controller.ts ***!
  261. \******************************************/
  262. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  263. "use strict";
  264. __webpack_require__.r(__webpack_exports__);
  265. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  266. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  267. /* harmony export */ });
  268. /* harmony import */ var _Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
  269. /* harmony import */ var _utils_ewma_bandwidth_estimator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/ewma-bandwidth-estimator */ "./src/utils/ewma-bandwidth-estimator.ts");
  270. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts");
  271. /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
  272. /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
  273. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
  274. 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, _toPropertyKey(descriptor.key), descriptor); } }
  275. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  276. function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
  277. function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
  278. var AbrController = /*#__PURE__*/function () {
  279. function AbrController(hls) {
  280. this.hls = void 0;
  281. this.lastLoadedFragLevel = 0;
  282. this._nextAutoLevel = -1;
  283. this.timer = void 0;
  284. this.onCheck = this._abandonRulesCheck.bind(this);
  285. this.fragCurrent = null;
  286. this.partCurrent = null;
  287. this.bitrateTestDelay = 0;
  288. this.bwEstimator = void 0;
  289. this.hls = hls;
  290. var config = hls.config;
  291. this.bwEstimator = new _utils_ewma_bandwidth_estimator__WEBPACK_IMPORTED_MODULE_1__["default"](config.abrEwmaSlowVoD, config.abrEwmaFastVoD, config.abrEwmaDefaultEstimate);
  292. this.registerListeners();
  293. }
  294. var _proto = AbrController.prototype;
  295. _proto.registerListeners = function registerListeners() {
  296. var hls = this.hls;
  297. hls.on(_events__WEBPACK_IMPORTED_MODULE_2__.Events.FRAG_LOADING, this.onFragLoading, this);
  298. hls.on(_events__WEBPACK_IMPORTED_MODULE_2__.Events.FRAG_LOADED, this.onFragLoaded, this);
  299. hls.on(_events__WEBPACK_IMPORTED_MODULE_2__.Events.FRAG_BUFFERED, this.onFragBuffered, this);
  300. hls.on(_events__WEBPACK_IMPORTED_MODULE_2__.Events.LEVEL_LOADED, this.onLevelLoaded, this);
  301. hls.on(_events__WEBPACK_IMPORTED_MODULE_2__.Events.ERROR, this.onError, this);
  302. };
  303. _proto.unregisterListeners = function unregisterListeners() {
  304. var hls = this.hls;
  305. hls.off(_events__WEBPACK_IMPORTED_MODULE_2__.Events.FRAG_LOADING, this.onFragLoading, this);
  306. hls.off(_events__WEBPACK_IMPORTED_MODULE_2__.Events.FRAG_LOADED, this.onFragLoaded, this);
  307. hls.off(_events__WEBPACK_IMPORTED_MODULE_2__.Events.FRAG_BUFFERED, this.onFragBuffered, this);
  308. hls.off(_events__WEBPACK_IMPORTED_MODULE_2__.Events.LEVEL_LOADED, this.onLevelLoaded, this);
  309. hls.off(_events__WEBPACK_IMPORTED_MODULE_2__.Events.ERROR, this.onError, this);
  310. };
  311. _proto.destroy = function destroy() {
  312. this.unregisterListeners();
  313. this.clearTimer();
  314. // @ts-ignore
  315. this.hls = this.onCheck = null;
  316. this.fragCurrent = this.partCurrent = null;
  317. };
  318. _proto.onFragLoading = function onFragLoading(event, data) {
  319. var frag = data.frag;
  320. if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_4__.PlaylistLevelType.MAIN) {
  321. if (!this.timer) {
  322. var _data$part;
  323. this.fragCurrent = frag;
  324. this.partCurrent = (_data$part = data.part) != null ? _data$part : null;
  325. this.timer = self.setInterval(this.onCheck, 100);
  326. }
  327. }
  328. };
  329. _proto.onLevelLoaded = function onLevelLoaded(event, data) {
  330. var config = this.hls.config;
  331. if (data.details.live) {
  332. this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive);
  333. } else {
  334. this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD);
  335. }
  336. }
  337. /*
  338. This method monitors the download rate of the current fragment, and will downswitch if that fragment will not load
  339. quickly enough to prevent underbuffering
  340. */;
  341. _proto._abandonRulesCheck = function _abandonRulesCheck() {
  342. var frag = this.fragCurrent,
  343. part = this.partCurrent,
  344. hls = this.hls;
  345. var autoLevelEnabled = hls.autoLevelEnabled,
  346. config = hls.config,
  347. media = hls.media;
  348. if (!frag || !media) {
  349. return;
  350. }
  351. var stats = part ? part.stats : frag.stats;
  352. var duration = part ? part.duration : frag.duration;
  353. // If frag loading is aborted, complete, or from lowest level, stop timer and return
  354. if (stats.aborted || stats.loaded && stats.loaded === stats.total || frag.level === 0) {
  355. this.clearTimer();
  356. // reset forced auto level value so that next level will be selected
  357. this._nextAutoLevel = -1;
  358. return;
  359. }
  360. // This check only runs if we're in ABR mode and actually playing
  361. if (!autoLevelEnabled || media.paused || !media.playbackRate || !media.readyState) {
  362. return;
  363. }
  364. var bufferInfo = hls.mainForwardBufferInfo;
  365. if (bufferInfo === null) {
  366. return;
  367. }
  368. var requestDelay = performance.now() - stats.loading.start;
  369. var playbackRate = Math.abs(media.playbackRate);
  370. // In order to work with a stable bandwidth, only begin monitoring bandwidth after half of the fragment has been loaded
  371. if (requestDelay <= 500 * duration / playbackRate) {
  372. return;
  373. }
  374. var loadedFirstByte = stats.loaded && stats.loading.first;
  375. var bwEstimate = this.bwEstimator.getEstimate();
  376. var levels = hls.levels,
  377. minAutoLevel = hls.minAutoLevel;
  378. var level = levels[frag.level];
  379. var expectedLen = stats.total || Math.max(stats.loaded, Math.round(duration * level.maxBitrate / 8));
  380. var loadRate = loadedFirstByte ? stats.loaded * 1000 / requestDelay : 0;
  381. // fragLoadDelay is an estimate of the time (in seconds) it will take to buffer the remainder of the fragment
  382. var fragLoadedDelay = loadRate ? (expectedLen - stats.loaded) / loadRate : expectedLen * 8 / bwEstimate;
  383. // bufferStarvationDelay is an estimate of the amount time (in seconds) it will take to exhaust the buffer
  384. var bufferStarvationDelay = bufferInfo.len / playbackRate;
  385. // Only downswitch if the time to finish loading the current fragment is greater than the amount of buffer left
  386. if (fragLoadedDelay <= bufferStarvationDelay) {
  387. return;
  388. }
  389. var fragLevelNextLoadedDelay = Number.POSITIVE_INFINITY;
  390. var nextLoadLevel;
  391. // Iterate through lower level and try to find the largest one that avoids rebuffering
  392. for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
  393. // compute time to load next fragment at lower level
  394. // 0.8 : consider only 80% of current bw to be conservative
  395. // 8 = bits per byte (bps/Bps)
  396. var levelNextBitrate = levels[nextLoadLevel].maxBitrate;
  397. fragLevelNextLoadedDelay = loadRate ? duration * levelNextBitrate / (8 * 0.8 * loadRate) : duration * levelNextBitrate / bwEstimate;
  398. if (fragLevelNextLoadedDelay < bufferStarvationDelay) {
  399. break;
  400. }
  401. }
  402. // Only emergency switch down if it takes less time to load a new fragment at lowest level instead of continuing
  403. // to load the current one
  404. if (fragLevelNextLoadedDelay >= fragLoadedDelay) {
  405. return;
  406. }
  407. _utils_logger__WEBPACK_IMPORTED_MODULE_5__.logger.warn("Fragment " + frag.sn + (part ? ' part ' + part.index : '') + " of level " + frag.level + " is loading too slowly and will cause an underbuffer; aborting and switching to level " + nextLoadLevel + "\n Current BW estimate: " + ((0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(bwEstimate) ? (bwEstimate / 1024).toFixed(3) : 'Unknown') + " Kb/s\n Estimated load time for current fragment: " + fragLoadedDelay.toFixed(3) + " s\n Estimated load time for the next fragment: " + fragLevelNextLoadedDelay.toFixed(3) + " s\n Time to underbuffer: " + bufferStarvationDelay.toFixed(3) + " s");
  408. hls.nextLoadLevel = nextLoadLevel;
  409. if (loadedFirstByte) {
  410. // If there has been loading progress, sample bandwidth
  411. this.bwEstimator.sample(requestDelay, stats.loaded);
  412. }
  413. this.clearTimer();
  414. if (frag.loader || frag.keyLoader) {
  415. this.fragCurrent = this.partCurrent = null;
  416. frag.abortRequests();
  417. }
  418. hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__.Events.FRAG_LOAD_EMERGENCY_ABORTED, {
  419. frag: frag,
  420. part: part,
  421. stats: stats
  422. });
  423. };
  424. _proto.onFragLoaded = function onFragLoaded(event, _ref) {
  425. var frag = _ref.frag,
  426. part = _ref.part;
  427. if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_4__.PlaylistLevelType.MAIN && (0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(frag.sn)) {
  428. var stats = part ? part.stats : frag.stats;
  429. var duration = part ? part.duration : frag.duration;
  430. // stop monitoring bw once frag loaded
  431. this.clearTimer();
  432. // store level id after successful fragment load
  433. this.lastLoadedFragLevel = frag.level;
  434. // reset forced auto level value so that next level will be selected
  435. this._nextAutoLevel = -1;
  436. // compute level average bitrate
  437. if (this.hls.config.abrMaxWithRealBitrate) {
  438. var level = this.hls.levels[frag.level];
  439. var loadedBytes = (level.loaded ? level.loaded.bytes : 0) + stats.loaded;
  440. var loadedDuration = (level.loaded ? level.loaded.duration : 0) + duration;
  441. level.loaded = {
  442. bytes: loadedBytes,
  443. duration: loadedDuration
  444. };
  445. level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
  446. }
  447. if (frag.bitrateTest) {
  448. var fragBufferedData = {
  449. stats: stats,
  450. frag: frag,
  451. part: part,
  452. id: frag.type
  453. };
  454. this.onFragBuffered(_events__WEBPACK_IMPORTED_MODULE_2__.Events.FRAG_BUFFERED, fragBufferedData);
  455. }
  456. }
  457. };
  458. _proto.onFragBuffered = function onFragBuffered(event, data) {
  459. var frag = data.frag,
  460. part = data.part;
  461. var stats = part ? part.stats : frag.stats;
  462. if (stats.aborted) {
  463. return;
  464. }
  465. // Only count non-alt-audio frags which were actually buffered in our BW calculations
  466. if (frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_4__.PlaylistLevelType.MAIN || frag.sn === 'initSegment') {
  467. return;
  468. }
  469. // Use the difference between parsing and request instead of buffering and request to compute fragLoadingProcessing;
  470. // rationale is that buffer appending only happens once media is attached. This can happen when config.startFragPrefetch
  471. // is used. If we used buffering in that case, our BW estimate sample will be very large.
  472. var processingMs = stats.parsing.end - stats.loading.start;
  473. this.bwEstimator.sample(processingMs, stats.loaded);
  474. stats.bwEstimate = this.bwEstimator.getEstimate();
  475. if (frag.bitrateTest) {
  476. this.bitrateTestDelay = processingMs / 1000;
  477. } else {
  478. this.bitrateTestDelay = 0;
  479. }
  480. };
  481. _proto.onError = function onError(event, data) {
  482. // stop timer in case of frag loading error
  483. switch (data.details) {
  484. case _errors__WEBPACK_IMPORTED_MODULE_3__.ErrorDetails.FRAG_LOAD_ERROR:
  485. case _errors__WEBPACK_IMPORTED_MODULE_3__.ErrorDetails.FRAG_LOAD_TIMEOUT:
  486. this.clearTimer();
  487. break;
  488. default:
  489. break;
  490. }
  491. };
  492. _proto.clearTimer = function clearTimer() {
  493. self.clearInterval(this.timer);
  494. this.timer = undefined;
  495. }
  496. // return next auto level
  497. ;
  498. _proto.getNextABRAutoLevel = function getNextABRAutoLevel() {
  499. var fragCurrent = this.fragCurrent,
  500. partCurrent = this.partCurrent,
  501. hls = this.hls;
  502. var maxAutoLevel = hls.maxAutoLevel,
  503. config = hls.config,
  504. minAutoLevel = hls.minAutoLevel,
  505. media = hls.media;
  506. var currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  507. var pos = media ? media.currentTime : 0;
  508. // playbackRate is the absolute value of the playback rate; if media.playbackRate is 0, we use 1 to load as
  509. // if we're playing back at the normal rate.
  510. var playbackRate = media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1.0;
  511. var avgbw = this.bwEstimator ? this.bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate;
  512. // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.
  513. var bufferInfo = hls.mainForwardBufferInfo;
  514. var bufferStarvationDelay = (bufferInfo ? bufferInfo.len : 0) / playbackRate;
  515. // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all
  516. var bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, config.abrBandWidthFactor, config.abrBandWidthUpFactor);
  517. if (bestLevel >= 0) {
  518. return bestLevel;
  519. }
  520. _utils_logger__WEBPACK_IMPORTED_MODULE_5__.logger.trace((bufferStarvationDelay ? 'rebuffering expected' : 'buffer is empty') + ", finding optimal quality level");
  521. // not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering
  522. // if no matching level found, logic will return 0
  523. var maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay;
  524. var bwFactor = config.abrBandWidthFactor;
  525. var bwUpFactor = config.abrBandWidthUpFactor;
  526. if (!bufferStarvationDelay) {
  527. // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test
  528. var bitrateTestDelay = this.bitrateTestDelay;
  529. if (bitrateTestDelay) {
  530. // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value
  531. // max video loading delay used in automatic start level selection :
  532. // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +
  533. // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )
  534. // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration
  535. var maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
  536. maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
  537. _utils_logger__WEBPACK_IMPORTED_MODULE_5__.logger.trace("bitrate test took " + Math.round(1000 * bitrateTestDelay) + "ms, set first fragment max fetchDuration to " + Math.round(1000 * maxStarvationDelay) + " ms");
  538. // don't use conservative factor on bitrate test
  539. bwFactor = bwUpFactor = 1;
  540. }
  541. }
  542. bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay + maxStarvationDelay, bwFactor, bwUpFactor);
  543. return Math.max(bestLevel, 0);
  544. };
  545. _proto.findBestLevel = function findBestLevel(currentBw, minAutoLevel, maxAutoLevel, maxFetchDuration, bwFactor, bwUpFactor) {
  546. var _level$details;
  547. var fragCurrent = this.fragCurrent,
  548. partCurrent = this.partCurrent,
  549. currentLevel = this.lastLoadedFragLevel;
  550. var levels = this.hls.levels;
  551. var level = levels[currentLevel];
  552. var live = !!(level !== null && level !== void 0 && (_level$details = level.details) !== null && _level$details !== void 0 && _level$details.live);
  553. var currentCodecSet = level === null || level === void 0 ? void 0 : level.codecSet;
  554. var currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  555. for (var i = maxAutoLevel; i >= minAutoLevel; i--) {
  556. var levelInfo = levels[i];
  557. if (!levelInfo || currentCodecSet && levelInfo.codecSet !== currentCodecSet) {
  558. continue;
  559. }
  560. var levelDetails = levelInfo.details;
  561. var avgDuration = (partCurrent ? levelDetails === null || levelDetails === void 0 ? void 0 : levelDetails.partTarget : levelDetails === null || levelDetails === void 0 ? void 0 : levelDetails.averagetargetduration) || currentFragDuration;
  562. var adjustedbw = void 0;
  563. // follow algorithm captured from stagefright :
  564. // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
  565. // Pick the highest bandwidth stream below or equal to estimated bandwidth.
  566. // consider only 80% of the available bandwidth, but if we are switching up,
  567. // be even more conservative (70%) to avoid overestimating and immediately
  568. // switching back.
  569. if (i <= currentLevel) {
  570. adjustedbw = bwFactor * currentBw;
  571. } else {
  572. adjustedbw = bwUpFactor * currentBw;
  573. }
  574. var bitrate = levels[i].maxBitrate;
  575. var fetchDuration = bitrate * avgDuration / adjustedbw;
  576. _utils_logger__WEBPACK_IMPORTED_MODULE_5__.logger.trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: " + i + "/" + Math.round(adjustedbw) + "/" + bitrate + "/" + avgDuration + "/" + maxFetchDuration + "/" + fetchDuration);
  577. // if adjusted bw is greater than level bitrate AND
  578. if (adjustedbw > bitrate && (
  579. // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
  580. // 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 ...
  581. // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1
  582. fetchDuration === 0 || !(0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(fetchDuration) || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration)) {
  583. // as we are looping from highest to lowest, this will return the best achievable quality level
  584. return i;
  585. }
  586. }
  587. // not enough time budget even with quality level 0 ... rebuffering might happen
  588. return -1;
  589. };
  590. _createClass(AbrController, [{
  591. key: "nextAutoLevel",
  592. get: function get() {
  593. var forcedAutoLevel = this._nextAutoLevel;
  594. var bwEstimator = this.bwEstimator;
  595. // in case next auto level has been forced, and bw not available or not reliable, return forced value
  596. if (forcedAutoLevel !== -1 && !bwEstimator.canEstimate()) {
  597. return forcedAutoLevel;
  598. }
  599. // compute next level using ABR logic
  600. var nextABRAutoLevel = this.getNextABRAutoLevel();
  601. // use forced auto level when ABR selected level has errored
  602. if (forcedAutoLevel !== -1 && this.hls.levels[nextABRAutoLevel].loadError) {
  603. return forcedAutoLevel;
  604. }
  605. // if forced auto level has been defined, use it to cap ABR computed quality level
  606. if (forcedAutoLevel !== -1) {
  607. nextABRAutoLevel = Math.min(forcedAutoLevel, nextABRAutoLevel);
  608. }
  609. return nextABRAutoLevel;
  610. },
  611. set: function set(nextLevel) {
  612. this._nextAutoLevel = nextLevel;
  613. }
  614. }]);
  615. return AbrController;
  616. }();
  617. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (AbrController);
  618. /***/ }),
  619. /***/ "./src/controller/base-playlist-controller.ts":
  620. /*!****************************************************!*\
  621. !*** ./src/controller/base-playlist-controller.ts ***!
  622. \****************************************************/
  623. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  624. "use strict";
  625. __webpack_require__.r(__webpack_exports__);
  626. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  627. /* harmony export */ "default": () => (/* binding */ BasePlaylistController)
  628. /* harmony export */ });
  629. /* harmony import */ var _Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
  630. /* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../types/level */ "./src/types/level.ts");
  631. /* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.ts");
  632. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
  633. /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
  634. var BasePlaylistController = /*#__PURE__*/function () {
  635. function BasePlaylistController(hls, logPrefix) {
  636. this.hls = void 0;
  637. this.timer = -1;
  638. this.requestScheduled = -1;
  639. this.canLoad = false;
  640. this.retryCount = 0;
  641. this.log = void 0;
  642. this.warn = void 0;
  643. this.log = _utils_logger__WEBPACK_IMPORTED_MODULE_3__.logger.log.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_3__.logger, logPrefix + ":");
  644. this.warn = _utils_logger__WEBPACK_IMPORTED_MODULE_3__.logger.warn.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_3__.logger, logPrefix + ":");
  645. this.hls = hls;
  646. }
  647. var _proto = BasePlaylistController.prototype;
  648. _proto.destroy = function destroy() {
  649. this.clearTimer();
  650. // @ts-ignore
  651. this.hls = this.log = this.warn = null;
  652. };
  653. _proto.onError = function onError(event, data) {
  654. if (data.fatal && data.type === _errors__WEBPACK_IMPORTED_MODULE_4__.ErrorTypes.NETWORK_ERROR) {
  655. this.clearTimer();
  656. }
  657. };
  658. _proto.clearTimer = function clearTimer() {
  659. clearTimeout(this.timer);
  660. this.timer = -1;
  661. };
  662. _proto.startLoad = function startLoad() {
  663. this.canLoad = true;
  664. this.retryCount = 0;
  665. this.requestScheduled = -1;
  666. this.loadPlaylist();
  667. };
  668. _proto.stopLoad = function stopLoad() {
  669. this.canLoad = false;
  670. this.clearTimer();
  671. };
  672. _proto.switchParams = function switchParams(playlistUri, previous) {
  673. var renditionReports = previous === null || previous === void 0 ? void 0 : previous.renditionReports;
  674. if (renditionReports) {
  675. for (var i = 0; i < renditionReports.length; i++) {
  676. var attr = renditionReports[i];
  677. var uri = '' + attr.URI;
  678. if (uri === playlistUri.slice(-uri.length)) {
  679. var msn = parseInt(attr['LAST-MSN']);
  680. var part = parseInt(attr['LAST-PART']);
  681. if (previous && this.hls.config.lowLatencyMode) {
  682. var currentGoal = Math.min(previous.age - previous.partTarget, previous.targetduration);
  683. if (part !== undefined && currentGoal > previous.partTarget) {
  684. part += 1;
  685. }
  686. }
  687. if ((0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(msn)) {
  688. return new _types_level__WEBPACK_IMPORTED_MODULE_1__.HlsUrlParameters(msn, (0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(part) ? part : undefined, _types_level__WEBPACK_IMPORTED_MODULE_1__.HlsSkip.No);
  689. }
  690. }
  691. }
  692. }
  693. };
  694. _proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {
  695. if (this.requestScheduled === -1) {
  696. this.requestScheduled = self.performance.now();
  697. }
  698. };
  699. _proto.shouldLoadTrack = function shouldLoadTrack(track) {
  700. return this.canLoad && track && !!track.url && (!track.details || track.details.live);
  701. };
  702. _proto.playlistLoaded = function playlistLoaded(index, data, previousDetails) {
  703. var _this = this;
  704. var details = data.details,
  705. stats = data.stats;
  706. // Set last updated date-time
  707. var now = self.performance.now();
  708. var elapsed = stats.loading.first ? Math.max(0, now - stats.loading.first) : 0;
  709. details.advancedDateTime = Date.now() - elapsed;
  710. // if current playlist is a live playlist, arm a timer to reload it
  711. if (details.live || previousDetails !== null && previousDetails !== void 0 && previousDetails.live) {
  712. details.reloaded(previousDetails);
  713. if (previousDetails) {
  714. this.log("live playlist " + index + " " + (details.advanced ? 'REFRESHED ' + details.lastPartSn + '-' + details.lastPartIndex : 'MISSED'));
  715. }
  716. // Merge live playlists to adjust fragment starts and fill in delta playlist skipped segments
  717. if (previousDetails && details.fragments.length > 0) {
  718. (0,_level_helper__WEBPACK_IMPORTED_MODULE_2__.mergeDetails)(previousDetails, details);
  719. }
  720. if (!this.canLoad || !details.live) {
  721. return;
  722. }
  723. var deliveryDirectives;
  724. var msn = undefined;
  725. var part = undefined;
  726. if (details.canBlockReload && details.endSN && details.advanced) {
  727. // Load level with LL-HLS delivery directives
  728. var lowLatencyMode = this.hls.config.lowLatencyMode;
  729. var lastPartSn = details.lastPartSn;
  730. var endSn = details.endSN;
  731. var lastPartIndex = details.lastPartIndex;
  732. var hasParts = lastPartIndex !== -1;
  733. var lastPart = lastPartSn === endSn;
  734. // When low latency mode is disabled, we'll skip part requests once the last part index is found
  735. var nextSnStartIndex = lowLatencyMode ? 0 : lastPartIndex;
  736. if (hasParts) {
  737. msn = lastPart ? endSn + 1 : lastPartSn;
  738. part = lastPart ? nextSnStartIndex : lastPartIndex + 1;
  739. } else {
  740. msn = endSn + 1;
  741. }
  742. // Low-Latency CDN Tune-in: "age" header and time since load indicates we're behind by more than one part
  743. // Update directives to obtain the Playlist that has the estimated additional duration of media
  744. var lastAdvanced = details.age;
  745. var cdnAge = lastAdvanced + details.ageHeader;
  746. var currentGoal = Math.min(cdnAge - details.partTarget, details.targetduration * 1.5);
  747. if (currentGoal > 0) {
  748. if (previousDetails && currentGoal > previousDetails.tuneInGoal) {
  749. // If we attempted to get the next or latest playlist update, but currentGoal increased,
  750. // then we either can't catchup, or the "age" header cannot be trusted.
  751. this.warn("CDN Tune-in goal increased from: " + previousDetails.tuneInGoal + " to: " + currentGoal + " with playlist age: " + details.age);
  752. currentGoal = 0;
  753. } else {
  754. var segments = Math.floor(currentGoal / details.targetduration);
  755. msn += segments;
  756. if (part !== undefined) {
  757. var parts = Math.round(currentGoal % details.targetduration / details.partTarget);
  758. part += parts;
  759. }
  760. this.log("CDN Tune-in age: " + details.ageHeader + "s last advanced " + lastAdvanced.toFixed(2) + "s goal: " + currentGoal + " skip sn " + segments + " to part " + part);
  761. }
  762. details.tuneInGoal = currentGoal;
  763. }
  764. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  765. if (lowLatencyMode || !lastPart) {
  766. this.loadPlaylist(deliveryDirectives);
  767. return;
  768. }
  769. } else {
  770. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  771. }
  772. var bufferInfo = this.hls.mainForwardBufferInfo;
  773. var position = bufferInfo ? bufferInfo.end - bufferInfo.len : 0;
  774. var distanceToLiveEdgeMs = (details.edge - position) * 1000;
  775. var reloadInterval = (0,_level_helper__WEBPACK_IMPORTED_MODULE_2__.computeReloadInterval)(details, distanceToLiveEdgeMs);
  776. if (!details.updated) {
  777. this.requestScheduled = -1;
  778. } else if (now > this.requestScheduled + reloadInterval) {
  779. this.requestScheduled = stats.loading.start;
  780. }
  781. if (msn !== undefined && details.canBlockReload) {
  782. this.requestScheduled = stats.loading.first + reloadInterval - (details.partTarget * 1000 || 1000);
  783. } else {
  784. this.requestScheduled = (this.requestScheduled === -1 ? now : this.requestScheduled) + reloadInterval;
  785. }
  786. var estimatedTimeUntilUpdate = this.requestScheduled - now;
  787. estimatedTimeUntilUpdate = Math.max(0, estimatedTimeUntilUpdate);
  788. this.log("reload live playlist " + index + " in " + Math.round(estimatedTimeUntilUpdate) + " ms");
  789. // this.log(
  790. // `live reload ${details.updated ? 'REFRESHED' : 'MISSED'}
  791. // reload in ${estimatedTimeUntilUpdate / 1000}
  792. // round trip ${(stats.loading.end - stats.loading.start) / 1000}
  793. // diff ${
  794. // (reloadInterval -
  795. // (estimatedTimeUntilUpdate + stats.loading.end - stats.loading.start)) /
  796. // 1000
  797. // }
  798. // reload interval ${reloadInterval / 1000}
  799. // target duration ${details.targetduration}
  800. // distance to edge ${distanceToLiveEdgeMs / 1000}`
  801. // );
  802. this.timer = self.setTimeout(function () {
  803. return _this.loadPlaylist(deliveryDirectives);
  804. }, estimatedTimeUntilUpdate);
  805. } else {
  806. this.clearTimer();
  807. }
  808. };
  809. _proto.getDeliveryDirectives = function getDeliveryDirectives(details, previousDeliveryDirectives, msn, part) {
  810. var skip = (0,_types_level__WEBPACK_IMPORTED_MODULE_1__.getSkipValue)(details, msn);
  811. if (previousDeliveryDirectives !== null && previousDeliveryDirectives !== void 0 && previousDeliveryDirectives.skip && details.deltaUpdateFailed) {
  812. msn = previousDeliveryDirectives.msn;
  813. part = previousDeliveryDirectives.part;
  814. skip = _types_level__WEBPACK_IMPORTED_MODULE_1__.HlsSkip.No;
  815. }
  816. return new _types_level__WEBPACK_IMPORTED_MODULE_1__.HlsUrlParameters(msn, part, skip);
  817. };
  818. _proto.retryLoadingOrFail = function retryLoadingOrFail(errorEvent) {
  819. var _this2 = this;
  820. var config = this.hls.config;
  821. var retry = this.retryCount < config.levelLoadingMaxRetry;
  822. if (retry) {
  823. var _errorEvent$context;
  824. this.requestScheduled = -1;
  825. this.retryCount++;
  826. if (errorEvent.details.indexOf('LoadTimeOut') > -1 && (_errorEvent$context = errorEvent.context) !== null && _errorEvent$context !== void 0 && _errorEvent$context.deliveryDirectives) {
  827. // The LL-HLS request already timed out so retry immediately
  828. this.warn("retry playlist loading #" + this.retryCount + " after \"" + errorEvent.details + "\"");
  829. this.loadPlaylist();
  830. } else {
  831. // exponential backoff capped to max retry timeout
  832. var delay = Math.min(Math.pow(2, this.retryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout);
  833. // Schedule level/track reload
  834. this.timer = self.setTimeout(function () {
  835. return _this2.loadPlaylist();
  836. }, delay);
  837. this.warn("retry playlist loading #" + this.retryCount + " in " + delay + " ms after \"" + errorEvent.details + "\"");
  838. }
  839. } else {
  840. this.warn("cannot recover from error \"" + errorEvent.details + "\"");
  841. // stopping live reloading timer if any
  842. this.clearTimer();
  843. // switch error to fatal
  844. errorEvent.fatal = true;
  845. }
  846. return retry;
  847. };
  848. return BasePlaylistController;
  849. }();
  850. /***/ }),
  851. /***/ "./src/controller/base-stream-controller.ts":
  852. /*!**************************************************!*\
  853. !*** ./src/controller/base-stream-controller.ts ***!
  854. \**************************************************/
  855. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  856. "use strict";
  857. __webpack_require__.r(__webpack_exports__);
  858. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  859. /* harmony export */ "State": () => (/* binding */ State),
  860. /* harmony export */ "default": () => (/* binding */ BaseStreamController)
  861. /* harmony export */ });
  862. /* harmony import */ var _Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
  863. /* harmony import */ var _task_loop__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../task-loop */ "./src/task-loop.ts");
  864. /* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.ts");
  865. /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
  866. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
  867. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../events */ "./src/events.ts");
  868. /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
  869. /* harmony import */ var _types_transmuxer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../types/transmuxer */ "./src/types/transmuxer.ts");
  870. /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
  871. /* harmony import */ var _utils_discontinuities__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/discontinuities */ "./src/utils/discontinuities.ts");
  872. /* harmony import */ var _fragment_finders__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./fragment-finders */ "./src/controller/fragment-finders.ts");
  873. /* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.ts");
  874. /* harmony import */ var _loader_fragment_loader__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../loader/fragment-loader */ "./src/loader/fragment-loader.ts");
  875. /* harmony import */ var _loader_key_loader__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../loader/key-loader */ "./src/loader/key-loader.ts");
  876. /* harmony import */ var _crypt_decrypter__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../crypt/decrypter */ "./src/crypt/decrypter.ts");
  877. /* harmony import */ var _utils_time_ranges__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../utils/time-ranges */ "./src/utils/time-ranges.ts");
  878. /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
  879. 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, _toPropertyKey(descriptor.key), descriptor); } }
  880. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  881. function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
  882. function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
  883. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  884. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  885. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  886. var State = {
  887. STOPPED: 'STOPPED',
  888. IDLE: 'IDLE',
  889. KEY_LOADING: 'KEY_LOADING',
  890. FRAG_LOADING: 'FRAG_LOADING',
  891. FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
  892. WAITING_TRACK: 'WAITING_TRACK',
  893. PARSING: 'PARSING',
  894. PARSED: 'PARSED',
  895. ENDED: 'ENDED',
  896. ERROR: 'ERROR',
  897. WAITING_INIT_PTS: 'WAITING_INIT_PTS',
  898. WAITING_LEVEL: 'WAITING_LEVEL'
  899. };
  900. var BaseStreamController = /*#__PURE__*/function (_TaskLoop) {
  901. _inheritsLoose(BaseStreamController, _TaskLoop);
  902. function BaseStreamController(hls, fragmentTracker, logPrefix) {
  903. var _this;
  904. _this = _TaskLoop.call(this) || this;
  905. _this.hls = void 0;
  906. _this.fragPrevious = null;
  907. _this.fragCurrent = null;
  908. _this.fragmentTracker = void 0;
  909. _this.transmuxer = null;
  910. _this._state = State.STOPPED;
  911. _this.media = null;
  912. _this.mediaBuffer = null;
  913. _this.config = void 0;
  914. _this.bitrateTest = false;
  915. _this.lastCurrentTime = 0;
  916. _this.nextLoadPosition = 0;
  917. _this.startPosition = 0;
  918. _this.loadedmetadata = false;
  919. _this.fragLoadError = 0;
  920. _this.retryDate = 0;
  921. _this.levels = null;
  922. _this.fragmentLoader = void 0;
  923. _this.keyLoader = void 0;
  924. _this.levelLastLoaded = null;
  925. _this.startFragRequested = false;
  926. _this.decrypter = void 0;
  927. _this.initPTS = [];
  928. _this.onvseeking = null;
  929. _this.onvended = null;
  930. _this.logPrefix = '';
  931. _this.log = void 0;
  932. _this.warn = void 0;
  933. _this.logPrefix = logPrefix;
  934. _this.log = _utils_logger__WEBPACK_IMPORTED_MODULE_4__.logger.log.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_4__.logger, logPrefix + ":");
  935. _this.warn = _utils_logger__WEBPACK_IMPORTED_MODULE_4__.logger.warn.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_4__.logger, logPrefix + ":");
  936. _this.hls = hls;
  937. _this.fragmentLoader = new _loader_fragment_loader__WEBPACK_IMPORTED_MODULE_12__["default"](hls.config);
  938. _this.keyLoader = new _loader_key_loader__WEBPACK_IMPORTED_MODULE_13__["default"](hls.config);
  939. _this.fragmentTracker = fragmentTracker;
  940. _this.config = hls.config;
  941. _this.decrypter = new _crypt_decrypter__WEBPACK_IMPORTED_MODULE_14__["default"](hls.config);
  942. hls.on(_events__WEBPACK_IMPORTED_MODULE_5__.Events.LEVEL_SWITCHING, _this.onLevelSwitching, _assertThisInitialized(_this));
  943. return _this;
  944. }
  945. var _proto = BaseStreamController.prototype;
  946. _proto.doTick = function doTick() {
  947. this.onTickEnd();
  948. };
  949. _proto.onTickEnd = function onTickEnd() {}
  950. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  951. ;
  952. _proto.startLoad = function startLoad(startPosition) {};
  953. _proto.stopLoad = function stopLoad() {
  954. this.fragmentLoader.abort();
  955. this.keyLoader.abort();
  956. var frag = this.fragCurrent;
  957. if (frag) {
  958. frag.abortRequests();
  959. this.fragmentTracker.removeFragment(frag);
  960. }
  961. this.resetTransmuxer();
  962. this.fragCurrent = null;
  963. this.fragPrevious = null;
  964. this.clearInterval();
  965. this.clearNextTick();
  966. this.state = State.STOPPED;
  967. };
  968. _proto._streamEnded = function _streamEnded(bufferInfo, levelDetails) {
  969. var fragCurrent = this.fragCurrent,
  970. fragmentTracker = this.fragmentTracker;
  971. // we just got done loading the final fragment and there is no other buffered range after ...
  972. // rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between
  973. // so we should not switch to ENDED in that case, to be able to buffer them
  974. if (!levelDetails.live && fragCurrent && this.media &&
  975. // NOTE: Because of the way parts are currently parsed/represented in the playlist, we can end up
  976. // in situations where the current fragment is actually greater than levelDetails.endSN. While
  977. // this feels like the "wrong place" to account for that, this is a narrower/safer change than
  978. // updating e.g. M3U8Parser::parseLevelPlaylist().
  979. fragCurrent.sn >= levelDetails.endSN && !bufferInfo.nextStart) {
  980. var partList = levelDetails.partList;
  981. // Since the last part isn't guaranteed to correspond to fragCurrent for ll-hls, check instead if the last part is buffered.
  982. if (partList !== null && partList !== void 0 && partList.length) {
  983. var lastPart = partList[partList.length - 1];
  984. // Checking the midpoint of the part for potential margin of error and related issues.
  985. // NOTE: Technically I believe parts could yield content that is < the computed duration (including potential a duration of 0)
  986. // and still be spec-compliant, so there may still be edge cases here. Likewise, there could be issues in end of stream
  987. // part mismatches for independent audio and video playlists/segments.
  988. var lastPartBuffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__.BufferHelper.isBuffered(this.media, lastPart.start + lastPart.duration / 2);
  989. return lastPartBuffered;
  990. }
  991. var fragState = fragmentTracker.getState(fragCurrent);
  992. return fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__.FragmentState.PARTIAL || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__.FragmentState.OK;
  993. }
  994. return false;
  995. };
  996. _proto.onMediaAttached = function onMediaAttached(event, data) {
  997. var media = this.media = this.mediaBuffer = data.media;
  998. this.onvseeking = this.onMediaSeeking.bind(this);
  999. this.onvended = this.onMediaEnded.bind(this);
  1000. media.addEventListener('seeking', this.onvseeking);
  1001. media.addEventListener('ended', this.onvended);
  1002. var config = this.config;
  1003. if (this.levels && config.autoStartLoad && this.state === State.STOPPED) {
  1004. this.startLoad(config.startPosition);
  1005. }
  1006. };
  1007. _proto.onMediaDetaching = function onMediaDetaching() {
  1008. var media = this.media;
  1009. if (media !== null && media !== void 0 && media.ended) {
  1010. this.log('MSE detaching and video ended, reset startPosition');
  1011. this.startPosition = this.lastCurrentTime = 0;
  1012. }
  1013. // remove video listeners
  1014. if (media && this.onvseeking && this.onvended) {
  1015. media.removeEventListener('seeking', this.onvseeking);
  1016. media.removeEventListener('ended', this.onvended);
  1017. this.onvseeking = this.onvended = null;
  1018. }
  1019. this.media = this.mediaBuffer = null;
  1020. this.loadedmetadata = false;
  1021. this.fragmentTracker.removeAllFragments();
  1022. this.stopLoad();
  1023. };
  1024. _proto.onMediaSeeking = function onMediaSeeking() {
  1025. var config = this.config,
  1026. fragCurrent = this.fragCurrent,
  1027. media = this.media,
  1028. mediaBuffer = this.mediaBuffer,
  1029. state = this.state;
  1030. var currentTime = media ? media.currentTime : 0;
  1031. var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__.BufferHelper.bufferInfo(mediaBuffer ? mediaBuffer : media, currentTime, config.maxBufferHole);
  1032. this.log("media seeking to " + ((0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(currentTime) ? currentTime.toFixed(3) : currentTime) + ", state: " + state);
  1033. if (state === State.ENDED) {
  1034. this.resetLoadingState();
  1035. } else if (fragCurrent) {
  1036. // Seeking while frag load is in progress
  1037. var tolerance = config.maxFragLookUpTolerance;
  1038. var fragStartOffset = fragCurrent.start - tolerance;
  1039. var fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;
  1040. // if seeking out of buffered range or into new one
  1041. if (!bufferInfo.len || fragEndOffset < bufferInfo.start || fragStartOffset > bufferInfo.end) {
  1042. var pastFragment = currentTime > fragEndOffset;
  1043. // if the seek position is outside the current fragment range
  1044. if (currentTime < fragStartOffset || pastFragment) {
  1045. if (pastFragment && fragCurrent.loader) {
  1046. this.log('seeking outside of buffer while fragment load in progress, cancel fragment load');
  1047. fragCurrent.abortRequests();
  1048. }
  1049. this.resetLoadingState();
  1050. }
  1051. }
  1052. }
  1053. if (media) {
  1054. this.lastCurrentTime = currentTime;
  1055. }
  1056. // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
  1057. if (!this.loadedmetadata && !bufferInfo.len) {
  1058. this.nextLoadPosition = this.startPosition = currentTime;
  1059. }
  1060. // Async tick to speed up processing
  1061. this.tickImmediate();
  1062. };
  1063. _proto.onMediaEnded = function onMediaEnded() {
  1064. // reset startPosition and lastCurrentTime to restart playback @ stream beginning
  1065. this.startPosition = this.lastCurrentTime = 0;
  1066. };
  1067. _proto.onLevelSwitching = function onLevelSwitching(event, data) {
  1068. this.fragLoadError = 0;
  1069. };
  1070. _proto.onHandlerDestroying = function onHandlerDestroying() {
  1071. this.stopLoad();
  1072. _TaskLoop.prototype.onHandlerDestroying.call(this);
  1073. };
  1074. _proto.onHandlerDestroyed = function onHandlerDestroyed() {
  1075. this.state = State.STOPPED;
  1076. this.hls.off(_events__WEBPACK_IMPORTED_MODULE_5__.Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  1077. if (this.fragmentLoader) {
  1078. this.fragmentLoader.destroy();
  1079. }
  1080. if (this.keyLoader) {
  1081. this.keyLoader.destroy();
  1082. }
  1083. if (this.decrypter) {
  1084. this.decrypter.destroy();
  1085. }
  1086. this.hls = this.log = this.warn = this.decrypter = this.keyLoader = this.fragmentLoader = this.fragmentTracker = null;
  1087. _TaskLoop.prototype.onHandlerDestroyed.call(this);
  1088. };
  1089. _proto.loadFragment = function loadFragment(frag, levelDetails, targetBufferTime) {
  1090. this._loadFragForPlayback(frag, levelDetails, targetBufferTime);
  1091. };
  1092. _proto._loadFragForPlayback = function _loadFragForPlayback(frag, levelDetails, targetBufferTime) {
  1093. var _this2 = this;
  1094. var progressCallback = function progressCallback(data) {
  1095. if (_this2.fragContextChanged(frag)) {
  1096. _this2.warn("Fragment " + frag.sn + (data.part ? ' p: ' + data.part.index : '') + " of level " + frag.level + " was dropped during download.");
  1097. _this2.fragmentTracker.removeFragment(frag);
  1098. return;
  1099. }
  1100. frag.stats.chunkCount++;
  1101. _this2._handleFragmentLoadProgress(data);
  1102. };
  1103. this._doFragLoad(frag, levelDetails, targetBufferTime, progressCallback).then(function (data) {
  1104. if (!data) {
  1105. // if we're here we probably needed to backtrack or are waiting for more parts
  1106. return;
  1107. }
  1108. _this2.fragLoadError = 0;
  1109. var state = _this2.state;
  1110. if (_this2.fragContextChanged(frag)) {
  1111. if (state === State.FRAG_LOADING || !_this2.fragCurrent && state === State.PARSING) {
  1112. _this2.fragmentTracker.removeFragment(frag);
  1113. _this2.state = State.IDLE;
  1114. }
  1115. return;
  1116. }
  1117. if ('payload' in data) {
  1118. _this2.log("Loaded fragment " + frag.sn + " of level " + frag.level);
  1119. _this2.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__.Events.FRAG_LOADED, data);
  1120. }
  1121. // Pass through the whole payload; controllers not implementing progressive loading receive data from this callback
  1122. _this2._handleFragmentLoadComplete(data);
  1123. }).catch(function (reason) {
  1124. if (_this2.state === State.STOPPED || _this2.state === State.ERROR) {
  1125. return;
  1126. }
  1127. _this2.warn(reason);
  1128. _this2.resetFragmentLoading(frag);
  1129. });
  1130. };
  1131. _proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset, type) {
  1132. if (type === void 0) {
  1133. type = null;
  1134. }
  1135. if (!(startOffset - endOffset)) {
  1136. return;
  1137. }
  1138. // When alternate audio is playing, the audio-stream-controller is responsible for the audio buffer. Otherwise,
  1139. // passing a null type flushes both buffers
  1140. var flushScope = {
  1141. startOffset: startOffset,
  1142. endOffset: endOffset,
  1143. type: type
  1144. };
  1145. // Reset load errors on flush
  1146. this.fragLoadError = 0;
  1147. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__.Events.BUFFER_FLUSHING, flushScope);
  1148. };
  1149. _proto._loadInitSegment = function _loadInitSegment(frag, details) {
  1150. var _this3 = this;
  1151. this._doFragLoad(frag, details).then(function (data) {
  1152. if (!data || _this3.fragContextChanged(frag) || !_this3.levels) {
  1153. throw new Error('init load aborted');
  1154. }
  1155. return data;
  1156. }).then(function (data) {
  1157. var hls = _this3.hls;
  1158. var payload = data.payload;
  1159. var decryptData = frag.decryptdata;
  1160. // check to see if the payload needs to be decrypted
  1161. if (payload && payload.byteLength > 0 && decryptData && decryptData.key && decryptData.iv && decryptData.method === 'AES-128') {
  1162. var startTime = self.performance.now();
  1163. // decrypt the subtitles
  1164. return _this3.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer).then(function (decryptedData) {
  1165. var endTime = self.performance.now();
  1166. hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__.Events.FRAG_DECRYPTED, {
  1167. frag: frag,
  1168. payload: decryptedData,
  1169. stats: {
  1170. tstart: startTime,
  1171. tdecrypt: endTime
  1172. }
  1173. });
  1174. data.payload = decryptedData;
  1175. return data;
  1176. });
  1177. }
  1178. return data;
  1179. }).then(function (data) {
  1180. var fragCurrent = _this3.fragCurrent,
  1181. hls = _this3.hls,
  1182. levels = _this3.levels;
  1183. if (!levels) {
  1184. throw new Error('init load aborted, missing levels');
  1185. }
  1186. var details = levels[frag.level].details;
  1187. console.assert(details, 'Level details are defined when init segment is loaded');
  1188. var stats = frag.stats;
  1189. _this3.state = State.IDLE;
  1190. _this3.fragLoadError = 0;
  1191. frag.data = new Uint8Array(data.payload);
  1192. stats.parsing.start = stats.buffering.start = self.performance.now();
  1193. stats.parsing.end = stats.buffering.end = self.performance.now();
  1194. // Silence FRAG_BUFFERED event if fragCurrent is null
  1195. if (data.frag === fragCurrent) {
  1196. hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__.Events.FRAG_BUFFERED, {
  1197. stats: stats,
  1198. frag: fragCurrent,
  1199. part: null,
  1200. id: frag.type
  1201. });
  1202. }
  1203. _this3.tick();
  1204. }).catch(function (reason) {
  1205. if (_this3.state === State.STOPPED || _this3.state === State.ERROR) {
  1206. return;
  1207. }
  1208. _this3.warn(reason);
  1209. _this3.resetFragmentLoading(frag);
  1210. });
  1211. };
  1212. _proto.fragContextChanged = function fragContextChanged(frag) {
  1213. var fragCurrent = this.fragCurrent;
  1214. return !frag || !fragCurrent || frag.level !== fragCurrent.level || frag.sn !== fragCurrent.sn || frag.urlId !== fragCurrent.urlId;
  1215. };
  1216. _proto.fragBufferedComplete = function fragBufferedComplete(frag, part) {
  1217. var _this$fragCurrent, _this$fragPrevious;
  1218. var media = this.mediaBuffer ? this.mediaBuffer : this.media;
  1219. this.log("Buffered " + frag.type + " sn: " + frag.sn + (part ? ' part: ' + part.index : '') + " of " + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + " " + frag.level + " " + (media ? _utils_time_ranges__WEBPACK_IMPORTED_MODULE_15__["default"].toString(_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__.BufferHelper.getBuffered(media)) : '(detached)'));
  1220. this.state = State.IDLE;
  1221. if (!media) {
  1222. return;
  1223. }
  1224. if (!this.loadedmetadata && frag.type == _types_loader__WEBPACK_IMPORTED_MODULE_16__.PlaylistLevelType.MAIN && media.buffered.length && ((_this$fragCurrent = this.fragCurrent) === null || _this$fragCurrent === void 0 ? void 0 : _this$fragCurrent.sn) === ((_this$fragPrevious = this.fragPrevious) === null || _this$fragPrevious === void 0 ? void 0 : _this$fragPrevious.sn)) {
  1225. this.loadedmetadata = true;
  1226. this.seekToStartPos();
  1227. }
  1228. this.tick();
  1229. };
  1230. _proto.seekToStartPos = function seekToStartPos() {};
  1231. _proto._handleFragmentLoadComplete = function _handleFragmentLoadComplete(fragLoadedEndData) {
  1232. var transmuxer = this.transmuxer;
  1233. if (!transmuxer) {
  1234. return;
  1235. }
  1236. var frag = fragLoadedEndData.frag,
  1237. part = fragLoadedEndData.part,
  1238. partsLoaded = fragLoadedEndData.partsLoaded;
  1239. // If we did not load parts, or loaded all parts, we have complete (not partial) fragment data
  1240. var complete = !partsLoaded || partsLoaded.length === 0 || partsLoaded.some(function (fragLoaded) {
  1241. return !fragLoaded;
  1242. });
  1243. var chunkMeta = new _types_transmuxer__WEBPACK_IMPORTED_MODULE_7__.ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount + 1, 0, part ? part.index : -1, !complete);
  1244. transmuxer.flush(chunkMeta);
  1245. }
  1246. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  1247. ;
  1248. _proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(frag) {};
  1249. _proto._doFragLoad = function _doFragLoad(frag, details, targetBufferTime, progressCallback) {
  1250. var _frag$decryptdata,
  1251. _this4 = this;
  1252. if (targetBufferTime === void 0) {
  1253. targetBufferTime = null;
  1254. }
  1255. if (!this.levels) {
  1256. throw new Error('frag load aborted, missing levels');
  1257. }
  1258. var keyLoadingPromise = null;
  1259. if (frag.encrypted && !((_frag$decryptdata = frag.decryptdata) !== null && _frag$decryptdata !== void 0 && _frag$decryptdata.key)) {
  1260. this.log("Loading key for " + frag.sn + " of [" + details.startSN + "-" + details.endSN + "], " + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + " " + frag.level);
  1261. this.state = State.KEY_LOADING;
  1262. this.fragCurrent = frag;
  1263. keyLoadingPromise = this.keyLoader.load(frag).then(function (keyLoadedData) {
  1264. if (keyLoadedData && !_this4.fragContextChanged(keyLoadedData.frag)) {
  1265. _this4.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__.Events.KEY_LOADED, keyLoadedData);
  1266. return keyLoadedData;
  1267. }
  1268. });
  1269. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__.Events.KEY_LOADING, {
  1270. frag: frag
  1271. });
  1272. this.throwIfFragContextChanged('KEY_LOADING');
  1273. }
  1274. targetBufferTime = Math.max(frag.start, targetBufferTime || 0);
  1275. if (this.config.lowLatencyMode && details) {
  1276. var partList = details.partList;
  1277. if (partList && progressCallback) {
  1278. if (targetBufferTime > frag.end && details.fragmentHint) {
  1279. frag = details.fragmentHint;
  1280. }
  1281. var partIndex = this.getNextPart(partList, frag, targetBufferTime);
  1282. if (partIndex > -1) {
  1283. var part = partList[partIndex];
  1284. this.log("Loading part sn: " + frag.sn + " p: " + part.index + " cc: " + frag.cc + " of playlist [" + details.startSN + "-" + details.endSN + "] parts [0-" + partIndex + "-" + (partList.length - 1) + "] " + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + ": " + frag.level + ", target: " + parseFloat(targetBufferTime.toFixed(3)));
  1285. this.nextLoadPosition = part.start + part.duration;
  1286. this.state = State.FRAG_LOADING;
  1287. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__.Events.FRAG_LOADING, {
  1288. frag: frag,
  1289. part: partList[partIndex],
  1290. targetBufferTime: targetBufferTime
  1291. });
  1292. this.throwIfFragContextChanged('FRAG_LOADING parts');
  1293. if (keyLoadingPromise) {
  1294. return keyLoadingPromise.then(function (keyLoadedData) {
  1295. if (!keyLoadedData || _this4.fragContextChanged(keyLoadedData === null || keyLoadedData === void 0 ? void 0 : keyLoadedData.frag)) {
  1296. return null;
  1297. }
  1298. return _this4.doFragPartsLoad(frag, partList, partIndex, progressCallback);
  1299. }).catch(function (error) {
  1300. return _this4.handleFragLoadError(error);
  1301. });
  1302. }
  1303. return this.doFragPartsLoad(frag, partList, partIndex, progressCallback).catch(function (error) {
  1304. return _this4.handleFragLoadError(error);
  1305. });
  1306. } else if (!frag.url || this.loadedEndOfParts(partList, targetBufferTime)) {
  1307. // Fragment hint has no parts
  1308. return Promise.resolve(null);
  1309. }
  1310. }
  1311. }
  1312. this.log("Loading fragment " + frag.sn + " cc: " + frag.cc + " " + (details ? 'of [' + details.startSN + '-' + details.endSN + '] ' : '') + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + ": " + frag.level + ", target: " + parseFloat(targetBufferTime.toFixed(3)));
  1313. // Don't update nextLoadPosition for fragments which are not buffered
  1314. if ((0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(frag.sn) && !this.bitrateTest) {
  1315. this.nextLoadPosition = frag.start + frag.duration;
  1316. }
  1317. this.state = State.FRAG_LOADING;
  1318. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__.Events.FRAG_LOADING, {
  1319. frag: frag,
  1320. targetBufferTime: targetBufferTime
  1321. });
  1322. this.throwIfFragContextChanged('FRAG_LOADING');
  1323. // Load key before streaming fragment data
  1324. var dataOnProgress = this.config.progressive;
  1325. if (dataOnProgress && keyLoadingPromise) {
  1326. return keyLoadingPromise.then(function (keyLoadedData) {
  1327. if (!keyLoadedData || _this4.fragContextChanged(keyLoadedData === null || keyLoadedData === void 0 ? void 0 : keyLoadedData.frag)) {
  1328. return null;
  1329. }
  1330. return _this4.fragmentLoader.load(frag, progressCallback);
  1331. }).catch(function (error) {
  1332. return _this4.handleFragLoadError(error);
  1333. });
  1334. }
  1335. // load unencrypted fragment data with progress event,
  1336. // or handle fragment result after key and fragment are finished loading
  1337. return Promise.all([this.fragmentLoader.load(frag, dataOnProgress ? progressCallback : undefined), keyLoadingPromise]).then(function (_ref) {
  1338. var fragLoadedData = _ref[0];
  1339. if (!dataOnProgress && fragLoadedData && progressCallback) {
  1340. progressCallback(fragLoadedData);
  1341. }
  1342. return fragLoadedData;
  1343. }).catch(function (error) {
  1344. return _this4.handleFragLoadError(error);
  1345. });
  1346. };
  1347. _proto.throwIfFragContextChanged = function throwIfFragContextChanged(context) {
  1348. // exit if context changed during event loop
  1349. if (this.fragCurrent === null) {
  1350. throw new Error("frag load aborted, context changed in " + context);
  1351. }
  1352. };
  1353. _proto.doFragPartsLoad = function doFragPartsLoad(frag, partList, partIndex, progressCallback) {
  1354. var _this5 = this;
  1355. return new Promise(function (resolve, reject) {
  1356. var partsLoaded = [];
  1357. var loadPartIndex = function loadPartIndex(index) {
  1358. var part = partList[index];
  1359. _this5.fragmentLoader.loadPart(frag, part, progressCallback).then(function (partLoadedData) {
  1360. partsLoaded[part.index] = partLoadedData;
  1361. var loadedPart = partLoadedData.part;
  1362. _this5.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__.Events.FRAG_LOADED, partLoadedData);
  1363. var nextPart = partList[index + 1];
  1364. if (nextPart && nextPart.fragment === frag) {
  1365. loadPartIndex(index + 1);
  1366. } else {
  1367. return resolve({
  1368. frag: frag,
  1369. part: loadedPart,
  1370. partsLoaded: partsLoaded
  1371. });
  1372. }
  1373. }).catch(reject);
  1374. };
  1375. loadPartIndex(partIndex);
  1376. });
  1377. };
  1378. _proto.handleFragLoadError = function handleFragLoadError(_ref2) {
  1379. var data = _ref2.data;
  1380. if (data && data.details === _errors__WEBPACK_IMPORTED_MODULE_6__.ErrorDetails.INTERNAL_ABORTED) {
  1381. this.handleFragLoadAborted(data.frag, data.part);
  1382. } else {
  1383. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__.Events.ERROR, data);
  1384. }
  1385. return null;
  1386. };
  1387. _proto._handleTransmuxerFlush = function _handleTransmuxerFlush(chunkMeta) {
  1388. var context = this.getCurrentContext(chunkMeta);
  1389. if (!context || this.state !== State.PARSING) {
  1390. if (!this.fragCurrent) {
  1391. this.state = State.IDLE;
  1392. }
  1393. return;
  1394. }
  1395. var frag = context.frag,
  1396. part = context.part,
  1397. level = context.level;
  1398. var now = self.performance.now();
  1399. frag.stats.parsing.end = now;
  1400. if (part) {
  1401. part.stats.parsing.end = now;
  1402. }
  1403. this.updateLevelTiming(frag, part, level, chunkMeta.partial);
  1404. };
  1405. _proto.getCurrentContext = function getCurrentContext(chunkMeta) {
  1406. var levels = this.levels;
  1407. var levelIndex = chunkMeta.level,
  1408. sn = chunkMeta.sn,
  1409. partIndex = chunkMeta.part;
  1410. if (!levels || !levels[levelIndex]) {
  1411. this.warn("Levels object was unset while buffering fragment " + sn + " of level " + levelIndex + ". The current chunk will not be buffered.");
  1412. return null;
  1413. }
  1414. var level = levels[levelIndex];
  1415. var part = partIndex > -1 ? (0,_level_helper__WEBPACK_IMPORTED_MODULE_11__.getPartWith)(level, sn, partIndex) : null;
  1416. var frag = part ? part.fragment : (0,_level_helper__WEBPACK_IMPORTED_MODULE_11__.getFragmentWithSN)(level, sn, this.fragCurrent);
  1417. if (!frag) {
  1418. return null;
  1419. }
  1420. return {
  1421. frag: frag,
  1422. part: part,
  1423. level: level
  1424. };
  1425. };
  1426. _proto.bufferFragmentData = function bufferFragmentData(data, frag, part, chunkMeta) {
  1427. if (!data || this.state !== State.PARSING) {
  1428. return;
  1429. }
  1430. var data1 = data.data1,
  1431. data2 = data.data2;
  1432. var buffer = data1;
  1433. if (data1 && data2) {
  1434. // Combine the moof + mdat so that we buffer with a single append
  1435. buffer = (0,_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_8__.appendUint8Array)(data1, data2);
  1436. }
  1437. if (!buffer || !buffer.length) {
  1438. return;
  1439. }
  1440. var segment = {
  1441. type: data.type,
  1442. frag: frag,
  1443. part: part,
  1444. chunkMeta: chunkMeta,
  1445. parent: frag.type,
  1446. data: buffer
  1447. };
  1448. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__.Events.BUFFER_APPENDING, segment);
  1449. if (data.dropped && data.independent && !part) {
  1450. // Clear buffer so that we reload previous segments sequentially if required
  1451. this.flushBufferGap(frag);
  1452. }
  1453. };
  1454. _proto.flushBufferGap = function flushBufferGap(frag) {
  1455. var media = this.media;
  1456. if (!media) {
  1457. return;
  1458. }
  1459. // If currentTime is not buffered, clear the back buffer so that we can backtrack as much as needed
  1460. if (!_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__.BufferHelper.isBuffered(media, media.currentTime)) {
  1461. this.flushMainBuffer(0, frag.start);
  1462. return;
  1463. }
  1464. // Remove back-buffer without interrupting playback to allow back tracking
  1465. var currentTime = media.currentTime;
  1466. var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__.BufferHelper.bufferInfo(media, currentTime, 0);
  1467. var fragDuration = frag.duration;
  1468. var segmentFraction = Math.min(this.config.maxFragLookUpTolerance * 2, fragDuration * 0.25);
  1469. var start = Math.max(Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction), currentTime + segmentFraction);
  1470. if (frag.start - start > segmentFraction) {
  1471. this.flushMainBuffer(start, frag.start);
  1472. }
  1473. };
  1474. _proto.getFwdBufferInfo = function getFwdBufferInfo(bufferable, type) {
  1475. var config = this.config;
  1476. var pos = this.getLoadPosition();
  1477. if (!(0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(pos)) {
  1478. return null;
  1479. }
  1480. var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__.BufferHelper.bufferInfo(bufferable, pos, config.maxBufferHole);
  1481. // Workaround flaw in getting forward buffer when maxBufferHole is smaller than gap at current pos
  1482. if (bufferInfo.len === 0 && bufferInfo.nextStart !== undefined) {
  1483. var bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type);
  1484. if (bufferedFragAtPos && bufferInfo.nextStart < bufferedFragAtPos.end) {
  1485. return _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__.BufferHelper.bufferInfo(bufferable, pos, Math.max(bufferInfo.nextStart, config.maxBufferHole));
  1486. }
  1487. }
  1488. return bufferInfo;
  1489. };
  1490. _proto.getMaxBufferLength = function getMaxBufferLength(levelBitrate) {
  1491. var config = this.config;
  1492. var maxBufLen;
  1493. if (levelBitrate) {
  1494. maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
  1495. } else {
  1496. maxBufLen = config.maxBufferLength;
  1497. }
  1498. return Math.min(maxBufLen, config.maxMaxBufferLength);
  1499. };
  1500. _proto.reduceMaxBufferLength = function reduceMaxBufferLength(threshold) {
  1501. var config = this.config;
  1502. var minLength = threshold || config.maxBufferLength;
  1503. if (config.maxMaxBufferLength >= minLength) {
  1504. // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
  1505. config.maxMaxBufferLength /= 2;
  1506. this.warn("Reduce max buffer length to " + config.maxMaxBufferLength + "s");
  1507. return true;
  1508. }
  1509. return false;
  1510. };
  1511. _proto.getNextFragment = function getNextFragment(pos, levelDetails) {
  1512. var fragments = levelDetails.fragments;
  1513. var fragLen = fragments.length;
  1514. if (!fragLen) {
  1515. return null;
  1516. }
  1517. // find fragment index, contiguous with end of buffer position
  1518. var config = this.config;
  1519. var start = fragments[0].start;
  1520. var frag;
  1521. if (levelDetails.live) {
  1522. var initialLiveManifestSize = config.initialLiveManifestSize;
  1523. if (fragLen < initialLiveManifestSize) {
  1524. this.warn("Not enough fragments to start playback (have: " + fragLen + ", need: " + initialLiveManifestSize + ")");
  1525. return null;
  1526. }
  1527. // The real fragment start times for a live stream are only known after the PTS range for that level is known.
  1528. // In order to discover the range, we load the best matching fragment for that level and demux it.
  1529. // Do not load using live logic if the starting frag is requested - we want to use getFragmentAtPosition() so that
  1530. // we get the fragment matching that start time
  1531. if (!levelDetails.PTSKnown && !this.startFragRequested && this.startPosition === -1) {
  1532. frag = this.getInitialLiveFragment(levelDetails, fragments);
  1533. this.startPosition = frag ? this.hls.liveSyncPosition || frag.start : pos;
  1534. }
  1535. } else if (pos <= start) {
  1536. // VoD playlist: if loadPosition before start of playlist, load first fragment
  1537. frag = fragments[0];
  1538. }
  1539. // If we haven't run into any special cases already, just load the fragment most closely matching the requested position
  1540. if (!frag) {
  1541. var end = config.lowLatencyMode ? levelDetails.partEnd : levelDetails.fragmentEnd;
  1542. frag = this.getFragmentAtPosition(pos, end, levelDetails);
  1543. }
  1544. return this.mapToInitFragWhenRequired(frag);
  1545. };
  1546. _proto.mapToInitFragWhenRequired = function mapToInitFragWhenRequired(frag) {
  1547. // If an initSegment is present, it must be buffered first
  1548. if (frag !== null && frag !== void 0 && frag.initSegment && !(frag !== null && frag !== void 0 && frag.initSegment.data) && !this.bitrateTest) {
  1549. return frag.initSegment;
  1550. }
  1551. return frag;
  1552. };
  1553. _proto.getNextPart = function getNextPart(partList, frag, targetBufferTime) {
  1554. var nextPart = -1;
  1555. var contiguous = false;
  1556. var independentAttrOmitted = true;
  1557. for (var i = 0, len = partList.length; i < len; i++) {
  1558. var part = partList[i];
  1559. independentAttrOmitted = independentAttrOmitted && !part.independent;
  1560. if (nextPart > -1 && targetBufferTime < part.start) {
  1561. break;
  1562. }
  1563. var loaded = part.loaded;
  1564. if (!loaded && (contiguous || part.independent || independentAttrOmitted) && part.fragment === frag) {
  1565. nextPart = i;
  1566. }
  1567. contiguous = loaded;
  1568. }
  1569. return nextPart;
  1570. };
  1571. _proto.loadedEndOfParts = function loadedEndOfParts(partList, targetBufferTime) {
  1572. var lastPart = partList[partList.length - 1];
  1573. return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;
  1574. }
  1575. /*
  1576. This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the
  1577. "sliding" of the playlist, which is its offset from the start of playback. After sliding we can compute the real
  1578. start and end times for each fragment in the playlist (after which this method will not need to be called).
  1579. */;
  1580. _proto.getInitialLiveFragment = function getInitialLiveFragment(levelDetails, fragments) {
  1581. var fragPrevious = this.fragPrevious;
  1582. var frag = null;
  1583. if (fragPrevious) {
  1584. if (levelDetails.hasProgramDateTime) {
  1585. // Prefer using PDT, because it can be accurate enough to choose the correct fragment without knowing the level sliding
  1586. this.log("Live playlist, switching playlist, load frag with same PDT: " + fragPrevious.programDateTime);
  1587. frag = (0,_fragment_finders__WEBPACK_IMPORTED_MODULE_10__.findFragmentByPDT)(fragments, fragPrevious.endProgramDateTime, this.config.maxFragLookUpTolerance);
  1588. }
  1589. if (!frag) {
  1590. // SN does not need to be accurate between renditions, but depending on the packaging it may be so.
  1591. var targetSN = fragPrevious.sn + 1;
  1592. if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
  1593. var fragNext = fragments[targetSN - levelDetails.startSN];
  1594. // Ensure that we're staying within the continuity range, since PTS resets upon a new range
  1595. if (fragPrevious.cc === fragNext.cc) {
  1596. frag = fragNext;
  1597. this.log("Live playlist, switching playlist, load frag with next SN: " + frag.sn);
  1598. }
  1599. }
  1600. // It's important to stay within the continuity range if available; otherwise the fragments in the playlist
  1601. // will have the wrong start times
  1602. if (!frag) {
  1603. frag = (0,_fragment_finders__WEBPACK_IMPORTED_MODULE_10__.findFragWithCC)(fragments, fragPrevious.cc);
  1604. if (frag) {
  1605. this.log("Live playlist, switching playlist, load frag with same CC: " + frag.sn);
  1606. }
  1607. }
  1608. }
  1609. } else {
  1610. // Find a new start fragment when fragPrevious is null
  1611. var liveStart = this.hls.liveSyncPosition;
  1612. if (liveStart !== null) {
  1613. frag = this.getFragmentAtPosition(liveStart, this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge, levelDetails);
  1614. }
  1615. }
  1616. return frag;
  1617. }
  1618. /*
  1619. This method finds the best matching fragment given the provided position.
  1620. */;
  1621. _proto.getFragmentAtPosition = function getFragmentAtPosition(bufferEnd, end, levelDetails) {
  1622. var config = this.config;
  1623. var fragPrevious = this.fragPrevious;
  1624. var fragments = levelDetails.fragments,
  1625. endSN = levelDetails.endSN;
  1626. var fragmentHint = levelDetails.fragmentHint;
  1627. var tolerance = config.maxFragLookUpTolerance;
  1628. var loadingParts = !!(config.lowLatencyMode && levelDetails.partList && fragmentHint);
  1629. if (loadingParts && fragmentHint && !this.bitrateTest) {
  1630. // Include incomplete fragment with parts at end
  1631. fragments = fragments.concat(fragmentHint);
  1632. endSN = fragmentHint.sn;
  1633. }
  1634. var frag;
  1635. if (bufferEnd < end) {
  1636. var lookupTolerance = bufferEnd > end - tolerance ? 0 : tolerance;
  1637. // Remove the tolerance if it would put the bufferEnd past the actual end of stream
  1638. // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
  1639. frag = (0,_fragment_finders__WEBPACK_IMPORTED_MODULE_10__.findFragmentByPTS)(fragPrevious, fragments, bufferEnd, lookupTolerance);
  1640. } else {
  1641. // reach end of playlist
  1642. frag = fragments[fragments.length - 1];
  1643. }
  1644. if (frag) {
  1645. var curSNIdx = frag.sn - levelDetails.startSN;
  1646. // Move fragPrevious forward to support forcing the next fragment to load
  1647. // when the buffer catches up to a previously buffered range.
  1648. if (this.fragmentTracker.getState(frag) === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__.FragmentState.OK) {
  1649. fragPrevious = frag;
  1650. }
  1651. if (fragPrevious && frag.sn === fragPrevious.sn && !loadingParts) {
  1652. // Force the next fragment to load if the previous one was already selected. This can occasionally happen with
  1653. // non-uniform fragment durations
  1654. var sameLevel = fragPrevious && frag.level === fragPrevious.level;
  1655. if (sameLevel) {
  1656. var nextFrag = fragments[curSNIdx + 1];
  1657. if (frag.sn < endSN && this.fragmentTracker.getState(nextFrag) !== _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__.FragmentState.OK) {
  1658. this.log("SN " + frag.sn + " just loaded, load next one: " + nextFrag.sn);
  1659. frag = nextFrag;
  1660. } else {
  1661. frag = null;
  1662. }
  1663. }
  1664. }
  1665. }
  1666. return frag;
  1667. };
  1668. _proto.synchronizeToLiveEdge = function synchronizeToLiveEdge(levelDetails) {
  1669. var config = this.config,
  1670. media = this.media;
  1671. if (!media) {
  1672. return;
  1673. }
  1674. var liveSyncPosition = this.hls.liveSyncPosition;
  1675. var currentTime = media.currentTime;
  1676. var start = levelDetails.fragments[0].start;
  1677. var end = levelDetails.edge;
  1678. var withinSlidingWindow = currentTime >= start - config.maxFragLookUpTolerance && currentTime <= end;
  1679. // Continue if we can seek forward to sync position or if current time is outside of sliding window
  1680. if (liveSyncPosition !== null && media.duration > liveSyncPosition && (currentTime < liveSyncPosition || !withinSlidingWindow)) {
  1681. // Continue if buffer is starving or if current time is behind max latency
  1682. var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
  1683. if (!withinSlidingWindow && media.readyState < 4 || currentTime < end - maxLatency) {
  1684. if (!this.loadedmetadata) {
  1685. this.nextLoadPosition = liveSyncPosition;
  1686. }
  1687. // Only seek if ready and there is not a significant forward buffer available for playback
  1688. if (media.readyState) {
  1689. this.warn("Playback: " + currentTime.toFixed(3) + " is located too far from the end of live sliding playlist: " + end + ", reset currentTime to : " + liveSyncPosition.toFixed(3));
  1690. media.currentTime = liveSyncPosition;
  1691. }
  1692. }
  1693. }
  1694. };
  1695. _proto.alignPlaylists = function alignPlaylists(details, previousDetails) {
  1696. var levels = this.levels,
  1697. levelLastLoaded = this.levelLastLoaded,
  1698. fragPrevious = this.fragPrevious;
  1699. var lastLevel = levelLastLoaded !== null ? levels[levelLastLoaded] : null;
  1700. // FIXME: If not for `shouldAlignOnDiscontinuities` requiring fragPrevious.cc,
  1701. // this could all go in level-helper mergeDetails()
  1702. var length = details.fragments.length;
  1703. if (!length) {
  1704. this.warn("No fragments in live playlist");
  1705. return 0;
  1706. }
  1707. var slidingStart = details.fragments[0].start;
  1708. var firstLevelLoad = !previousDetails;
  1709. var aligned = details.alignedSliding && (0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(slidingStart);
  1710. if (firstLevelLoad || !aligned && !slidingStart) {
  1711. (0,_utils_discontinuities__WEBPACK_IMPORTED_MODULE_9__.alignStream)(fragPrevious, lastLevel, details);
  1712. var alignedSlidingStart = details.fragments[0].start;
  1713. this.log("Live playlist sliding: " + alignedSlidingStart.toFixed(2) + " start-sn: " + (previousDetails ? previousDetails.startSN : 'na') + "->" + details.startSN + " prev-sn: " + (fragPrevious ? fragPrevious.sn : 'na') + " fragments: " + length);
  1714. return alignedSlidingStart;
  1715. }
  1716. return slidingStart;
  1717. };
  1718. _proto.waitForCdnTuneIn = function waitForCdnTuneIn(details) {
  1719. // Wait for Low-Latency CDN Tune-in to get an updated playlist
  1720. var advancePartLimit = 3;
  1721. return details.live && details.canBlockReload && details.partTarget && details.tuneInGoal > Math.max(details.partHoldBack, details.partTarget * advancePartLimit);
  1722. };
  1723. _proto.setStartPosition = function setStartPosition(details, sliding) {
  1724. // compute start position if set to -1. use it straight away if value is defined
  1725. var startPosition = this.startPosition;
  1726. if (startPosition < sliding) {
  1727. startPosition = -1;
  1728. }
  1729. if (startPosition === -1 || this.lastCurrentTime === -1) {
  1730. // first, check if start time offset has been set in playlist, if yes, use this value
  1731. var startTimeOffset = details.startTimeOffset;
  1732. if ((0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(startTimeOffset)) {
  1733. startPosition = sliding + startTimeOffset;
  1734. if (startTimeOffset < 0) {
  1735. startPosition += details.totalduration;
  1736. }
  1737. startPosition = Math.min(Math.max(sliding, startPosition), sliding + details.totalduration);
  1738. this.log("Start time offset " + startTimeOffset + " found in playlist, adjust startPosition to " + startPosition);
  1739. this.startPosition = startPosition;
  1740. } else if (details.live) {
  1741. // Leave this.startPosition at -1, so that we can use `getInitialLiveFragment` logic when startPosition has
  1742. // not been specified via the config or an as an argument to startLoad (#3736).
  1743. startPosition = this.hls.liveSyncPosition || sliding;
  1744. } else {
  1745. this.startPosition = startPosition = 0;
  1746. }
  1747. this.lastCurrentTime = startPosition;
  1748. }
  1749. this.nextLoadPosition = startPosition;
  1750. };
  1751. _proto.getLoadPosition = function getLoadPosition() {
  1752. var media = this.media;
  1753. // if we have not yet loaded any fragment, start loading from start position
  1754. var pos = 0;
  1755. if (this.loadedmetadata && media) {
  1756. pos = media.currentTime;
  1757. } else if (this.nextLoadPosition) {
  1758. pos = this.nextLoadPosition;
  1759. }
  1760. return pos;
  1761. };
  1762. _proto.handleFragLoadAborted = function handleFragLoadAborted(frag, part) {
  1763. if (this.transmuxer && frag.sn !== 'initSegment' && frag.stats.aborted) {
  1764. this.warn("Fragment " + frag.sn + (part ? ' part' + part.index : '') + " of level " + frag.level + " was aborted");
  1765. this.resetFragmentLoading(frag);
  1766. }
  1767. };
  1768. _proto.resetFragmentLoading = function resetFragmentLoading(frag) {
  1769. if (!this.fragCurrent || !this.fragContextChanged(frag) && this.state !== State.FRAG_LOADING_WAITING_RETRY) {
  1770. this.state = State.IDLE;
  1771. }
  1772. };
  1773. _proto.onFragmentOrKeyLoadError = function onFragmentOrKeyLoadError(filterType, data) {
  1774. if (data.fatal) {
  1775. return;
  1776. }
  1777. var frag = data.frag;
  1778. // Handle frag error related to caller's filterType
  1779. if (!frag || frag.type !== filterType) {
  1780. return;
  1781. }
  1782. var fragCurrent = this.fragCurrent;
  1783. console.assert(fragCurrent && frag.sn === fragCurrent.sn && frag.level === fragCurrent.level && frag.urlId === fragCurrent.urlId, 'Frag load error must match current frag to retry');
  1784. var config = this.config;
  1785. // keep retrying until the limit will be reached
  1786. if (this.fragLoadError + 1 <= config.fragLoadingMaxRetry) {
  1787. if (!this.loadedmetadata) {
  1788. this.startFragRequested = false;
  1789. this.nextLoadPosition = this.startPosition;
  1790. }
  1791. // exponential backoff capped to config.fragLoadingMaxRetryTimeout
  1792. var delay = Math.min(Math.pow(2, this.fragLoadError) * config.fragLoadingRetryDelay, config.fragLoadingMaxRetryTimeout);
  1793. this.warn("Fragment " + frag.sn + " of " + filterType + " " + frag.level + " failed to load, retrying in " + delay + "ms");
  1794. this.retryDate = self.performance.now() + delay;
  1795. this.fragLoadError++;
  1796. this.state = State.FRAG_LOADING_WAITING_RETRY;
  1797. } else if (data.levelRetry) {
  1798. if (filterType === _types_loader__WEBPACK_IMPORTED_MODULE_16__.PlaylistLevelType.AUDIO) {
  1799. // Reset current fragment since audio track audio is essential and may not have a fail-over track
  1800. this.fragCurrent = null;
  1801. }
  1802. // Fragment errors that result in a level switch or redundant fail-over
  1803. // should reset the stream controller state to idle
  1804. this.fragLoadError = 0;
  1805. this.state = State.IDLE;
  1806. } else {
  1807. _utils_logger__WEBPACK_IMPORTED_MODULE_4__.logger.error(data.details + " reaches max retry, redispatch as fatal ...");
  1808. // switch error to fatal
  1809. data.fatal = true;
  1810. this.hls.stopLoad();
  1811. this.state = State.ERROR;
  1812. }
  1813. };
  1814. _proto.afterBufferFlushed = function afterBufferFlushed(media, bufferType, playlistType) {
  1815. if (!media) {
  1816. return;
  1817. }
  1818. // After successful buffer flushing, filter flushed fragments from bufferedFrags use mediaBuffered instead of media
  1819. // (so that we will check against video.buffered ranges in case of alt audio track)
  1820. var bufferedTimeRanges = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__.BufferHelper.getBuffered(media);
  1821. this.fragmentTracker.detectEvictedFragments(bufferType, bufferedTimeRanges, playlistType);
  1822. if (this.state === State.ENDED) {
  1823. this.resetLoadingState();
  1824. }
  1825. };
  1826. _proto.resetLoadingState = function resetLoadingState() {
  1827. this.fragCurrent = null;
  1828. this.fragPrevious = null;
  1829. this.state = State.IDLE;
  1830. };
  1831. _proto.resetStartWhenNotLoaded = function resetStartWhenNotLoaded(level) {
  1832. // if loadedmetadata is not set, it means that first frag request failed
  1833. // in that case, reset startFragRequested flag
  1834. if (!this.loadedmetadata) {
  1835. this.startFragRequested = false;
  1836. var details = this.levels ? this.levels[level].details : null;
  1837. if (details !== null && details !== void 0 && details.live) {
  1838. // Update the start position and return to IDLE to recover live start
  1839. this.startPosition = -1;
  1840. this.setStartPosition(details, 0);
  1841. this.resetLoadingState();
  1842. } else {
  1843. this.nextLoadPosition = this.startPosition;
  1844. }
  1845. }
  1846. };
  1847. _proto.updateLevelTiming = function updateLevelTiming(frag, part, level, partial) {
  1848. var _this6 = this;
  1849. var details = level.details;
  1850. console.assert(!!details, 'level.details must be defined');
  1851. var parsed = Object.keys(frag.elementaryStreams).reduce(function (result, type) {
  1852. var info = frag.elementaryStreams[type];
  1853. if (info) {
  1854. var parsedDuration = info.endPTS - info.startPTS;
  1855. if (parsedDuration <= 0) {
  1856. // Destroy the transmuxer after it's next time offset failed to advance because duration was <= 0.
  1857. // The new transmuxer will be configured with a time offset matching the next fragment start,
  1858. // preventing the timeline from shifting.
  1859. _this6.warn("Could not parse fragment " + frag.sn + " " + type + " duration reliably (" + parsedDuration + ")");
  1860. return result || false;
  1861. }
  1862. var drift = partial ? 0 : (0,_level_helper__WEBPACK_IMPORTED_MODULE_11__.updateFragPTSDTS)(details, frag, info.startPTS, info.endPTS, info.startDTS, info.endDTS);
  1863. _this6.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__.Events.LEVEL_PTS_UPDATED, {
  1864. details: details,
  1865. level: level,
  1866. drift: drift,
  1867. type: type,
  1868. frag: frag,
  1869. start: info.startPTS,
  1870. end: info.endPTS
  1871. });
  1872. return true;
  1873. }
  1874. return result;
  1875. }, false);
  1876. if (!parsed) {
  1877. this.warn("Found no media in fragment " + frag.sn + " of level " + level.id + " resetting transmuxer to fallback to playlist timing");
  1878. this.resetTransmuxer();
  1879. }
  1880. this.state = State.PARSED;
  1881. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__.Events.FRAG_PARSED, {
  1882. frag: frag,
  1883. part: part
  1884. });
  1885. };
  1886. _proto.resetTransmuxer = function resetTransmuxer() {
  1887. if (this.transmuxer) {
  1888. this.transmuxer.destroy();
  1889. this.transmuxer = null;
  1890. }
  1891. };
  1892. _createClass(BaseStreamController, [{
  1893. key: "state",
  1894. get: function get() {
  1895. return this._state;
  1896. },
  1897. set: function set(nextState) {
  1898. var previousState = this._state;
  1899. if (previousState !== nextState) {
  1900. this._state = nextState;
  1901. this.log(previousState + "->" + nextState);
  1902. }
  1903. }
  1904. }]);
  1905. return BaseStreamController;
  1906. }(_task_loop__WEBPACK_IMPORTED_MODULE_1__["default"]);
  1907. /***/ }),
  1908. /***/ "./src/controller/buffer-controller.ts":
  1909. /*!*********************************************!*\
  1910. !*** ./src/controller/buffer-controller.ts ***!
  1911. \*********************************************/
  1912. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  1913. "use strict";
  1914. __webpack_require__.r(__webpack_exports__);
  1915. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  1916. /* harmony export */ "default": () => (/* binding */ BufferController)
  1917. /* harmony export */ });
  1918. /* harmony import */ var _Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
  1919. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
  1920. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
  1921. /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
  1922. /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
  1923. /* harmony import */ var _utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/mediasource-helper */ "./src/utils/mediasource-helper.ts");
  1924. /* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
  1925. /* harmony import */ var _buffer_operation_queue__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./buffer-operation-queue */ "./src/controller/buffer-operation-queue.ts");
  1926. var MediaSource = (0,_utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__.getMediaSource)();
  1927. var VIDEO_CODEC_PROFILE_REPACE = /([ha]vc.)(?:\.[^.,]+)+/;
  1928. var BufferController = /*#__PURE__*/function () {
  1929. // The level details used to determine duration, target-duration and live
  1930. // cache the self generated object url to detect hijack of video tag
  1931. // A queue of buffer operations which require the SourceBuffer to not be updating upon execution
  1932. // References to event listeners for each SourceBuffer, so that they can be referenced for event removal
  1933. // The number of BUFFER_CODEC events received before any sourceBuffers are created
  1934. // The total number of BUFFER_CODEC events received
  1935. // A reference to the attached media element
  1936. // A reference to the active media source
  1937. // counters
  1938. function BufferController(_hls) {
  1939. var _this = this;
  1940. this.details = null;
  1941. this._objectUrl = null;
  1942. this.operationQueue = void 0;
  1943. this.listeners = void 0;
  1944. this.hls = void 0;
  1945. this.bufferCodecEventsExpected = 0;
  1946. this._bufferCodecEventsTotal = 0;
  1947. this.media = null;
  1948. this.mediaSource = null;
  1949. this.appendError = 0;
  1950. this.tracks = {};
  1951. this.pendingTracks = {};
  1952. this.sourceBuffer = void 0;
  1953. this._onMediaSourceOpen = function () {
  1954. var hls = _this.hls,
  1955. media = _this.media,
  1956. mediaSource = _this.mediaSource;
  1957. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.log('[buffer-controller]: Media source opened');
  1958. if (media) {
  1959. _this.updateMediaElementDuration();
  1960. hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.MEDIA_ATTACHED, {
  1961. media: media
  1962. });
  1963. }
  1964. if (mediaSource) {
  1965. // once received, don't listen anymore to sourceopen event
  1966. mediaSource.removeEventListener('sourceopen', _this._onMediaSourceOpen);
  1967. }
  1968. _this.checkPendingTracks();
  1969. };
  1970. this._onMediaSourceClose = function () {
  1971. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.log('[buffer-controller]: Media source closed');
  1972. };
  1973. this._onMediaSourceEnded = function () {
  1974. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.log('[buffer-controller]: Media source ended');
  1975. };
  1976. this.hls = _hls;
  1977. this._initSourceBuffer();
  1978. this.registerListeners();
  1979. }
  1980. var _proto = BufferController.prototype;
  1981. _proto.hasSourceTypes = function hasSourceTypes() {
  1982. return this.getSourceBufferTypes().length > 0 || Object.keys(this.pendingTracks).length > 0;
  1983. };
  1984. _proto.destroy = function destroy() {
  1985. this.unregisterListeners();
  1986. this.details = null;
  1987. };
  1988. _proto.registerListeners = function registerListeners() {
  1989. var hls = this.hls;
  1990. hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  1991. hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  1992. hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.MANIFEST_PARSED, this.onManifestParsed, this);
  1993. hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.BUFFER_RESET, this.onBufferReset, this);
  1994. hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.BUFFER_APPENDING, this.onBufferAppending, this);
  1995. hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.BUFFER_CODECS, this.onBufferCodecs, this);
  1996. hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.BUFFER_EOS, this.onBufferEos, this);
  1997. hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  1998. hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  1999. hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.FRAG_PARSED, this.onFragParsed, this);
  2000. hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.FRAG_CHANGED, this.onFragChanged, this);
  2001. };
  2002. _proto.unregisterListeners = function unregisterListeners() {
  2003. var hls = this.hls;
  2004. hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  2005. hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  2006. hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.MANIFEST_PARSED, this.onManifestParsed, this);
  2007. hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.BUFFER_RESET, this.onBufferReset, this);
  2008. hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.BUFFER_APPENDING, this.onBufferAppending, this);
  2009. hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.BUFFER_CODECS, this.onBufferCodecs, this);
  2010. hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.BUFFER_EOS, this.onBufferEos, this);
  2011. hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  2012. hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  2013. hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.FRAG_PARSED, this.onFragParsed, this);
  2014. hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.FRAG_CHANGED, this.onFragChanged, this);
  2015. };
  2016. _proto._initSourceBuffer = function _initSourceBuffer() {
  2017. this.sourceBuffer = {};
  2018. this.operationQueue = new _buffer_operation_queue__WEBPACK_IMPORTED_MODULE_7__["default"](this.sourceBuffer);
  2019. this.listeners = {
  2020. audio: [],
  2021. video: [],
  2022. audiovideo: []
  2023. };
  2024. };
  2025. _proto.onManifestParsed = function onManifestParsed(event, data) {
  2026. // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller
  2027. // sourcebuffers will be created all at once when the expected nb of tracks will be reached
  2028. // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller
  2029. // it will contain the expected nb of source buffers, no need to compute it
  2030. var codecEvents = 2;
  2031. if (data.audio && !data.video || !data.altAudio) {
  2032. codecEvents = 1;
  2033. }
  2034. this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = codecEvents;
  2035. this.details = null;
  2036. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.log(this.bufferCodecEventsExpected + " bufferCodec event(s) expected");
  2037. };
  2038. _proto.onMediaAttaching = function onMediaAttaching(event, data) {
  2039. var media = this.media = data.media;
  2040. if (media && MediaSource) {
  2041. var ms = this.mediaSource = new MediaSource();
  2042. // MediaSource listeners are arrow functions with a lexical scope, and do not need to be bound
  2043. ms.addEventListener('sourceopen', this._onMediaSourceOpen);
  2044. ms.addEventListener('sourceended', this._onMediaSourceEnded);
  2045. ms.addEventListener('sourceclose', this._onMediaSourceClose);
  2046. // link video and media Source
  2047. media.src = self.URL.createObjectURL(ms);
  2048. // cache the locally generated object url
  2049. this._objectUrl = media.src;
  2050. }
  2051. };
  2052. _proto.onMediaDetaching = function onMediaDetaching() {
  2053. var media = this.media,
  2054. mediaSource = this.mediaSource,
  2055. _objectUrl = this._objectUrl;
  2056. if (mediaSource) {
  2057. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.log('[buffer-controller]: media source detaching');
  2058. if (mediaSource.readyState === 'open') {
  2059. try {
  2060. // endOfStream could trigger exception if any sourcebuffer is in updating state
  2061. // we don't really care about checking sourcebuffer state here,
  2062. // as we are anyway detaching the MediaSource
  2063. // let's just avoid this exception to propagate
  2064. mediaSource.endOfStream();
  2065. } catch (err) {
  2066. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.warn("[buffer-controller]: onMediaDetaching: " + err.message + " while calling endOfStream");
  2067. }
  2068. }
  2069. // Clean up the SourceBuffers by invoking onBufferReset
  2070. this.onBufferReset();
  2071. mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);
  2072. mediaSource.removeEventListener('sourceended', this._onMediaSourceEnded);
  2073. mediaSource.removeEventListener('sourceclose', this._onMediaSourceClose);
  2074. // Detach properly the MediaSource from the HTMLMediaElement as
  2075. // suggested in https://github.com/w3c/media-source/issues/53.
  2076. if (media) {
  2077. if (_objectUrl) {
  2078. self.URL.revokeObjectURL(_objectUrl);
  2079. }
  2080. // clean up video tag src only if it's our own url. some external libraries might
  2081. // hijack the video tag and change its 'src' without destroying the Hls instance first
  2082. if (media.src === _objectUrl) {
  2083. media.removeAttribute('src');
  2084. media.load();
  2085. } else {
  2086. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.warn('[buffer-controller]: media.src was changed by a third party - skip cleanup');
  2087. }
  2088. }
  2089. this.mediaSource = null;
  2090. this.media = null;
  2091. this._objectUrl = null;
  2092. this.bufferCodecEventsExpected = this._bufferCodecEventsTotal;
  2093. this.pendingTracks = {};
  2094. this.tracks = {};
  2095. }
  2096. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.MEDIA_DETACHED, undefined);
  2097. };
  2098. _proto.onBufferReset = function onBufferReset() {
  2099. var _this2 = this;
  2100. this.getSourceBufferTypes().forEach(function (type) {
  2101. var sb = _this2.sourceBuffer[type];
  2102. try {
  2103. if (sb) {
  2104. _this2.removeBufferListeners(type);
  2105. if (_this2.mediaSource) {
  2106. _this2.mediaSource.removeSourceBuffer(sb);
  2107. }
  2108. // Synchronously remove the SB from the map before the next call in order to prevent an async function from
  2109. // accessing it
  2110. _this2.sourceBuffer[type] = undefined;
  2111. }
  2112. } catch (err) {
  2113. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.warn("[buffer-controller]: Failed to reset the " + type + " buffer", err);
  2114. }
  2115. });
  2116. this._initSourceBuffer();
  2117. };
  2118. _proto.onBufferCodecs = function onBufferCodecs(event, data) {
  2119. var _this3 = this;
  2120. var sourceBufferCount = this.getSourceBufferTypes().length;
  2121. Object.keys(data).forEach(function (trackName) {
  2122. if (sourceBufferCount) {
  2123. // check if SourceBuffer codec needs to change
  2124. var track = _this3.tracks[trackName];
  2125. if (track && typeof track.buffer.changeType === 'function') {
  2126. var _data$trackName = data[trackName],
  2127. id = _data$trackName.id,
  2128. codec = _data$trackName.codec,
  2129. levelCodec = _data$trackName.levelCodec,
  2130. container = _data$trackName.container,
  2131. metadata = _data$trackName.metadata;
  2132. var currentCodec = (track.levelCodec || track.codec).replace(VIDEO_CODEC_PROFILE_REPACE, '$1');
  2133. var nextCodec = (levelCodec || codec).replace(VIDEO_CODEC_PROFILE_REPACE, '$1');
  2134. if (currentCodec !== nextCodec) {
  2135. var mimeType = container + ";codecs=" + (levelCodec || codec);
  2136. _this3.appendChangeType(trackName, mimeType);
  2137. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.log("[buffer-controller]: switching codec " + currentCodec + " to " + nextCodec);
  2138. _this3.tracks[trackName] = {
  2139. buffer: track.buffer,
  2140. codec: codec,
  2141. container: container,
  2142. levelCodec: levelCodec,
  2143. metadata: metadata,
  2144. id: id
  2145. };
  2146. }
  2147. }
  2148. } else {
  2149. // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks
  2150. _this3.pendingTracks[trackName] = data[trackName];
  2151. }
  2152. });
  2153. // if sourcebuffers already created, do nothing ...
  2154. if (sourceBufferCount) {
  2155. return;
  2156. }
  2157. this.bufferCodecEventsExpected = Math.max(this.bufferCodecEventsExpected - 1, 0);
  2158. if (this.mediaSource && this.mediaSource.readyState === 'open') {
  2159. this.checkPendingTracks();
  2160. }
  2161. };
  2162. _proto.appendChangeType = function appendChangeType(type, mimeType) {
  2163. var _this4 = this;
  2164. var operationQueue = this.operationQueue;
  2165. var operation = {
  2166. execute: function execute() {
  2167. var sb = _this4.sourceBuffer[type];
  2168. if (sb) {
  2169. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.log("[buffer-controller]: changing " + type + " sourceBuffer type to " + mimeType);
  2170. sb.changeType(mimeType);
  2171. }
  2172. operationQueue.shiftAndExecuteNext(type);
  2173. },
  2174. onStart: function onStart() {},
  2175. onComplete: function onComplete() {},
  2176. onError: function onError(e) {
  2177. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.warn("[buffer-controller]: Failed to change " + type + " SourceBuffer type", e);
  2178. }
  2179. };
  2180. operationQueue.append(operation, type);
  2181. };
  2182. _proto.onBufferAppending = function onBufferAppending(event, eventData) {
  2183. var _this5 = this;
  2184. var hls = this.hls,
  2185. operationQueue = this.operationQueue,
  2186. tracks = this.tracks;
  2187. var data = eventData.data,
  2188. type = eventData.type,
  2189. frag = eventData.frag,
  2190. part = eventData.part,
  2191. chunkMeta = eventData.chunkMeta;
  2192. var chunkStats = chunkMeta.buffering[type];
  2193. var bufferAppendingStart = self.performance.now();
  2194. chunkStats.start = bufferAppendingStart;
  2195. var fragBuffering = frag.stats.buffering;
  2196. var partBuffering = part ? part.stats.buffering : null;
  2197. if (fragBuffering.start === 0) {
  2198. fragBuffering.start = bufferAppendingStart;
  2199. }
  2200. if (partBuffering && partBuffering.start === 0) {
  2201. partBuffering.start = bufferAppendingStart;
  2202. }
  2203. // TODO: Only update timestampOffset when audio/mpeg fragment or part is not contiguous with previously appended
  2204. // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)
  2205. // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`
  2206. // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos).
  2207. // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486
  2208. var audioTrack = tracks.audio;
  2209. var checkTimestampOffset = type === 'audio' && chunkMeta.id === 1 && (audioTrack === null || audioTrack === void 0 ? void 0 : audioTrack.container) === 'audio/mpeg';
  2210. var operation = {
  2211. execute: function execute() {
  2212. chunkStats.executeStart = self.performance.now();
  2213. if (checkTimestampOffset) {
  2214. var sb = _this5.sourceBuffer[type];
  2215. if (sb) {
  2216. var delta = frag.start - sb.timestampOffset;
  2217. if (Math.abs(delta) >= 0.1) {
  2218. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.log("[buffer-controller]: Updating audio SourceBuffer timestampOffset to " + frag.start + " (delta: " + delta + ") sn: " + frag.sn + ")");
  2219. sb.timestampOffset = frag.start;
  2220. }
  2221. }
  2222. }
  2223. _this5.appendExecutor(data, type);
  2224. },
  2225. onStart: function onStart() {
  2226. // logger.debug(`[buffer-controller]: ${type} SourceBuffer updatestart`);
  2227. },
  2228. onComplete: function onComplete() {
  2229. // logger.debug(`[buffer-controller]: ${type} SourceBuffer updateend`);
  2230. var end = self.performance.now();
  2231. chunkStats.executeEnd = chunkStats.end = end;
  2232. if (fragBuffering.first === 0) {
  2233. fragBuffering.first = end;
  2234. }
  2235. if (partBuffering && partBuffering.first === 0) {
  2236. partBuffering.first = end;
  2237. }
  2238. var sourceBuffer = _this5.sourceBuffer;
  2239. var timeRanges = {};
  2240. for (var _type in sourceBuffer) {
  2241. timeRanges[_type] = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__.BufferHelper.getBuffered(sourceBuffer[_type]);
  2242. }
  2243. _this5.appendError = 0;
  2244. _this5.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.BUFFER_APPENDED, {
  2245. type: type,
  2246. frag: frag,
  2247. part: part,
  2248. chunkMeta: chunkMeta,
  2249. parent: frag.type,
  2250. timeRanges: timeRanges
  2251. });
  2252. },
  2253. onError: function onError(err) {
  2254. // in case any error occured while appending, put back segment in segments table
  2255. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.error("[buffer-controller]: Error encountered while trying to append to the " + type + " SourceBuffer", err);
  2256. var event = {
  2257. type: _errors__WEBPACK_IMPORTED_MODULE_3__.ErrorTypes.MEDIA_ERROR,
  2258. parent: frag.type,
  2259. details: _errors__WEBPACK_IMPORTED_MODULE_3__.ErrorDetails.BUFFER_APPEND_ERROR,
  2260. err: err,
  2261. fatal: false
  2262. };
  2263. if (err.code === DOMException.QUOTA_EXCEEDED_ERR) {
  2264. // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
  2265. // let's stop appending any segments, and report BUFFER_FULL_ERROR error
  2266. event.details = _errors__WEBPACK_IMPORTED_MODULE_3__.ErrorDetails.BUFFER_FULL_ERROR;
  2267. } else {
  2268. _this5.appendError++;
  2269. event.details = _errors__WEBPACK_IMPORTED_MODULE_3__.ErrorDetails.BUFFER_APPEND_ERROR;
  2270. /* with UHD content, we could get loop of quota exceeded error until
  2271. browser is able to evict some data from sourcebuffer. Retrying can help recover.
  2272. */
  2273. if (_this5.appendError > hls.config.appendErrorMaxRetry) {
  2274. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.error("[buffer-controller]: Failed " + hls.config.appendErrorMaxRetry + " times to append segment in sourceBuffer");
  2275. event.fatal = true;
  2276. hls.stopLoad();
  2277. }
  2278. }
  2279. hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.ERROR, event);
  2280. }
  2281. };
  2282. operationQueue.append(operation, type);
  2283. };
  2284. _proto.onBufferFlushing = function onBufferFlushing(event, data) {
  2285. var _this6 = this;
  2286. var operationQueue = this.operationQueue;
  2287. var flushOperation = function flushOperation(type) {
  2288. return {
  2289. execute: _this6.removeExecutor.bind(_this6, type, data.startOffset, data.endOffset),
  2290. onStart: function onStart() {
  2291. // logger.debug(`[buffer-controller]: Started flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
  2292. },
  2293. onComplete: function onComplete() {
  2294. // logger.debug(`[buffer-controller]: Finished flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
  2295. _this6.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.BUFFER_FLUSHED, {
  2296. type: type
  2297. });
  2298. },
  2299. onError: function onError(e) {
  2300. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.warn("[buffer-controller]: Failed to remove from " + type + " SourceBuffer", e);
  2301. }
  2302. };
  2303. };
  2304. if (data.type) {
  2305. operationQueue.append(flushOperation(data.type), data.type);
  2306. } else {
  2307. this.getSourceBufferTypes().forEach(function (type) {
  2308. operationQueue.append(flushOperation(type), type);
  2309. });
  2310. }
  2311. };
  2312. _proto.onFragParsed = function onFragParsed(event, data) {
  2313. var _this7 = this;
  2314. var frag = data.frag,
  2315. part = data.part;
  2316. var buffersAppendedTo = [];
  2317. var elementaryStreams = part ? part.elementaryStreams : frag.elementaryStreams;
  2318. if (elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_6__.ElementaryStreamTypes.AUDIOVIDEO]) {
  2319. buffersAppendedTo.push('audiovideo');
  2320. } else {
  2321. if (elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_6__.ElementaryStreamTypes.AUDIO]) {
  2322. buffersAppendedTo.push('audio');
  2323. }
  2324. if (elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_6__.ElementaryStreamTypes.VIDEO]) {
  2325. buffersAppendedTo.push('video');
  2326. }
  2327. }
  2328. var onUnblocked = function onUnblocked() {
  2329. var now = self.performance.now();
  2330. frag.stats.buffering.end = now;
  2331. if (part) {
  2332. part.stats.buffering.end = now;
  2333. }
  2334. var stats = part ? part.stats : frag.stats;
  2335. _this7.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.FRAG_BUFFERED, {
  2336. frag: frag,
  2337. part: part,
  2338. stats: stats,
  2339. id: frag.type
  2340. });
  2341. };
  2342. if (buffersAppendedTo.length === 0) {
  2343. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.warn("Fragments must have at least one ElementaryStreamType set. type: " + frag.type + " level: " + frag.level + " sn: " + frag.sn);
  2344. }
  2345. this.blockBuffers(onUnblocked, buffersAppendedTo);
  2346. };
  2347. _proto.onFragChanged = function onFragChanged(event, data) {
  2348. this.flushBackBuffer();
  2349. }
  2350. // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()
  2351. // an undefined data.type will mark all buffers as EOS.
  2352. ;
  2353. _proto.onBufferEos = function onBufferEos(event, data) {
  2354. var _this8 = this;
  2355. var ended = this.getSourceBufferTypes().reduce(function (acc, type) {
  2356. var sb = _this8.sourceBuffer[type];
  2357. if (!data.type || data.type === type) {
  2358. if (sb && !sb.ended) {
  2359. sb.ended = true;
  2360. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.log("[buffer-controller]: " + type + " sourceBuffer now EOS");
  2361. }
  2362. }
  2363. return acc && !!(!sb || sb.ended);
  2364. }, true);
  2365. if (ended) {
  2366. this.blockBuffers(function () {
  2367. var mediaSource = _this8.mediaSource;
  2368. if (!mediaSource || mediaSource.readyState !== 'open') {
  2369. return;
  2370. }
  2371. // Allow this to throw and be caught by the enqueueing function
  2372. mediaSource.endOfStream();
  2373. });
  2374. }
  2375. };
  2376. _proto.onLevelUpdated = function onLevelUpdated(event, _ref) {
  2377. var details = _ref.details;
  2378. if (!details.fragments.length) {
  2379. return;
  2380. }
  2381. this.details = details;
  2382. if (this.getSourceBufferTypes().length) {
  2383. this.blockBuffers(this.updateMediaElementDuration.bind(this));
  2384. } else {
  2385. this.updateMediaElementDuration();
  2386. }
  2387. };
  2388. _proto.flushBackBuffer = function flushBackBuffer() {
  2389. var hls = this.hls,
  2390. details = this.details,
  2391. media = this.media,
  2392. sourceBuffer = this.sourceBuffer;
  2393. if (!media || details === null) {
  2394. return;
  2395. }
  2396. var sourceBufferTypes = this.getSourceBufferTypes();
  2397. if (!sourceBufferTypes.length) {
  2398. return;
  2399. }
  2400. // Support for deprecated liveBackBufferLength
  2401. var backBufferLength = details.live && hls.config.liveBackBufferLength !== null ? hls.config.liveBackBufferLength : hls.config.backBufferLength;
  2402. if (!(0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(backBufferLength) || backBufferLength < 0) {
  2403. return;
  2404. }
  2405. var currentTime = media.currentTime;
  2406. var targetDuration = details.levelTargetDuration;
  2407. var maxBackBufferLength = Math.max(backBufferLength, targetDuration);
  2408. var targetBackBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration - maxBackBufferLength;
  2409. sourceBufferTypes.forEach(function (type) {
  2410. var sb = sourceBuffer[type];
  2411. if (sb) {
  2412. var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__.BufferHelper.getBuffered(sb);
  2413. // when target buffer start exceeds actual buffer start
  2414. if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
  2415. hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.BACK_BUFFER_REACHED, {
  2416. bufferEnd: targetBackBufferPosition
  2417. });
  2418. // Support for deprecated event:
  2419. if (details.live) {
  2420. hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.LIVE_BACK_BUFFER_REACHED, {
  2421. bufferEnd: targetBackBufferPosition
  2422. });
  2423. }
  2424. hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.BUFFER_FLUSHING, {
  2425. startOffset: 0,
  2426. endOffset: targetBackBufferPosition,
  2427. type: type
  2428. });
  2429. }
  2430. }
  2431. });
  2432. }
  2433. /**
  2434. * Update Media Source duration to current level duration or override to Infinity if configuration parameter
  2435. * 'liveDurationInfinity` is set to `true`
  2436. * More details: https://github.com/video-dev/hls.js/issues/355
  2437. */;
  2438. _proto.updateMediaElementDuration = function updateMediaElementDuration() {
  2439. if (!this.details || !this.media || !this.mediaSource || this.mediaSource.readyState !== 'open') {
  2440. return;
  2441. }
  2442. var details = this.details,
  2443. hls = this.hls,
  2444. media = this.media,
  2445. mediaSource = this.mediaSource;
  2446. var levelDuration = details.fragments[0].start + details.totalduration;
  2447. var mediaDuration = media.duration;
  2448. var msDuration = (0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(mediaSource.duration) ? mediaSource.duration : 0;
  2449. if (details.live && hls.config.liveDurationInfinity) {
  2450. // Override duration to Infinity
  2451. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.log('[buffer-controller]: Media Source duration is set to Infinity');
  2452. mediaSource.duration = Infinity;
  2453. this.updateSeekableRange(details);
  2454. } else if (levelDuration > msDuration && levelDuration > mediaDuration || !(0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(mediaDuration)) {
  2455. // levelDuration was the last value we set.
  2456. // not using mediaSource.duration as the browser may tweak this value
  2457. // only update Media Source duration if its value increase, this is to avoid
  2458. // flushing already buffered portion when switching between quality level
  2459. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.log("[buffer-controller]: Updating Media Source duration to " + levelDuration.toFixed(3));
  2460. mediaSource.duration = levelDuration;
  2461. }
  2462. };
  2463. _proto.updateSeekableRange = function updateSeekableRange(levelDetails) {
  2464. var mediaSource = this.mediaSource;
  2465. var fragments = levelDetails.fragments;
  2466. var len = fragments.length;
  2467. if (len && levelDetails.live && mediaSource !== null && mediaSource !== void 0 && mediaSource.setLiveSeekableRange) {
  2468. var start = Math.max(0, fragments[0].start);
  2469. var end = Math.max(start, start + levelDetails.totalduration);
  2470. mediaSource.setLiveSeekableRange(start, end);
  2471. }
  2472. };
  2473. _proto.checkPendingTracks = function checkPendingTracks() {
  2474. var bufferCodecEventsExpected = this.bufferCodecEventsExpected,
  2475. operationQueue = this.operationQueue,
  2476. pendingTracks = this.pendingTracks;
  2477. // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.
  2478. // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after
  2479. // data has been appended to existing ones.
  2480. // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.
  2481. var pendingTracksCount = Object.keys(pendingTracks).length;
  2482. if (pendingTracksCount && !bufferCodecEventsExpected || pendingTracksCount === 2) {
  2483. // ok, let's create them now !
  2484. this.createSourceBuffers(pendingTracks);
  2485. this.pendingTracks = {};
  2486. // append any pending segments now !
  2487. var buffers = this.getSourceBufferTypes();
  2488. if (buffers.length === 0) {
  2489. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.ERROR, {
  2490. type: _errors__WEBPACK_IMPORTED_MODULE_3__.ErrorTypes.MEDIA_ERROR,
  2491. details: _errors__WEBPACK_IMPORTED_MODULE_3__.ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,
  2492. fatal: true,
  2493. reason: 'could not create source buffer for media codec(s)'
  2494. });
  2495. return;
  2496. }
  2497. buffers.forEach(function (type) {
  2498. operationQueue.executeNext(type);
  2499. });
  2500. }
  2501. };
  2502. _proto.createSourceBuffers = function createSourceBuffers(tracks) {
  2503. var sourceBuffer = this.sourceBuffer,
  2504. mediaSource = this.mediaSource;
  2505. if (!mediaSource) {
  2506. throw Error('createSourceBuffers called when mediaSource was null');
  2507. }
  2508. var tracksCreated = 0;
  2509. for (var trackName in tracks) {
  2510. if (!sourceBuffer[trackName]) {
  2511. var track = tracks[trackName];
  2512. if (!track) {
  2513. throw Error("source buffer exists for track " + trackName + ", however track does not");
  2514. }
  2515. // use levelCodec as first priority
  2516. var codec = track.levelCodec || track.codec;
  2517. var mimeType = track.container + ";codecs=" + codec;
  2518. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.log("[buffer-controller]: creating sourceBuffer(" + mimeType + ")");
  2519. try {
  2520. var sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);
  2521. var sbName = trackName;
  2522. this.addBufferListener(sbName, 'updatestart', this._onSBUpdateStart);
  2523. this.addBufferListener(sbName, 'updateend', this._onSBUpdateEnd);
  2524. this.addBufferListener(sbName, 'error', this._onSBUpdateError);
  2525. this.tracks[trackName] = {
  2526. buffer: sb,
  2527. codec: codec,
  2528. container: track.container,
  2529. levelCodec: track.levelCodec,
  2530. metadata: track.metadata,
  2531. id: track.id
  2532. };
  2533. tracksCreated++;
  2534. } catch (err) {
  2535. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.error("[buffer-controller]: error while trying to add sourceBuffer: " + err.message);
  2536. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.ERROR, {
  2537. type: _errors__WEBPACK_IMPORTED_MODULE_3__.ErrorTypes.MEDIA_ERROR,
  2538. details: _errors__WEBPACK_IMPORTED_MODULE_3__.ErrorDetails.BUFFER_ADD_CODEC_ERROR,
  2539. fatal: false,
  2540. error: err,
  2541. mimeType: mimeType
  2542. });
  2543. }
  2544. }
  2545. }
  2546. if (tracksCreated) {
  2547. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.BUFFER_CREATED, {
  2548. tracks: this.tracks
  2549. });
  2550. }
  2551. }
  2552. // Keep as arrow functions so that we can directly reference these functions directly as event listeners
  2553. ;
  2554. _proto._onSBUpdateStart = function _onSBUpdateStart(type) {
  2555. var operationQueue = this.operationQueue;
  2556. var operation = operationQueue.current(type);
  2557. operation.onStart();
  2558. };
  2559. _proto._onSBUpdateEnd = function _onSBUpdateEnd(type) {
  2560. var operationQueue = this.operationQueue;
  2561. var operation = operationQueue.current(type);
  2562. operation.onComplete();
  2563. operationQueue.shiftAndExecuteNext(type);
  2564. };
  2565. _proto._onSBUpdateError = function _onSBUpdateError(type, event) {
  2566. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.error("[buffer-controller]: " + type + " SourceBuffer error", event);
  2567. // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
  2568. // SourceBuffer errors are not necessarily fatal; if so, the HTMLMediaElement will fire an error event
  2569. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.ERROR, {
  2570. type: _errors__WEBPACK_IMPORTED_MODULE_3__.ErrorTypes.MEDIA_ERROR,
  2571. details: _errors__WEBPACK_IMPORTED_MODULE_3__.ErrorDetails.BUFFER_APPENDING_ERROR,
  2572. fatal: false
  2573. });
  2574. // updateend is always fired after error, so we'll allow that to shift the current operation off of the queue
  2575. var operation = this.operationQueue.current(type);
  2576. if (operation) {
  2577. operation.onError(event);
  2578. }
  2579. }
  2580. // This method must result in an updateend event; if remove is not called, _onSBUpdateEnd must be called manually
  2581. ;
  2582. _proto.removeExecutor = function removeExecutor(type, startOffset, endOffset) {
  2583. var media = this.media,
  2584. mediaSource = this.mediaSource,
  2585. operationQueue = this.operationQueue,
  2586. sourceBuffer = this.sourceBuffer;
  2587. var sb = sourceBuffer[type];
  2588. if (!media || !mediaSource || !sb) {
  2589. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.warn("[buffer-controller]: Attempting to remove from the " + type + " SourceBuffer, but it does not exist");
  2590. operationQueue.shiftAndExecuteNext(type);
  2591. return;
  2592. }
  2593. var mediaDuration = (0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(media.duration) ? media.duration : Infinity;
  2594. var msDuration = (0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(mediaSource.duration) ? mediaSource.duration : Infinity;
  2595. var removeStart = Math.max(0, startOffset);
  2596. var removeEnd = Math.min(endOffset, mediaDuration, msDuration);
  2597. if (removeEnd > removeStart) {
  2598. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.log("[buffer-controller]: Removing [" + removeStart + "," + removeEnd + "] from the " + type + " SourceBuffer");
  2599. console.assert(!sb.updating, type + " sourceBuffer must not be updating");
  2600. sb.remove(removeStart, removeEnd);
  2601. } else {
  2602. // Cycle the queue
  2603. operationQueue.shiftAndExecuteNext(type);
  2604. }
  2605. }
  2606. // This method must result in an updateend event; if append is not called, _onSBUpdateEnd must be called manually
  2607. ;
  2608. _proto.appendExecutor = function appendExecutor(data, type) {
  2609. var operationQueue = this.operationQueue,
  2610. sourceBuffer = this.sourceBuffer;
  2611. var sb = sourceBuffer[type];
  2612. if (!sb) {
  2613. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.warn("[buffer-controller]: Attempting to append to the " + type + " SourceBuffer, but it does not exist");
  2614. operationQueue.shiftAndExecuteNext(type);
  2615. return;
  2616. }
  2617. sb.ended = false;
  2618. console.assert(!sb.updating, type + " sourceBuffer must not be updating");
  2619. sb.appendBuffer(data);
  2620. }
  2621. // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises
  2622. // resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue
  2623. // upon completion, since we already do it here
  2624. ;
  2625. _proto.blockBuffers = function blockBuffers(onUnblocked, buffers) {
  2626. var _this9 = this;
  2627. if (buffers === void 0) {
  2628. buffers = this.getSourceBufferTypes();
  2629. }
  2630. if (!buffers.length) {
  2631. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.log('[buffer-controller]: Blocking operation requested, but no SourceBuffers exist');
  2632. Promise.resolve().then(onUnblocked);
  2633. return;
  2634. }
  2635. var operationQueue = this.operationQueue;
  2636. // logger.debug(`[buffer-controller]: Blocking ${buffers} SourceBuffer`);
  2637. var blockingOperations = buffers.map(function (type) {
  2638. return operationQueue.appendBlocker(type);
  2639. });
  2640. Promise.all(blockingOperations).then(function () {
  2641. // logger.debug(`[buffer-controller]: Blocking operation resolved; unblocking ${buffers} SourceBuffer`);
  2642. onUnblocked();
  2643. buffers.forEach(function (type) {
  2644. var sb = _this9.sourceBuffer[type];
  2645. // Only cycle the queue if the SB is not updating. There's a bug in Chrome which sets the SB updating flag to
  2646. // true when changing the MediaSource duration (https://bugs.chromium.org/p/chromium/issues/detail?id=959359&can=2&q=mediasource%20duration)
  2647. // While this is a workaround, it's probably useful to have around
  2648. if (!sb || !sb.updating) {
  2649. operationQueue.shiftAndExecuteNext(type);
  2650. }
  2651. });
  2652. });
  2653. };
  2654. _proto.getSourceBufferTypes = function getSourceBufferTypes() {
  2655. return Object.keys(this.sourceBuffer);
  2656. };
  2657. _proto.addBufferListener = function addBufferListener(type, event, fn) {
  2658. var buffer = this.sourceBuffer[type];
  2659. if (!buffer) {
  2660. return;
  2661. }
  2662. var listener = fn.bind(this, type);
  2663. this.listeners[type].push({
  2664. event: event,
  2665. listener: listener
  2666. });
  2667. buffer.addEventListener(event, listener);
  2668. };
  2669. _proto.removeBufferListeners = function removeBufferListeners(type) {
  2670. var buffer = this.sourceBuffer[type];
  2671. if (!buffer) {
  2672. return;
  2673. }
  2674. this.listeners[type].forEach(function (l) {
  2675. buffer.removeEventListener(l.event, l.listener);
  2676. });
  2677. };
  2678. return BufferController;
  2679. }();
  2680. /***/ }),
  2681. /***/ "./src/controller/buffer-operation-queue.ts":
  2682. /*!**************************************************!*\
  2683. !*** ./src/controller/buffer-operation-queue.ts ***!
  2684. \**************************************************/
  2685. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  2686. "use strict";
  2687. __webpack_require__.r(__webpack_exports__);
  2688. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  2689. /* harmony export */ "default": () => (/* binding */ BufferOperationQueue)
  2690. /* harmony export */ });
  2691. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
  2692. var BufferOperationQueue = /*#__PURE__*/function () {
  2693. function BufferOperationQueue(sourceBufferReference) {
  2694. this.buffers = void 0;
  2695. this.queues = {
  2696. video: [],
  2697. audio: [],
  2698. audiovideo: []
  2699. };
  2700. this.buffers = sourceBufferReference;
  2701. }
  2702. var _proto = BufferOperationQueue.prototype;
  2703. _proto.append = function append(operation, type) {
  2704. var queue = this.queues[type];
  2705. queue.push(operation);
  2706. if (queue.length === 1 && this.buffers[type]) {
  2707. this.executeNext(type);
  2708. }
  2709. };
  2710. _proto.insertAbort = function insertAbort(operation, type) {
  2711. var queue = this.queues[type];
  2712. queue.unshift(operation);
  2713. this.executeNext(type);
  2714. };
  2715. _proto.appendBlocker = function appendBlocker(type) {
  2716. var execute;
  2717. var promise = new Promise(function (resolve) {
  2718. execute = resolve;
  2719. });
  2720. var operation = {
  2721. execute: execute,
  2722. onStart: function onStart() {},
  2723. onComplete: function onComplete() {},
  2724. onError: function onError() {}
  2725. };
  2726. this.append(operation, type);
  2727. return promise;
  2728. };
  2729. _proto.executeNext = function executeNext(type) {
  2730. var buffers = this.buffers,
  2731. queues = this.queues;
  2732. var sb = buffers[type];
  2733. var queue = queues[type];
  2734. if (queue.length) {
  2735. var operation = queue[0];
  2736. try {
  2737. // Operations are expected to result in an 'updateend' event being fired. If not, the queue will lock. Operations
  2738. // which do not end with this event must call _onSBUpdateEnd manually
  2739. operation.execute();
  2740. } catch (e) {
  2741. _utils_logger__WEBPACK_IMPORTED_MODULE_0__.logger.warn('[buffer-operation-queue]: Unhandled exception executing the current operation');
  2742. operation.onError(e);
  2743. // Only shift the current operation off, otherwise the updateend handler will do this for us
  2744. if (!sb || !sb.updating) {
  2745. queue.shift();
  2746. this.executeNext(type);
  2747. }
  2748. }
  2749. }
  2750. };
  2751. _proto.shiftAndExecuteNext = function shiftAndExecuteNext(type) {
  2752. this.queues[type].shift();
  2753. this.executeNext(type);
  2754. };
  2755. _proto.current = function current(type) {
  2756. return this.queues[type][0];
  2757. };
  2758. return BufferOperationQueue;
  2759. }();
  2760. /***/ }),
  2761. /***/ "./src/controller/cap-level-controller.ts":
  2762. /*!************************************************!*\
  2763. !*** ./src/controller/cap-level-controller.ts ***!
  2764. \************************************************/
  2765. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  2766. "use strict";
  2767. __webpack_require__.r(__webpack_exports__);
  2768. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  2769. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  2770. /* harmony export */ });
  2771. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
  2772. 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, _toPropertyKey(descriptor.key), descriptor); } }
  2773. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  2774. function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
  2775. function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
  2776. /*
  2777. * cap stream level to media size dimension controller
  2778. */
  2779. var CapLevelController = /*#__PURE__*/function () {
  2780. function CapLevelController(hls) {
  2781. this.autoLevelCapping = void 0;
  2782. this.firstLevel = void 0;
  2783. this.media = void 0;
  2784. this.restrictedLevels = void 0;
  2785. this.timer = void 0;
  2786. this.hls = void 0;
  2787. this.streamController = void 0;
  2788. this.clientRect = void 0;
  2789. this.hls = hls;
  2790. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  2791. this.firstLevel = -1;
  2792. this.media = null;
  2793. this.restrictedLevels = [];
  2794. this.timer = undefined;
  2795. this.clientRect = null;
  2796. this.registerListeners();
  2797. }
  2798. var _proto = CapLevelController.prototype;
  2799. _proto.setStreamController = function setStreamController(streamController) {
  2800. this.streamController = streamController;
  2801. };
  2802. _proto.destroy = function destroy() {
  2803. this.unregisterListener();
  2804. if (this.hls.config.capLevelToPlayerSize) {
  2805. this.stopCapping();
  2806. }
  2807. this.media = null;
  2808. this.clientRect = null;
  2809. // @ts-ignore
  2810. this.hls = this.streamController = null;
  2811. };
  2812. _proto.registerListeners = function registerListeners() {
  2813. var hls = this.hls;
  2814. hls.on(_events__WEBPACK_IMPORTED_MODULE_0__.Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  2815. hls.on(_events__WEBPACK_IMPORTED_MODULE_0__.Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  2816. hls.on(_events__WEBPACK_IMPORTED_MODULE_0__.Events.MANIFEST_PARSED, this.onManifestParsed, this);
  2817. hls.on(_events__WEBPACK_IMPORTED_MODULE_0__.Events.BUFFER_CODECS, this.onBufferCodecs, this);
  2818. hls.on(_events__WEBPACK_IMPORTED_MODULE_0__.Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  2819. };
  2820. _proto.unregisterListener = function unregisterListener() {
  2821. var hls = this.hls;
  2822. hls.off(_events__WEBPACK_IMPORTED_MODULE_0__.Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  2823. hls.off(_events__WEBPACK_IMPORTED_MODULE_0__.Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  2824. hls.off(_events__WEBPACK_IMPORTED_MODULE_0__.Events.MANIFEST_PARSED, this.onManifestParsed, this);
  2825. hls.off(_events__WEBPACK_IMPORTED_MODULE_0__.Events.BUFFER_CODECS, this.onBufferCodecs, this);
  2826. hls.off(_events__WEBPACK_IMPORTED_MODULE_0__.Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  2827. };
  2828. _proto.onFpsDropLevelCapping = function onFpsDropLevelCapping(event, data) {
  2829. // Don't add a restricted level more than once
  2830. if (CapLevelController.isLevelAllowed(data.droppedLevel, this.restrictedLevels)) {
  2831. this.restrictedLevels.push(data.droppedLevel);
  2832. }
  2833. };
  2834. _proto.onMediaAttaching = function onMediaAttaching(event, data) {
  2835. this.media = data.media instanceof HTMLVideoElement ? data.media : null;
  2836. this.clientRect = null;
  2837. };
  2838. _proto.onManifestParsed = function onManifestParsed(event, data) {
  2839. var hls = this.hls;
  2840. this.restrictedLevels = [];
  2841. this.firstLevel = data.firstLevel;
  2842. if (hls.config.capLevelToPlayerSize && data.video) {
  2843. // Start capping immediately if the manifest has signaled video codecs
  2844. this.startCapping();
  2845. }
  2846. }
  2847. // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted
  2848. // to the first level
  2849. ;
  2850. _proto.onBufferCodecs = function onBufferCodecs(event, data) {
  2851. var hls = this.hls;
  2852. if (hls.config.capLevelToPlayerSize && data.video) {
  2853. // If the manifest did not signal a video codec capping has been deferred until we're certain video is present
  2854. this.startCapping();
  2855. }
  2856. };
  2857. _proto.onMediaDetaching = function onMediaDetaching() {
  2858. this.stopCapping();
  2859. };
  2860. _proto.detectPlayerSize = function detectPlayerSize() {
  2861. if (this.media && this.mediaHeight > 0 && this.mediaWidth > 0) {
  2862. var levels = this.hls.levels;
  2863. if (levels.length) {
  2864. var hls = this.hls;
  2865. hls.autoLevelCapping = this.getMaxLevel(levels.length - 1);
  2866. if (hls.autoLevelCapping > this.autoLevelCapping && this.streamController) {
  2867. // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch
  2868. // usually happen when the user go to the fullscreen mode.
  2869. this.streamController.nextLevelSwitch();
  2870. }
  2871. this.autoLevelCapping = hls.autoLevelCapping;
  2872. }
  2873. }
  2874. }
  2875. /*
  2876. * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
  2877. */;
  2878. _proto.getMaxLevel = function getMaxLevel(capLevelIndex) {
  2879. var _this = this;
  2880. var levels = this.hls.levels;
  2881. if (!levels.length) {
  2882. return -1;
  2883. }
  2884. var validLevels = levels.filter(function (level, index) {
  2885. return CapLevelController.isLevelAllowed(index, _this.restrictedLevels) && index <= capLevelIndex;
  2886. });
  2887. this.clientRect = null;
  2888. return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
  2889. };
  2890. _proto.startCapping = function startCapping() {
  2891. if (this.timer) {
  2892. // Don't reset capping if started twice; this can happen if the manifest signals a video codec
  2893. return;
  2894. }
  2895. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  2896. this.hls.firstLevel = this.getMaxLevel(this.firstLevel);
  2897. self.clearInterval(this.timer);
  2898. this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1000);
  2899. this.detectPlayerSize();
  2900. };
  2901. _proto.stopCapping = function stopCapping() {
  2902. this.restrictedLevels = [];
  2903. this.firstLevel = -1;
  2904. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  2905. if (this.timer) {
  2906. self.clearInterval(this.timer);
  2907. this.timer = undefined;
  2908. }
  2909. };
  2910. _proto.getDimensions = function getDimensions() {
  2911. if (this.clientRect) {
  2912. return this.clientRect;
  2913. }
  2914. var media = this.media;
  2915. var boundsRect = {
  2916. width: 0,
  2917. height: 0
  2918. };
  2919. if (media) {
  2920. var clientRect = media.getBoundingClientRect();
  2921. boundsRect.width = clientRect.width;
  2922. boundsRect.height = clientRect.height;
  2923. if (!boundsRect.width && !boundsRect.height) {
  2924. // When the media element has no width or height (equivalent to not being in the DOM),
  2925. // then use its width and height attributes (media.width, media.height)
  2926. boundsRect.width = clientRect.right - clientRect.left || media.width || 0;
  2927. boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;
  2928. }
  2929. }
  2930. this.clientRect = boundsRect;
  2931. return boundsRect;
  2932. };
  2933. CapLevelController.isLevelAllowed = function isLevelAllowed(level, restrictedLevels) {
  2934. if (restrictedLevels === void 0) {
  2935. restrictedLevels = [];
  2936. }
  2937. return restrictedLevels.indexOf(level) === -1;
  2938. };
  2939. CapLevelController.getMaxLevelByMediaSize = function getMaxLevelByMediaSize(levels, width, height) {
  2940. if (!levels || !levels.length) {
  2941. return -1;
  2942. }
  2943. // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next
  2944. // to determine whether we've chosen the greatest bandwidth for the media's dimensions
  2945. var atGreatestBandwidth = function atGreatestBandwidth(curLevel, nextLevel) {
  2946. if (!nextLevel) {
  2947. return true;
  2948. }
  2949. return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
  2950. };
  2951. // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to
  2952. // the max level
  2953. var maxLevelIndex = levels.length - 1;
  2954. for (var i = 0; i < levels.length; i += 1) {
  2955. var level = levels[i];
  2956. if ((level.width >= width || level.height >= height) && atGreatestBandwidth(level, levels[i + 1])) {
  2957. maxLevelIndex = i;
  2958. break;
  2959. }
  2960. }
  2961. return maxLevelIndex;
  2962. };
  2963. _createClass(CapLevelController, [{
  2964. key: "mediaWidth",
  2965. get: function get() {
  2966. return this.getDimensions().width * this.contentScaleFactor;
  2967. }
  2968. }, {
  2969. key: "mediaHeight",
  2970. get: function get() {
  2971. return this.getDimensions().height * this.contentScaleFactor;
  2972. }
  2973. }, {
  2974. key: "contentScaleFactor",
  2975. get: function get() {
  2976. var pixelRatio = 1;
  2977. if (!this.hls.config.ignoreDevicePixelRatio) {
  2978. try {
  2979. pixelRatio = self.devicePixelRatio;
  2980. } catch (e) {
  2981. /* no-op */
  2982. }
  2983. }
  2984. return pixelRatio;
  2985. }
  2986. }]);
  2987. return CapLevelController;
  2988. }();
  2989. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (CapLevelController);
  2990. /***/ }),
  2991. /***/ "./src/controller/fps-controller.ts":
  2992. /*!******************************************!*\
  2993. !*** ./src/controller/fps-controller.ts ***!
  2994. \******************************************/
  2995. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  2996. "use strict";
  2997. __webpack_require__.r(__webpack_exports__);
  2998. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  2999. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  3000. /* harmony export */ });
  3001. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
  3002. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
  3003. var FPSController = /*#__PURE__*/function () {
  3004. // stream controller must be provided as a dependency!
  3005. function FPSController(hls) {
  3006. this.hls = void 0;
  3007. this.isVideoPlaybackQualityAvailable = false;
  3008. this.timer = void 0;
  3009. this.media = null;
  3010. this.lastTime = void 0;
  3011. this.lastDroppedFrames = 0;
  3012. this.lastDecodedFrames = 0;
  3013. this.streamController = void 0;
  3014. this.hls = hls;
  3015. this.registerListeners();
  3016. }
  3017. var _proto = FPSController.prototype;
  3018. _proto.setStreamController = function setStreamController(streamController) {
  3019. this.streamController = streamController;
  3020. };
  3021. _proto.registerListeners = function registerListeners() {
  3022. this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__.Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  3023. };
  3024. _proto.unregisterListeners = function unregisterListeners() {
  3025. this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__.Events.MEDIA_ATTACHING, this.onMediaAttaching);
  3026. };
  3027. _proto.destroy = function destroy() {
  3028. if (this.timer) {
  3029. clearInterval(this.timer);
  3030. }
  3031. this.unregisterListeners();
  3032. this.isVideoPlaybackQualityAvailable = false;
  3033. this.media = null;
  3034. };
  3035. _proto.onMediaAttaching = function onMediaAttaching(event, data) {
  3036. var config = this.hls.config;
  3037. if (config.capLevelOnFPSDrop) {
  3038. var media = data.media instanceof self.HTMLVideoElement ? data.media : null;
  3039. this.media = media;
  3040. if (media && typeof media.getVideoPlaybackQuality === 'function') {
  3041. this.isVideoPlaybackQualityAvailable = true;
  3042. }
  3043. self.clearInterval(this.timer);
  3044. this.timer = self.setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
  3045. }
  3046. };
  3047. _proto.checkFPS = function checkFPS(video, decodedFrames, droppedFrames) {
  3048. var currentTime = performance.now();
  3049. if (decodedFrames) {
  3050. if (this.lastTime) {
  3051. var currentPeriod = currentTime - this.lastTime;
  3052. var currentDropped = droppedFrames - this.lastDroppedFrames;
  3053. var currentDecoded = decodedFrames - this.lastDecodedFrames;
  3054. var droppedFPS = 1000 * currentDropped / currentPeriod;
  3055. var hls = this.hls;
  3056. hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__.Events.FPS_DROP, {
  3057. currentDropped: currentDropped,
  3058. currentDecoded: currentDecoded,
  3059. totalDroppedFrames: droppedFrames
  3060. });
  3061. if (droppedFPS > 0) {
  3062. // logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));
  3063. if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
  3064. var currentLevel = hls.currentLevel;
  3065. _utils_logger__WEBPACK_IMPORTED_MODULE_1__.logger.warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);
  3066. if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
  3067. currentLevel = currentLevel - 1;
  3068. hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__.Events.FPS_DROP_LEVEL_CAPPING, {
  3069. level: currentLevel,
  3070. droppedLevel: hls.currentLevel
  3071. });
  3072. hls.autoLevelCapping = currentLevel;
  3073. this.streamController.nextLevelSwitch();
  3074. }
  3075. }
  3076. }
  3077. }
  3078. this.lastTime = currentTime;
  3079. this.lastDroppedFrames = droppedFrames;
  3080. this.lastDecodedFrames = decodedFrames;
  3081. }
  3082. };
  3083. _proto.checkFPSInterval = function checkFPSInterval() {
  3084. var video = this.media;
  3085. if (video) {
  3086. if (this.isVideoPlaybackQualityAvailable) {
  3087. var videoPlaybackQuality = video.getVideoPlaybackQuality();
  3088. this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
  3089. } else {
  3090. // HTMLVideoElement doesn't include the webkit types
  3091. this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
  3092. }
  3093. }
  3094. };
  3095. return FPSController;
  3096. }();
  3097. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (FPSController);
  3098. /***/ }),
  3099. /***/ "./src/controller/fragment-finders.ts":
  3100. /*!********************************************!*\
  3101. !*** ./src/controller/fragment-finders.ts ***!
  3102. \********************************************/
  3103. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  3104. "use strict";
  3105. __webpack_require__.r(__webpack_exports__);
  3106. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  3107. /* harmony export */ "findFragWithCC": () => (/* binding */ findFragWithCC),
  3108. /* harmony export */ "findFragmentByPDT": () => (/* binding */ findFragmentByPDT),
  3109. /* harmony export */ "findFragmentByPTS": () => (/* binding */ findFragmentByPTS),
  3110. /* harmony export */ "fragmentWithinToleranceTest": () => (/* binding */ fragmentWithinToleranceTest),
  3111. /* harmony export */ "pdtWithinToleranceTest": () => (/* binding */ pdtWithinToleranceTest)
  3112. /* harmony export */ });
  3113. /* harmony import */ var _Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
  3114. /* harmony import */ var _utils_binary_search__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/binary-search */ "./src/utils/binary-search.ts");
  3115. /**
  3116. * Returns first fragment whose endPdt value exceeds the given PDT.
  3117. * @param {Array<Fragment>} fragments - The array of candidate fragments
  3118. * @param {number|null} [PDTValue = null] - The PDT value which must be exceeded
  3119. * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  3120. * @returns {*|null} fragment - The best matching fragment
  3121. */
  3122. function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
  3123. if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !(0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(PDTValue)) {
  3124. return null;
  3125. }
  3126. // if less than start
  3127. var startPDT = fragments[0].programDateTime;
  3128. if (PDTValue < (startPDT || 0)) {
  3129. return null;
  3130. }
  3131. var endPDT = fragments[fragments.length - 1].endProgramDateTime;
  3132. if (PDTValue >= (endPDT || 0)) {
  3133. return null;
  3134. }
  3135. maxFragLookUpTolerance = maxFragLookUpTolerance || 0;
  3136. for (var seg = 0; seg < fragments.length; ++seg) {
  3137. var frag = fragments[seg];
  3138. if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
  3139. return frag;
  3140. }
  3141. }
  3142. return null;
  3143. }
  3144. /**
  3145. * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.
  3146. * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus
  3147. * breaking any traps which would cause the same fragment to be continuously selected within a small range.
  3148. * @param {*} fragPrevious - The last frag successfully appended
  3149. * @param {Array} fragments - The array of candidate fragments
  3150. * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within
  3151. * @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  3152. * @returns {*} foundFrag - The best matching fragment
  3153. */
  3154. function findFragmentByPTS(fragPrevious, fragments, bufferEnd, maxFragLookUpTolerance) {
  3155. if (bufferEnd === void 0) {
  3156. bufferEnd = 0;
  3157. }
  3158. if (maxFragLookUpTolerance === void 0) {
  3159. maxFragLookUpTolerance = 0;
  3160. }
  3161. var fragNext = null;
  3162. if (fragPrevious) {
  3163. fragNext = fragments[fragPrevious.sn - fragments[0].sn + 1] || null;
  3164. } else if (bufferEnd === 0 && fragments[0].start === 0) {
  3165. fragNext = fragments[0];
  3166. }
  3167. // Prefer the next fragment if it's within tolerance
  3168. if (fragNext && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0) {
  3169. return fragNext;
  3170. }
  3171. // We might be seeking past the tolerance so find the best match
  3172. var foundFragment = _utils_binary_search__WEBPACK_IMPORTED_MODULE_1__["default"].search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
  3173. if (foundFragment && (foundFragment !== fragPrevious || !fragNext)) {
  3174. return foundFragment;
  3175. }
  3176. // If no match was found return the next fragment after fragPrevious, or null
  3177. return fragNext;
  3178. }
  3179. /**
  3180. * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.
  3181. * @param {*} candidate - The fragment to test
  3182. * @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within
  3183. * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous
  3184. * @returns {number} - 0 if it matches, 1 if too low, -1 if too high
  3185. */
  3186. function fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, candidate) {
  3187. if (bufferEnd === void 0) {
  3188. bufferEnd = 0;
  3189. }
  3190. if (maxFragLookUpTolerance === void 0) {
  3191. maxFragLookUpTolerance = 0;
  3192. }
  3193. // eagerly accept an accurate match (no tolerance)
  3194. if (candidate.start <= bufferEnd && candidate.start + candidate.duration > bufferEnd) {
  3195. return 0;
  3196. }
  3197. // offset should be within fragment boundary - config.maxFragLookUpTolerance
  3198. // this is to cope with situations like
  3199. // bufferEnd = 9.991
  3200. // frag[Ø] : [0,10]
  3201. // frag[1] : [10,20]
  3202. // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
  3203. // frag start frag start+duration
  3204. // |-----------------------------|
  3205. // <---> <--->
  3206. // ...--------><-----------------------------><---------....
  3207. // previous frag matching fragment next frag
  3208. // return -1 return 0 return 1
  3209. // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
  3210. // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
  3211. var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
  3212. if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
  3213. return 1;
  3214. } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
  3215. // if maxFragLookUpTolerance will have negative value then don't return -1 for first element
  3216. return -1;
  3217. }
  3218. return 0;
  3219. }
  3220. /**
  3221. * The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.
  3222. * This function tests the candidate's program date time values, as represented in Unix time
  3223. * @param {*} candidate - The fragment to test
  3224. * @param {number} [pdtBufferEnd = 0] - The Unix time representing the end of the current buffered range
  3225. * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous
  3226. * @returns {boolean} True if contiguous, false otherwise
  3227. */
  3228. function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
  3229. var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000;
  3230. // endProgramDateTime can be null, default to zero
  3231. var endProgramDateTime = candidate.endProgramDateTime || 0;
  3232. return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
  3233. }
  3234. function findFragWithCC(fragments, cc) {
  3235. return _utils_binary_search__WEBPACK_IMPORTED_MODULE_1__["default"].search(fragments, function (candidate) {
  3236. if (candidate.cc < cc) {
  3237. return 1;
  3238. } else if (candidate.cc > cc) {
  3239. return -1;
  3240. } else {
  3241. return 0;
  3242. }
  3243. });
  3244. }
  3245. /***/ }),
  3246. /***/ "./src/controller/fragment-tracker.ts":
  3247. /*!********************************************!*\
  3248. !*** ./src/controller/fragment-tracker.ts ***!
  3249. \********************************************/
  3250. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  3251. "use strict";
  3252. __webpack_require__.r(__webpack_exports__);
  3253. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  3254. /* harmony export */ "FragmentState": () => (/* binding */ FragmentState),
  3255. /* harmony export */ "FragmentTracker": () => (/* binding */ FragmentTracker)
  3256. /* harmony export */ });
  3257. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
  3258. /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
  3259. var FragmentState;
  3260. (function (FragmentState) {
  3261. FragmentState["NOT_LOADED"] = "NOT_LOADED";
  3262. FragmentState["APPENDING"] = "APPENDING";
  3263. FragmentState["PARTIAL"] = "PARTIAL";
  3264. FragmentState["OK"] = "OK";
  3265. })(FragmentState || (FragmentState = {}));
  3266. var FragmentTracker = /*#__PURE__*/function () {
  3267. function FragmentTracker(hls) {
  3268. this.activeFragment = null;
  3269. this.activeParts = null;
  3270. this.fragments = Object.create(null);
  3271. this.timeRanges = Object.create(null);
  3272. this.bufferPadding = 0.2;
  3273. this.hls = void 0;
  3274. this.hls = hls;
  3275. this._registerListeners();
  3276. }
  3277. var _proto = FragmentTracker.prototype;
  3278. _proto._registerListeners = function _registerListeners() {
  3279. var hls = this.hls;
  3280. hls.on(_events__WEBPACK_IMPORTED_MODULE_0__.Events.BUFFER_APPENDED, this.onBufferAppended, this);
  3281. hls.on(_events__WEBPACK_IMPORTED_MODULE_0__.Events.FRAG_BUFFERED, this.onFragBuffered, this);
  3282. hls.on(_events__WEBPACK_IMPORTED_MODULE_0__.Events.FRAG_LOADED, this.onFragLoaded, this);
  3283. };
  3284. _proto._unregisterListeners = function _unregisterListeners() {
  3285. var hls = this.hls;
  3286. hls.off(_events__WEBPACK_IMPORTED_MODULE_0__.Events.BUFFER_APPENDED, this.onBufferAppended, this);
  3287. hls.off(_events__WEBPACK_IMPORTED_MODULE_0__.Events.FRAG_BUFFERED, this.onFragBuffered, this);
  3288. hls.off(_events__WEBPACK_IMPORTED_MODULE_0__.Events.FRAG_LOADED, this.onFragLoaded, this);
  3289. };
  3290. _proto.destroy = function destroy() {
  3291. this._unregisterListeners();
  3292. // @ts-ignore
  3293. this.fragments = this.timeRanges = null;
  3294. }
  3295. /**
  3296. * Return a Fragment with an appended range that matches the position and levelType.
  3297. * If not found any Fragment, return null
  3298. */;
  3299. _proto.getAppendedFrag = function getAppendedFrag(position, levelType) {
  3300. if (levelType === _types_loader__WEBPACK_IMPORTED_MODULE_1__.PlaylistLevelType.MAIN) {
  3301. var activeFragment = this.activeFragment,
  3302. activeParts = this.activeParts;
  3303. if (!activeFragment) {
  3304. return null;
  3305. }
  3306. if (activeParts) {
  3307. for (var i = activeParts.length; i--;) {
  3308. var activePart = activeParts[i];
  3309. var appendedPTS = activePart ? activePart.end : activeFragment.appendedPTS;
  3310. if (activePart.start <= position && appendedPTS !== undefined && position <= appendedPTS) {
  3311. // 9 is a magic number. remove parts from lookup after a match but keep some short seeks back.
  3312. if (i > 9) {
  3313. this.activeParts = activeParts.slice(i - 9);
  3314. }
  3315. return activePart;
  3316. }
  3317. }
  3318. } else if (activeFragment.start <= position && activeFragment.appendedPTS !== undefined && position <= activeFragment.appendedPTS) {
  3319. return activeFragment;
  3320. }
  3321. }
  3322. return this.getBufferedFrag(position, levelType);
  3323. }
  3324. /**
  3325. * Return a buffered Fragment that matches the position and levelType.
  3326. * A buffered Fragment is one whose loading, parsing and appending is done (completed or "partial" meaning aborted).
  3327. * If not found any Fragment, return null
  3328. */;
  3329. _proto.getBufferedFrag = function getBufferedFrag(position, levelType) {
  3330. var fragments = this.fragments;
  3331. var keys = Object.keys(fragments);
  3332. for (var i = keys.length; i--;) {
  3333. var fragmentEntity = fragments[keys[i]];
  3334. if ((fragmentEntity === null || fragmentEntity === void 0 ? void 0 : fragmentEntity.body.type) === levelType && fragmentEntity.buffered) {
  3335. var frag = fragmentEntity.body;
  3336. if (frag.start <= position && position <= frag.end) {
  3337. return frag;
  3338. }
  3339. }
  3340. }
  3341. return null;
  3342. }
  3343. /**
  3344. * Partial fragments effected by coded frame eviction will be removed
  3345. * The browser will unload parts of the buffer to free up memory for new buffer data
  3346. * 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)
  3347. */;
  3348. _proto.detectEvictedFragments = function detectEvictedFragments(elementaryStream, timeRange, playlistType) {
  3349. var _this = this;
  3350. // Check if any flagged fragments have been unloaded
  3351. Object.keys(this.fragments).forEach(function (key) {
  3352. var fragmentEntity = _this.fragments[key];
  3353. if (!fragmentEntity) {
  3354. return;
  3355. }
  3356. if (!fragmentEntity.buffered) {
  3357. if (fragmentEntity.body.type === playlistType) {
  3358. _this.removeFragment(fragmentEntity.body);
  3359. }
  3360. return;
  3361. }
  3362. var esData = fragmentEntity.range[elementaryStream];
  3363. if (!esData) {
  3364. return;
  3365. }
  3366. esData.time.some(function (time) {
  3367. var isNotBuffered = !_this.isTimeBuffered(time.startPTS, time.endPTS, timeRange);
  3368. if (isNotBuffered) {
  3369. // Unregister partial fragment as it needs to load again to be reused
  3370. _this.removeFragment(fragmentEntity.body);
  3371. }
  3372. return isNotBuffered;
  3373. });
  3374. });
  3375. }
  3376. /**
  3377. * Checks if the fragment passed in is loaded in the buffer properly
  3378. * Partially loaded fragments will be registered as a partial fragment
  3379. */;
  3380. _proto.detectPartialFragments = function detectPartialFragments(data) {
  3381. var _this2 = this;
  3382. var timeRanges = this.timeRanges;
  3383. var frag = data.frag,
  3384. part = data.part;
  3385. if (!timeRanges || frag.sn === 'initSegment') {
  3386. return;
  3387. }
  3388. var fragKey = getFragmentKey(frag);
  3389. var fragmentEntity = this.fragments[fragKey];
  3390. if (!fragmentEntity) {
  3391. return;
  3392. }
  3393. Object.keys(timeRanges).forEach(function (elementaryStream) {
  3394. var streamInfo = frag.elementaryStreams[elementaryStream];
  3395. if (!streamInfo) {
  3396. return;
  3397. }
  3398. var timeRange = timeRanges[elementaryStream];
  3399. var partial = part !== null || streamInfo.partial === true;
  3400. fragmentEntity.range[elementaryStream] = _this2.getBufferedTimes(frag, part, partial, timeRange);
  3401. });
  3402. fragmentEntity.loaded = null;
  3403. if (Object.keys(fragmentEntity.range).length) {
  3404. fragmentEntity.buffered = true;
  3405. } else {
  3406. // remove fragment if nothing was appended
  3407. this.removeFragment(fragmentEntity.body);
  3408. }
  3409. };
  3410. _proto.fragBuffered = function fragBuffered(frag) {
  3411. var fragKey = getFragmentKey(frag);
  3412. var fragmentEntity = this.fragments[fragKey];
  3413. if (fragmentEntity) {
  3414. fragmentEntity.loaded = null;
  3415. fragmentEntity.buffered = true;
  3416. }
  3417. };
  3418. _proto.getBufferedTimes = function getBufferedTimes(fragment, part, partial, timeRange) {
  3419. var buffered = {
  3420. time: [],
  3421. partial: partial
  3422. };
  3423. var startPTS = part ? part.start : fragment.start;
  3424. var endPTS = part ? part.end : fragment.end;
  3425. var minEndPTS = fragment.minEndPTS || endPTS;
  3426. var maxStartPTS = fragment.maxStartPTS || startPTS;
  3427. for (var i = 0; i < timeRange.length; i++) {
  3428. var startTime = timeRange.start(i) - this.bufferPadding;
  3429. var endTime = timeRange.end(i) + this.bufferPadding;
  3430. if (maxStartPTS >= startTime && minEndPTS <= endTime) {
  3431. // Fragment is entirely contained in buffer
  3432. // No need to check the other timeRange times since it's completely playable
  3433. buffered.time.push({
  3434. startPTS: Math.max(startPTS, timeRange.start(i)),
  3435. endPTS: Math.min(endPTS, timeRange.end(i))
  3436. });
  3437. break;
  3438. } else if (startPTS < endTime && endPTS > startTime) {
  3439. buffered.partial = true;
  3440. // Check for intersection with buffer
  3441. // Get playable sections of the fragment
  3442. buffered.time.push({
  3443. startPTS: Math.max(startPTS, timeRange.start(i)),
  3444. endPTS: Math.min(endPTS, timeRange.end(i))
  3445. });
  3446. } else if (endPTS <= startTime) {
  3447. // No need to check the rest of the timeRange as it is in order
  3448. break;
  3449. }
  3450. }
  3451. return buffered;
  3452. }
  3453. /**
  3454. * Gets the partial fragment for a certain time
  3455. */;
  3456. _proto.getPartialFragment = function getPartialFragment(time) {
  3457. var bestFragment = null;
  3458. var timePadding;
  3459. var startTime;
  3460. var endTime;
  3461. var bestOverlap = 0;
  3462. var bufferPadding = this.bufferPadding,
  3463. fragments = this.fragments;
  3464. Object.keys(fragments).forEach(function (key) {
  3465. var fragmentEntity = fragments[key];
  3466. if (!fragmentEntity) {
  3467. return;
  3468. }
  3469. if (isPartial(fragmentEntity)) {
  3470. startTime = fragmentEntity.body.start - bufferPadding;
  3471. endTime = fragmentEntity.body.end + bufferPadding;
  3472. if (time >= startTime && time <= endTime) {
  3473. // Use the fragment that has the most padding from start and end time
  3474. timePadding = Math.min(time - startTime, endTime - time);
  3475. if (bestOverlap <= timePadding) {
  3476. bestFragment = fragmentEntity.body;
  3477. bestOverlap = timePadding;
  3478. }
  3479. }
  3480. }
  3481. });
  3482. return bestFragment;
  3483. };
  3484. _proto.getState = function getState(fragment) {
  3485. var fragKey = getFragmentKey(fragment);
  3486. var fragmentEntity = this.fragments[fragKey];
  3487. if (fragmentEntity) {
  3488. if (!fragmentEntity.buffered) {
  3489. return FragmentState.APPENDING;
  3490. } else if (isPartial(fragmentEntity)) {
  3491. return FragmentState.PARTIAL;
  3492. } else {
  3493. return FragmentState.OK;
  3494. }
  3495. }
  3496. return FragmentState.NOT_LOADED;
  3497. };
  3498. _proto.isTimeBuffered = function isTimeBuffered(startPTS, endPTS, timeRange) {
  3499. var startTime;
  3500. var endTime;
  3501. for (var i = 0; i < timeRange.length; i++) {
  3502. startTime = timeRange.start(i) - this.bufferPadding;
  3503. endTime = timeRange.end(i) + this.bufferPadding;
  3504. if (startPTS >= startTime && endPTS <= endTime) {
  3505. return true;
  3506. }
  3507. if (endPTS <= startTime) {
  3508. // No need to check the rest of the timeRange as it is in order
  3509. return false;
  3510. }
  3511. }
  3512. return false;
  3513. };
  3514. _proto.onFragLoaded = function onFragLoaded(event, data) {
  3515. var frag = data.frag,
  3516. part = data.part;
  3517. // don't track initsegment (for which sn is not a number)
  3518. // don't track frags used for bitrateTest, they're irrelevant.
  3519. // don't track parts for memory efficiency
  3520. if (frag.sn === 'initSegment' || frag.bitrateTest || part) {
  3521. return;
  3522. }
  3523. var fragKey = getFragmentKey(frag);
  3524. this.fragments[fragKey] = {
  3525. body: frag,
  3526. loaded: data,
  3527. buffered: false,
  3528. range: Object.create(null)
  3529. };
  3530. };
  3531. _proto.onBufferAppended = function onBufferAppended(event, data) {
  3532. var _this3 = this;
  3533. var frag = data.frag,
  3534. part = data.part,
  3535. timeRanges = data.timeRanges;
  3536. if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_1__.PlaylistLevelType.MAIN) {
  3537. if (this.activeFragment !== frag) {
  3538. this.activeFragment = frag;
  3539. frag.appendedPTS = undefined;
  3540. }
  3541. if (part) {
  3542. var activeParts = this.activeParts;
  3543. if (!activeParts) {
  3544. this.activeParts = activeParts = [];
  3545. }
  3546. activeParts.push(part);
  3547. } else {
  3548. this.activeParts = null;
  3549. }
  3550. }
  3551. // Store the latest timeRanges loaded in the buffer
  3552. this.timeRanges = timeRanges;
  3553. Object.keys(timeRanges).forEach(function (elementaryStream) {
  3554. var timeRange = timeRanges[elementaryStream];
  3555. _this3.detectEvictedFragments(elementaryStream, timeRange);
  3556. if (!part && frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_1__.PlaylistLevelType.MAIN) {
  3557. var streamInfo = frag.elementaryStreams[elementaryStream];
  3558. if (!streamInfo) {
  3559. return;
  3560. }
  3561. for (var i = 0; i < timeRange.length; i++) {
  3562. var rangeEnd = timeRange.end(i);
  3563. if (rangeEnd <= streamInfo.endPTS && rangeEnd > streamInfo.startPTS) {
  3564. frag.appendedPTS = Math.max(rangeEnd, frag.appendedPTS || 0);
  3565. } else {
  3566. frag.appendedPTS = streamInfo.endPTS;
  3567. }
  3568. }
  3569. }
  3570. });
  3571. };
  3572. _proto.onFragBuffered = function onFragBuffered(event, data) {
  3573. this.detectPartialFragments(data);
  3574. };
  3575. _proto.hasFragment = function hasFragment(fragment) {
  3576. var fragKey = getFragmentKey(fragment);
  3577. return !!this.fragments[fragKey];
  3578. };
  3579. _proto.removeFragmentsInRange = function removeFragmentsInRange(start, end, playlistType) {
  3580. var _this4 = this;
  3581. Object.keys(this.fragments).forEach(function (key) {
  3582. var fragmentEntity = _this4.fragments[key];
  3583. if (!fragmentEntity) {
  3584. return;
  3585. }
  3586. if (fragmentEntity.buffered) {
  3587. var frag = fragmentEntity.body;
  3588. if (frag.type === playlistType && frag.start < end && frag.end > start) {
  3589. _this4.removeFragment(frag);
  3590. }
  3591. }
  3592. });
  3593. };
  3594. _proto.removeFragment = function removeFragment(fragment) {
  3595. var fragKey = getFragmentKey(fragment);
  3596. fragment.stats.loaded = 0;
  3597. fragment.clearElementaryStreamInfo();
  3598. fragment.appendedPTS = undefined;
  3599. delete this.fragments[fragKey];
  3600. };
  3601. _proto.removeAllFragments = function removeAllFragments() {
  3602. this.fragments = Object.create(null);
  3603. this.activeFragment = null;
  3604. this.activeParts = null;
  3605. };
  3606. return FragmentTracker;
  3607. }();
  3608. function isPartial(fragmentEntity) {
  3609. var _fragmentEntity$range, _fragmentEntity$range2;
  3610. return fragmentEntity.buffered && (((_fragmentEntity$range = fragmentEntity.range.video) === null || _fragmentEntity$range === void 0 ? void 0 : _fragmentEntity$range.partial) || ((_fragmentEntity$range2 = fragmentEntity.range.audio) === null || _fragmentEntity$range2 === void 0 ? void 0 : _fragmentEntity$range2.partial));
  3611. }
  3612. function getFragmentKey(fragment) {
  3613. return fragment.type + "_" + fragment.level + "_" + fragment.urlId + "_" + fragment.sn;
  3614. }
  3615. /***/ }),
  3616. /***/ "./src/controller/gap-controller.ts":
  3617. /*!******************************************!*\
  3618. !*** ./src/controller/gap-controller.ts ***!
  3619. \******************************************/
  3620. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  3621. "use strict";
  3622. __webpack_require__.r(__webpack_exports__);
  3623. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  3624. /* harmony export */ "MAX_START_GAP_JUMP": () => (/* binding */ MAX_START_GAP_JUMP),
  3625. /* harmony export */ "SKIP_BUFFER_HOLE_STEP_SECONDS": () => (/* binding */ SKIP_BUFFER_HOLE_STEP_SECONDS),
  3626. /* harmony export */ "SKIP_BUFFER_RANGE_START": () => (/* binding */ SKIP_BUFFER_RANGE_START),
  3627. /* harmony export */ "STALL_MINIMUM_DURATION_MS": () => (/* binding */ STALL_MINIMUM_DURATION_MS),
  3628. /* harmony export */ "default": () => (/* binding */ GapController)
  3629. /* harmony export */ });
  3630. /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
  3631. /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
  3632. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts");
  3633. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
  3634. var STALL_MINIMUM_DURATION_MS = 250;
  3635. var MAX_START_GAP_JUMP = 2.0;
  3636. var SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;
  3637. var SKIP_BUFFER_RANGE_START = 0.05;
  3638. var GapController = /*#__PURE__*/function () {
  3639. function GapController(config, media, fragmentTracker, hls) {
  3640. this.config = void 0;
  3641. this.media = null;
  3642. this.fragmentTracker = void 0;
  3643. this.hls = void 0;
  3644. this.nudgeRetry = 0;
  3645. this.stallReported = false;
  3646. this.stalled = null;
  3647. this.moved = false;
  3648. this.seeking = false;
  3649. this.config = config;
  3650. this.media = media;
  3651. this.fragmentTracker = fragmentTracker;
  3652. this.hls = hls;
  3653. }
  3654. var _proto = GapController.prototype;
  3655. _proto.destroy = function destroy() {
  3656. this.media = null;
  3657. // @ts-ignore
  3658. this.hls = this.fragmentTracker = null;
  3659. }
  3660. /**
  3661. * Checks if the playhead is stuck within a gap, and if so, attempts to free it.
  3662. * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).
  3663. *
  3664. * @param {number} lastCurrentTime Previously read playhead position
  3665. */;
  3666. _proto.poll = function poll(lastCurrentTime, activeFrag) {
  3667. var config = this.config,
  3668. media = this.media,
  3669. stalled = this.stalled;
  3670. if (media === null) {
  3671. return;
  3672. }
  3673. var currentTime = media.currentTime,
  3674. seeking = media.seeking;
  3675. var seeked = this.seeking && !seeking;
  3676. var beginSeek = !this.seeking && seeking;
  3677. this.seeking = seeking;
  3678. // The playhead is moving, no-op
  3679. if (currentTime !== lastCurrentTime) {
  3680. this.moved = true;
  3681. if (stalled !== null) {
  3682. // The playhead is now moving, but was previously stalled
  3683. if (this.stallReported) {
  3684. var _stalledDuration = self.performance.now() - stalled;
  3685. _utils_logger__WEBPACK_IMPORTED_MODULE_3__.logger.warn("playback not stuck anymore @" + currentTime + ", after " + Math.round(_stalledDuration) + "ms");
  3686. this.stallReported = false;
  3687. }
  3688. this.stalled = null;
  3689. this.nudgeRetry = 0;
  3690. }
  3691. return;
  3692. }
  3693. // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek
  3694. if (beginSeek || seeked) {
  3695. this.stalled = null;
  3696. }
  3697. // The playhead should not be moving
  3698. if (media.paused && !seeking || media.ended || media.playbackRate === 0 || !_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__.BufferHelper.getBuffered(media).length) {
  3699. return;
  3700. }
  3701. var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__.BufferHelper.bufferInfo(media, currentTime, 0);
  3702. var isBuffered = bufferInfo.len > 0;
  3703. var nextStart = bufferInfo.nextStart || 0;
  3704. // There is no playable buffer (seeked, waiting for buffer)
  3705. if (!isBuffered && !nextStart) {
  3706. return;
  3707. }
  3708. if (seeking) {
  3709. // Waiting for seeking in a buffered range to complete
  3710. var hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP;
  3711. // Next buffered range is too far ahead to jump to while still seeking
  3712. var noBufferGap = !nextStart || activeFrag && activeFrag.start <= currentTime || nextStart - currentTime > MAX_START_GAP_JUMP && !this.fragmentTracker.getPartialFragment(currentTime);
  3713. if (hasEnoughBuffer || noBufferGap) {
  3714. return;
  3715. }
  3716. // Reset moved state when seeking to a point in or before a gap
  3717. this.moved = false;
  3718. }
  3719. // Skip start gaps if we haven't played, but the last poll detected the start of a stall
  3720. // The addition poll gives the browser a chance to jump the gap for us
  3721. if (!this.moved && this.stalled !== null) {
  3722. var _level$details;
  3723. // Jump start gaps within jump threshold
  3724. var startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime;
  3725. // When joining a live stream with audio tracks, account for live playlist window sliding by allowing
  3726. // a larger jump over start gaps caused by the audio-stream-controller buffering a start fragment
  3727. // that begins over 1 target duration after the video start position.
  3728. var level = this.hls.levels ? this.hls.levels[this.hls.currentLevel] : null;
  3729. var isLive = level === null || level === void 0 ? void 0 : (_level$details = level.details) === null || _level$details === void 0 ? void 0 : _level$details.live;
  3730. var maxStartGapJump = isLive ? level.details.targetduration * 2 : MAX_START_GAP_JUMP;
  3731. if (startJump > 0 && startJump <= maxStartGapJump) {
  3732. this._trySkipBufferHole(null);
  3733. return;
  3734. }
  3735. }
  3736. // Start tracking stall time
  3737. var tnow = self.performance.now();
  3738. if (stalled === null) {
  3739. this.stalled = tnow;
  3740. return;
  3741. }
  3742. var stalledDuration = tnow - stalled;
  3743. if (!seeking && stalledDuration >= STALL_MINIMUM_DURATION_MS) {
  3744. // Report stalling after trying to fix
  3745. this._reportStall(bufferInfo);
  3746. if (!this.media) {
  3747. return;
  3748. }
  3749. }
  3750. var bufferedWithHoles = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__.BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);
  3751. this._tryFixBufferStall(bufferedWithHoles, stalledDuration);
  3752. }
  3753. /**
  3754. * Detects and attempts to fix known buffer stalling issues.
  3755. * @param bufferInfo - The properties of the current buffer.
  3756. * @param stalledDurationMs - The amount of time Hls.js has been stalling for.
  3757. * @private
  3758. */;
  3759. _proto._tryFixBufferStall = function _tryFixBufferStall(bufferInfo, stalledDurationMs) {
  3760. var config = this.config,
  3761. fragmentTracker = this.fragmentTracker,
  3762. media = this.media;
  3763. if (media === null) {
  3764. return;
  3765. }
  3766. var currentTime = media.currentTime;
  3767. var partial = fragmentTracker.getPartialFragment(currentTime);
  3768. if (partial) {
  3769. // Try to skip over the buffer hole caused by a partial fragment
  3770. // This method isn't limited by the size of the gap between buffered ranges
  3771. var targetTime = this._trySkipBufferHole(partial);
  3772. // we return here in this case, meaning
  3773. // the branch below only executes when we don't handle a partial fragment
  3774. if (targetTime || !this.media) {
  3775. return;
  3776. }
  3777. }
  3778. // if we haven't had to skip over a buffer hole of a partial fragment
  3779. // we may just have to "nudge" the playlist as the browser decoding/rendering engine
  3780. // needs to cross some sort of threshold covering all source-buffers content
  3781. // to start playing properly.
  3782. if (bufferInfo.len > config.maxBufferHole && stalledDurationMs > config.highBufferWatchdogPeriod * 1000) {
  3783. _utils_logger__WEBPACK_IMPORTED_MODULE_3__.logger.warn('Trying to nudge playhead over buffer-hole');
  3784. // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds
  3785. // We only try to jump the hole if it's under the configured size
  3786. // Reset stalled so to rearm watchdog timer
  3787. this.stalled = null;
  3788. this._tryNudgeBuffer();
  3789. }
  3790. }
  3791. /**
  3792. * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.
  3793. * @param bufferLen - The playhead distance from the end of the current buffer segment.
  3794. * @private
  3795. */;
  3796. _proto._reportStall = function _reportStall(bufferInfo) {
  3797. var hls = this.hls,
  3798. media = this.media,
  3799. stallReported = this.stallReported;
  3800. if (!stallReported && media) {
  3801. // Report stalled error once
  3802. this.stallReported = true;
  3803. _utils_logger__WEBPACK_IMPORTED_MODULE_3__.logger.warn("Playback stalling at @" + media.currentTime + " due to low buffer (" + JSON.stringify(bufferInfo) + ")");
  3804. hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__.Events.ERROR, {
  3805. type: _errors__WEBPACK_IMPORTED_MODULE_1__.ErrorTypes.MEDIA_ERROR,
  3806. details: _errors__WEBPACK_IMPORTED_MODULE_1__.ErrorDetails.BUFFER_STALLED_ERROR,
  3807. fatal: false,
  3808. buffer: bufferInfo.len
  3809. });
  3810. }
  3811. }
  3812. /**
  3813. * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
  3814. * @param partial - The partial fragment found at the current time (where playback is stalling).
  3815. * @private
  3816. */;
  3817. _proto._trySkipBufferHole = function _trySkipBufferHole(partial) {
  3818. var config = this.config,
  3819. hls = this.hls,
  3820. media = this.media;
  3821. if (media === null) {
  3822. return 0;
  3823. }
  3824. var currentTime = media.currentTime;
  3825. var lastEndTime = 0;
  3826. // Check if currentTime is between unbuffered regions of partial fragments
  3827. var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__.BufferHelper.getBuffered(media);
  3828. for (var i = 0; i < buffered.length; i++) {
  3829. var startTime = buffered.start(i);
  3830. if (currentTime + config.maxBufferHole >= lastEndTime && currentTime < startTime) {
  3831. var targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, media.currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);
  3832. _utils_logger__WEBPACK_IMPORTED_MODULE_3__.logger.warn("skipping hole, adjusting currentTime from " + currentTime + " to " + targetTime);
  3833. this.moved = true;
  3834. this.stalled = null;
  3835. media.currentTime = targetTime;
  3836. if (partial) {
  3837. hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__.Events.ERROR, {
  3838. type: _errors__WEBPACK_IMPORTED_MODULE_1__.ErrorTypes.MEDIA_ERROR,
  3839. details: _errors__WEBPACK_IMPORTED_MODULE_1__.ErrorDetails.BUFFER_SEEK_OVER_HOLE,
  3840. fatal: false,
  3841. reason: "fragment loaded with buffer holes, seeking from " + currentTime + " to " + targetTime,
  3842. frag: partial
  3843. });
  3844. }
  3845. return targetTime;
  3846. }
  3847. lastEndTime = buffered.end(i);
  3848. }
  3849. return 0;
  3850. }
  3851. /**
  3852. * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
  3853. * @private
  3854. */;
  3855. _proto._tryNudgeBuffer = function _tryNudgeBuffer() {
  3856. var config = this.config,
  3857. hls = this.hls,
  3858. media = this.media,
  3859. nudgeRetry = this.nudgeRetry;
  3860. if (media === null) {
  3861. return;
  3862. }
  3863. var currentTime = media.currentTime;
  3864. this.nudgeRetry++;
  3865. if (nudgeRetry < config.nudgeMaxRetry) {
  3866. var targetTime = currentTime + (nudgeRetry + 1) * config.nudgeOffset;
  3867. // playback stalled in buffered area ... let's nudge currentTime to try to overcome this
  3868. _utils_logger__WEBPACK_IMPORTED_MODULE_3__.logger.warn("Nudging 'currentTime' from " + currentTime + " to " + targetTime);
  3869. media.currentTime = targetTime;
  3870. hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__.Events.ERROR, {
  3871. type: _errors__WEBPACK_IMPORTED_MODULE_1__.ErrorTypes.MEDIA_ERROR,
  3872. details: _errors__WEBPACK_IMPORTED_MODULE_1__.ErrorDetails.BUFFER_NUDGE_ON_STALL,
  3873. fatal: false
  3874. });
  3875. } else {
  3876. _utils_logger__WEBPACK_IMPORTED_MODULE_3__.logger.error("Playhead still not moving while enough data buffered @" + currentTime + " after " + config.nudgeMaxRetry + " nudges");
  3877. hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__.Events.ERROR, {
  3878. type: _errors__WEBPACK_IMPORTED_MODULE_1__.ErrorTypes.MEDIA_ERROR,
  3879. details: _errors__WEBPACK_IMPORTED_MODULE_1__.ErrorDetails.BUFFER_STALLED_ERROR,
  3880. fatal: true
  3881. });
  3882. }
  3883. };
  3884. return GapController;
  3885. }();
  3886. /***/ }),
  3887. /***/ "./src/controller/id3-track-controller.ts":
  3888. /*!************************************************!*\
  3889. !*** ./src/controller/id3-track-controller.ts ***!
  3890. \************************************************/
  3891. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  3892. "use strict";
  3893. __webpack_require__.r(__webpack_exports__);
  3894. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  3895. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  3896. /* harmony export */ });
  3897. /* harmony import */ var _Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
  3898. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
  3899. /* harmony import */ var _utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/texttrack-utils */ "./src/utils/texttrack-utils.ts");
  3900. /* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
  3901. /* harmony import */ var _loader_date_range__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../loader/date-range */ "./src/loader/date-range.ts");
  3902. /* harmony import */ var _types_demuxer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../types/demuxer */ "./src/types/demuxer.ts");
  3903. var MIN_CUE_DURATION = 0.25;
  3904. function getCueClass() {
  3905. // Attempt to recreate Safari functionality by creating
  3906. // WebKitDataCue objects when available and store the decoded
  3907. // ID3 data in the value property of the cue
  3908. return self.WebKitDataCue || self.VTTCue || self.TextTrackCue;
  3909. }
  3910. // VTTCue latest draft allows an infinite duration, fallback
  3911. // to MAX_VALUE if necessary
  3912. var MAX_CUE_ENDTIME = function () {
  3913. var Cue = getCueClass();
  3914. try {
  3915. new Cue(0, Number.POSITIVE_INFINITY, '');
  3916. } catch (e) {
  3917. return Number.MAX_VALUE;
  3918. }
  3919. return Number.POSITIVE_INFINITY;
  3920. }();
  3921. function dateRangeDateToTimelineSeconds(date, offset) {
  3922. return date.getTime() / 1000 - offset;
  3923. }
  3924. function hexToArrayBuffer(str) {
  3925. return Uint8Array.from(str.replace(/^0x/, '').replace(/([\da-fA-F]{2}) ?/g, '0x$1 ').replace(/ +$/, '').split(' ')).buffer;
  3926. }
  3927. var ID3TrackController = /*#__PURE__*/function () {
  3928. function ID3TrackController(hls) {
  3929. this.hls = void 0;
  3930. this.id3Track = null;
  3931. this.media = null;
  3932. this.dateRangeCuesAppended = {};
  3933. this.hls = hls;
  3934. this._registerListeners();
  3935. }
  3936. var _proto = ID3TrackController.prototype;
  3937. _proto.destroy = function destroy() {
  3938. this._unregisterListeners();
  3939. this.id3Track = null;
  3940. this.media = null;
  3941. this.dateRangeCuesAppended = {};
  3942. // @ts-ignore
  3943. this.hls = null;
  3944. };
  3945. _proto._registerListeners = function _registerListeners() {
  3946. var hls = this.hls;
  3947. hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  3948. hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  3949. hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3950. hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  3951. hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  3952. hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  3953. };
  3954. _proto._unregisterListeners = function _unregisterListeners() {
  3955. var hls = this.hls;
  3956. hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  3957. hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  3958. hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3959. hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  3960. hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  3961. hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  3962. }
  3963. // Add ID3 metatadata text track.
  3964. ;
  3965. _proto.onMediaAttached = function onMediaAttached(event, data) {
  3966. this.media = data.media;
  3967. };
  3968. _proto.onMediaDetaching = function onMediaDetaching() {
  3969. if (!this.id3Track) {
  3970. return;
  3971. }
  3972. (0,_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_2__.clearCurrentCues)(this.id3Track);
  3973. this.id3Track = null;
  3974. this.media = null;
  3975. this.dateRangeCuesAppended = {};
  3976. };
  3977. _proto.onManifestLoading = function onManifestLoading() {
  3978. this.dateRangeCuesAppended = {};
  3979. };
  3980. _proto.createTrack = function createTrack(media) {
  3981. var track = this.getID3Track(media.textTracks);
  3982. track.mode = 'hidden';
  3983. return track;
  3984. };
  3985. _proto.getID3Track = function getID3Track(textTracks) {
  3986. if (!this.media) {
  3987. return;
  3988. }
  3989. for (var i = 0; i < textTracks.length; i++) {
  3990. var textTrack = textTracks[i];
  3991. if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {
  3992. // send 'addtrack' when reusing the textTrack for metadata,
  3993. // same as what we do for captions
  3994. (0,_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_2__.sendAddTrackEvent)(textTrack, this.media);
  3995. return textTrack;
  3996. }
  3997. }
  3998. return this.media.addTextTrack('metadata', 'id3');
  3999. };
  4000. _proto.onFragParsingMetadata = function onFragParsingMetadata(event, data) {
  4001. if (!this.media) {
  4002. return;
  4003. }
  4004. var _this$hls$config = this.hls.config,
  4005. enableEmsgMetadataCues = _this$hls$config.enableEmsgMetadataCues,
  4006. enableID3MetadataCues = _this$hls$config.enableID3MetadataCues;
  4007. if (!enableEmsgMetadataCues && !enableID3MetadataCues) {
  4008. return;
  4009. }
  4010. var fragment = data.frag,
  4011. samples = data.samples,
  4012. details = data.details;
  4013. // create track dynamically
  4014. if (!this.id3Track) {
  4015. this.id3Track = this.createTrack(this.media);
  4016. }
  4017. var Cue = getCueClass();
  4018. for (var i = 0; i < samples.length; i++) {
  4019. var type = samples[i].type;
  4020. if (type === _types_demuxer__WEBPACK_IMPORTED_MODULE_5__.MetadataSchema.emsg && !enableEmsgMetadataCues || !enableID3MetadataCues) {
  4021. continue;
  4022. }
  4023. var frames = _demux_id3__WEBPACK_IMPORTED_MODULE_3__.getID3Frames(samples[i].data);
  4024. if (frames) {
  4025. var startTime = samples[i].pts;
  4026. var endTime = startTime + samples[i].duration;
  4027. if (endTime > MAX_CUE_ENDTIME) {
  4028. endTime = MAX_CUE_ENDTIME;
  4029. }
  4030. var timeDiff = endTime - startTime;
  4031. if (timeDiff <= 0) {
  4032. endTime = startTime + MIN_CUE_DURATION;
  4033. }
  4034. for (var j = 0; j < frames.length; j++) {
  4035. var frame = frames[j];
  4036. // Safari doesn't put the timestamp frame in the TextTrack
  4037. if (!_demux_id3__WEBPACK_IMPORTED_MODULE_3__.isTimeStampFrame(frame)) {
  4038. // add a bounds to any unbounded cues
  4039. this.updateId3CueEnds(startTime);
  4040. var cue = new Cue(startTime, endTime, '');
  4041. cue.value = frame;
  4042. if (type) {
  4043. cue.type = type;
  4044. }
  4045. this.id3Track.addCue(cue);
  4046. }
  4047. }
  4048. }
  4049. }
  4050. };
  4051. _proto.updateId3CueEnds = function updateId3CueEnds(startTime) {
  4052. var _this$id3Track;
  4053. var cues = (_this$id3Track = this.id3Track) === null || _this$id3Track === void 0 ? void 0 : _this$id3Track.cues;
  4054. if (cues) {
  4055. for (var i = cues.length; i--;) {
  4056. var cue = cues[i];
  4057. if (cue.startTime < startTime && cue.endTime === MAX_CUE_ENDTIME) {
  4058. cue.endTime = startTime;
  4059. }
  4060. }
  4061. }
  4062. };
  4063. _proto.onBufferFlushing = function onBufferFlushing(event, _ref) {
  4064. var startOffset = _ref.startOffset,
  4065. endOffset = _ref.endOffset,
  4066. type = _ref.type;
  4067. var id3Track = this.id3Track,
  4068. hls = this.hls;
  4069. if (!hls) {
  4070. return;
  4071. }
  4072. var _hls$config = hls.config,
  4073. enableEmsgMetadataCues = _hls$config.enableEmsgMetadataCues,
  4074. enableID3MetadataCues = _hls$config.enableID3MetadataCues;
  4075. if (id3Track && (enableEmsgMetadataCues || enableID3MetadataCues)) {
  4076. var predicate;
  4077. if (type === 'audio') {
  4078. predicate = function predicate(cue) {
  4079. return cue.type === _types_demuxer__WEBPACK_IMPORTED_MODULE_5__.MetadataSchema.audioId3 && enableID3MetadataCues;
  4080. };
  4081. } else if (type === 'video') {
  4082. predicate = function predicate(cue) {
  4083. return cue.type === _types_demuxer__WEBPACK_IMPORTED_MODULE_5__.MetadataSchema.emsg && enableEmsgMetadataCues;
  4084. };
  4085. } else {
  4086. predicate = function predicate(cue) {
  4087. return cue.type === _types_demuxer__WEBPACK_IMPORTED_MODULE_5__.MetadataSchema.audioId3 && enableID3MetadataCues || cue.type === _types_demuxer__WEBPACK_IMPORTED_MODULE_5__.MetadataSchema.emsg && enableEmsgMetadataCues;
  4088. };
  4089. }
  4090. (0,_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_2__.removeCuesInRange)(id3Track, startOffset, endOffset, predicate);
  4091. }
  4092. };
  4093. _proto.onLevelUpdated = function onLevelUpdated(event, _ref2) {
  4094. var _this = this;
  4095. var details = _ref2.details;
  4096. if (!this.media || !details.hasProgramDateTime || !this.hls.config.enableDateRangeMetadataCues) {
  4097. return;
  4098. }
  4099. var dateRangeCuesAppended = this.dateRangeCuesAppended,
  4100. id3Track = this.id3Track;
  4101. var dateRanges = details.dateRanges;
  4102. var ids = Object.keys(dateRanges);
  4103. // Remove cues from track not found in details.dateRanges
  4104. if (id3Track) {
  4105. var idsToRemove = Object.keys(dateRangeCuesAppended).filter(function (id) {
  4106. return !ids.includes(id);
  4107. });
  4108. var _loop = function _loop(i) {
  4109. var id = idsToRemove[i];
  4110. Object.keys(dateRangeCuesAppended[id].cues).forEach(function (key) {
  4111. id3Track.removeCue(dateRangeCuesAppended[id].cues[key]);
  4112. });
  4113. delete dateRangeCuesAppended[id];
  4114. };
  4115. for (var i = idsToRemove.length; i--;) {
  4116. _loop(i);
  4117. }
  4118. }
  4119. // Exit if the playlist does not have Date Ranges or does not have Program Date Time
  4120. var lastFragment = details.fragments[details.fragments.length - 1];
  4121. if (ids.length === 0 || !(0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(lastFragment === null || lastFragment === void 0 ? void 0 : lastFragment.programDateTime)) {
  4122. return;
  4123. }
  4124. if (!this.id3Track) {
  4125. this.id3Track = this.createTrack(this.media);
  4126. }
  4127. var dateTimeOffset = lastFragment.programDateTime / 1000 - lastFragment.start;
  4128. var Cue = getCueClass();
  4129. var _loop2 = function _loop2(_i) {
  4130. var id = ids[_i];
  4131. var dateRange = dateRanges[id];
  4132. var appendedDateRangeCues = dateRangeCuesAppended[id];
  4133. var cues = (appendedDateRangeCues === null || appendedDateRangeCues === void 0 ? void 0 : appendedDateRangeCues.cues) || {};
  4134. var durationKnown = (appendedDateRangeCues === null || appendedDateRangeCues === void 0 ? void 0 : appendedDateRangeCues.durationKnown) || false;
  4135. var startTime = dateRangeDateToTimelineSeconds(dateRange.startDate, dateTimeOffset);
  4136. var endTime = MAX_CUE_ENDTIME;
  4137. var endDate = dateRange.endDate;
  4138. if (endDate) {
  4139. endTime = dateRangeDateToTimelineSeconds(endDate, dateTimeOffset);
  4140. durationKnown = true;
  4141. } else if (dateRange.endOnNext && !durationKnown) {
  4142. var nextDateRangeWithSameClass = ids.reduce(function (filterMapArray, id) {
  4143. var candidate = dateRanges[id];
  4144. if (candidate.class === dateRange.class && candidate.id !== id && candidate.startDate > dateRange.startDate) {
  4145. filterMapArray.push(candidate);
  4146. }
  4147. return filterMapArray;
  4148. }, []).sort(function (a, b) {
  4149. return a.startDate.getTime() - b.startDate.getTime();
  4150. })[0];
  4151. if (nextDateRangeWithSameClass) {
  4152. endTime = dateRangeDateToTimelineSeconds(nextDateRangeWithSameClass.startDate, dateTimeOffset);
  4153. durationKnown = true;
  4154. }
  4155. }
  4156. var attributes = Object.keys(dateRange.attr);
  4157. for (var j = 0; j < attributes.length; j++) {
  4158. var key = attributes[j];
  4159. if (key === _loader_date_range__WEBPACK_IMPORTED_MODULE_4__.DateRangeAttribute.ID || key === _loader_date_range__WEBPACK_IMPORTED_MODULE_4__.DateRangeAttribute.CLASS || key === _loader_date_range__WEBPACK_IMPORTED_MODULE_4__.DateRangeAttribute.START_DATE || key === _loader_date_range__WEBPACK_IMPORTED_MODULE_4__.DateRangeAttribute.DURATION || key === _loader_date_range__WEBPACK_IMPORTED_MODULE_4__.DateRangeAttribute.END_DATE || key === _loader_date_range__WEBPACK_IMPORTED_MODULE_4__.DateRangeAttribute.END_ON_NEXT) {
  4160. continue;
  4161. }
  4162. var cue = cues[key];
  4163. if (cue) {
  4164. if (durationKnown && !appendedDateRangeCues.durationKnown) {
  4165. cue.endTime = endTime;
  4166. }
  4167. } else {
  4168. var data = dateRange.attr[key];
  4169. cue = new Cue(startTime, endTime, '');
  4170. if (key === _loader_date_range__WEBPACK_IMPORTED_MODULE_4__.DateRangeAttribute.SCTE35_OUT || key === _loader_date_range__WEBPACK_IMPORTED_MODULE_4__.DateRangeAttribute.SCTE35_IN) {
  4171. data = hexToArrayBuffer(data);
  4172. }
  4173. cue.value = {
  4174. key: key,
  4175. data: data
  4176. };
  4177. cue.type = _types_demuxer__WEBPACK_IMPORTED_MODULE_5__.MetadataSchema.dateRange;
  4178. _this.id3Track.addCue(cue);
  4179. cues[key] = cue;
  4180. }
  4181. }
  4182. dateRangeCuesAppended[id] = {
  4183. cues: cues,
  4184. dateRange: dateRange,
  4185. durationKnown: durationKnown
  4186. };
  4187. };
  4188. for (var _i = 0; _i < ids.length; _i++) {
  4189. _loop2(_i);
  4190. }
  4191. };
  4192. return ID3TrackController;
  4193. }();
  4194. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (ID3TrackController);
  4195. /***/ }),
  4196. /***/ "./src/controller/latency-controller.ts":
  4197. /*!**********************************************!*\
  4198. !*** ./src/controller/latency-controller.ts ***!
  4199. \**********************************************/
  4200. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  4201. "use strict";
  4202. __webpack_require__.r(__webpack_exports__);
  4203. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  4204. /* harmony export */ "default": () => (/* binding */ LatencyController)
  4205. /* harmony export */ });
  4206. /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
  4207. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
  4208. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
  4209. 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, _toPropertyKey(descriptor.key), descriptor); } }
  4210. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4211. function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
  4212. function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
  4213. var LatencyController = /*#__PURE__*/function () {
  4214. function LatencyController(hls) {
  4215. var _this = this;
  4216. this.hls = void 0;
  4217. this.config = void 0;
  4218. this.media = null;
  4219. this.levelDetails = null;
  4220. this.currentTime = 0;
  4221. this.stallCount = 0;
  4222. this._latency = null;
  4223. this.timeupdateHandler = function () {
  4224. return _this.timeupdate();
  4225. };
  4226. this.hls = hls;
  4227. this.config = hls.config;
  4228. this.registerListeners();
  4229. }
  4230. var _proto = LatencyController.prototype;
  4231. _proto.destroy = function destroy() {
  4232. this.unregisterListeners();
  4233. this.onMediaDetaching();
  4234. this.levelDetails = null;
  4235. // @ts-ignore
  4236. this.hls = this.timeupdateHandler = null;
  4237. };
  4238. _proto.registerListeners = function registerListeners() {
  4239. this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  4240. this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  4241. this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4242. this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  4243. this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.ERROR, this.onError, this);
  4244. };
  4245. _proto.unregisterListeners = function unregisterListeners() {
  4246. this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.MEDIA_ATTACHED, this.onMediaAttached);
  4247. this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.MEDIA_DETACHING, this.onMediaDetaching);
  4248. this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.MANIFEST_LOADING, this.onManifestLoading);
  4249. this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.LEVEL_UPDATED, this.onLevelUpdated);
  4250. this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.ERROR, this.onError);
  4251. };
  4252. _proto.onMediaAttached = function onMediaAttached(event, data) {
  4253. this.media = data.media;
  4254. this.media.addEventListener('timeupdate', this.timeupdateHandler);
  4255. };
  4256. _proto.onMediaDetaching = function onMediaDetaching() {
  4257. if (this.media) {
  4258. this.media.removeEventListener('timeupdate', this.timeupdateHandler);
  4259. this.media = null;
  4260. }
  4261. };
  4262. _proto.onManifestLoading = function onManifestLoading() {
  4263. this.levelDetails = null;
  4264. this._latency = null;
  4265. this.stallCount = 0;
  4266. };
  4267. _proto.onLevelUpdated = function onLevelUpdated(event, _ref) {
  4268. var details = _ref.details;
  4269. this.levelDetails = details;
  4270. if (details.advanced) {
  4271. this.timeupdate();
  4272. }
  4273. if (!details.live && this.media) {
  4274. this.media.removeEventListener('timeupdate', this.timeupdateHandler);
  4275. }
  4276. };
  4277. _proto.onError = function onError(event, data) {
  4278. if (data.details !== _errors__WEBPACK_IMPORTED_MODULE_0__.ErrorDetails.BUFFER_STALLED_ERROR) {
  4279. return;
  4280. }
  4281. this.stallCount++;
  4282. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.warn('[playback-rate-controller]: Stall detected, adjusting target latency');
  4283. };
  4284. _proto.timeupdate = function timeupdate() {
  4285. var media = this.media,
  4286. levelDetails = this.levelDetails;
  4287. if (!media || !levelDetails) {
  4288. return;
  4289. }
  4290. this.currentTime = media.currentTime;
  4291. var latency = this.computeLatency();
  4292. if (latency === null) {
  4293. return;
  4294. }
  4295. this._latency = latency;
  4296. // Adapt playbackRate to meet target latency in low-latency mode
  4297. var _this$config = this.config,
  4298. lowLatencyMode = _this$config.lowLatencyMode,
  4299. maxLiveSyncPlaybackRate = _this$config.maxLiveSyncPlaybackRate;
  4300. if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1) {
  4301. return;
  4302. }
  4303. var targetLatency = this.targetLatency;
  4304. if (targetLatency === null) {
  4305. return;
  4306. }
  4307. var distanceFromTarget = latency - targetLatency;
  4308. // Only adjust playbackRate when within one target duration of targetLatency
  4309. // and more than one second from under-buffering.
  4310. // Playback further than one target duration from target can be considered DVR playback.
  4311. var liveMinLatencyDuration = Math.min(this.maxLatency, targetLatency + levelDetails.targetduration);
  4312. var inLiveRange = distanceFromTarget < liveMinLatencyDuration;
  4313. if (levelDetails.live && inLiveRange && distanceFromTarget > 0.05 && this.forwardBufferLength > 1) {
  4314. var max = Math.min(2, Math.max(1.0, maxLiveSyncPlaybackRate));
  4315. var rate = Math.round(2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled)) * 20) / 20;
  4316. media.playbackRate = Math.min(max, Math.max(1, rate));
  4317. } else if (media.playbackRate !== 1 && media.playbackRate !== 0) {
  4318. media.playbackRate = 1;
  4319. }
  4320. };
  4321. _proto.estimateLiveEdge = function estimateLiveEdge() {
  4322. var levelDetails = this.levelDetails;
  4323. if (levelDetails === null) {
  4324. return null;
  4325. }
  4326. return levelDetails.edge + levelDetails.age;
  4327. };
  4328. _proto.computeLatency = function computeLatency() {
  4329. var liveEdge = this.estimateLiveEdge();
  4330. if (liveEdge === null) {
  4331. return null;
  4332. }
  4333. return liveEdge - this.currentTime;
  4334. };
  4335. _createClass(LatencyController, [{
  4336. key: "latency",
  4337. get: function get() {
  4338. return this._latency || 0;
  4339. }
  4340. }, {
  4341. key: "maxLatency",
  4342. get: function get() {
  4343. var config = this.config,
  4344. levelDetails = this.levelDetails;
  4345. if (config.liveMaxLatencyDuration !== undefined) {
  4346. return config.liveMaxLatencyDuration;
  4347. }
  4348. return levelDetails ? config.liveMaxLatencyDurationCount * levelDetails.targetduration : 0;
  4349. }
  4350. }, {
  4351. key: "targetLatency",
  4352. get: function get() {
  4353. var levelDetails = this.levelDetails;
  4354. if (levelDetails === null) {
  4355. return null;
  4356. }
  4357. var holdBack = levelDetails.holdBack,
  4358. partHoldBack = levelDetails.partHoldBack,
  4359. targetduration = levelDetails.targetduration;
  4360. var _this$config2 = this.config,
  4361. liveSyncDuration = _this$config2.liveSyncDuration,
  4362. liveSyncDurationCount = _this$config2.liveSyncDurationCount,
  4363. lowLatencyMode = _this$config2.lowLatencyMode;
  4364. var userConfig = this.hls.userConfig;
  4365. var targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack;
  4366. if (userConfig.liveSyncDuration || userConfig.liveSyncDurationCount || targetLatency === 0) {
  4367. targetLatency = liveSyncDuration !== undefined ? liveSyncDuration : liveSyncDurationCount * targetduration;
  4368. }
  4369. var maxLiveSyncOnStallIncrease = targetduration;
  4370. var liveSyncOnStallIncrease = 1.0;
  4371. return targetLatency + Math.min(this.stallCount * liveSyncOnStallIncrease, maxLiveSyncOnStallIncrease);
  4372. }
  4373. }, {
  4374. key: "liveSyncPosition",
  4375. get: function get() {
  4376. var liveEdge = this.estimateLiveEdge();
  4377. var targetLatency = this.targetLatency;
  4378. var levelDetails = this.levelDetails;
  4379. if (liveEdge === null || targetLatency === null || levelDetails === null) {
  4380. return null;
  4381. }
  4382. var edge = levelDetails.edge;
  4383. var syncPosition = liveEdge - targetLatency - this.edgeStalled;
  4384. var min = edge - levelDetails.totalduration;
  4385. var max = edge - (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration);
  4386. return Math.min(Math.max(min, syncPosition), max);
  4387. }
  4388. }, {
  4389. key: "drift",
  4390. get: function get() {
  4391. var levelDetails = this.levelDetails;
  4392. if (levelDetails === null) {
  4393. return 1;
  4394. }
  4395. return levelDetails.drift;
  4396. }
  4397. }, {
  4398. key: "edgeStalled",
  4399. get: function get() {
  4400. var levelDetails = this.levelDetails;
  4401. if (levelDetails === null) {
  4402. return 0;
  4403. }
  4404. var maxLevelUpdateAge = (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration) * 3;
  4405. return Math.max(levelDetails.age - maxLevelUpdateAge, 0);
  4406. }
  4407. }, {
  4408. key: "forwardBufferLength",
  4409. get: function get() {
  4410. var media = this.media,
  4411. levelDetails = this.levelDetails;
  4412. if (!media || !levelDetails) {
  4413. return 0;
  4414. }
  4415. var bufferedRanges = media.buffered.length;
  4416. return (bufferedRanges ? media.buffered.end(bufferedRanges - 1) : levelDetails.edge) - this.currentTime;
  4417. }
  4418. }]);
  4419. return LatencyController;
  4420. }();
  4421. /***/ }),
  4422. /***/ "./src/controller/level-controller.ts":
  4423. /*!********************************************!*\
  4424. !*** ./src/controller/level-controller.ts ***!
  4425. \********************************************/
  4426. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  4427. "use strict";
  4428. __webpack_require__.r(__webpack_exports__);
  4429. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  4430. /* harmony export */ "default": () => (/* binding */ LevelController)
  4431. /* harmony export */ });
  4432. /* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../types/level */ "./src/types/level.ts");
  4433. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
  4434. /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
  4435. /* harmony import */ var _utils_codecs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/codecs */ "./src/utils/codecs.ts");
  4436. /* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.ts");
  4437. /* harmony import */ var _base_playlist_controller__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./base-playlist-controller */ "./src/controller/base-playlist-controller.ts");
  4438. /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
  4439. function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
  4440. 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, _toPropertyKey(descriptor.key), descriptor); } }
  4441. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4442. function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
  4443. function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
  4444. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4445. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4446. /*
  4447. * Level Controller
  4448. */
  4449. var chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase());
  4450. var LevelController = /*#__PURE__*/function (_BasePlaylistControll) {
  4451. _inheritsLoose(LevelController, _BasePlaylistControll);
  4452. function LevelController(hls) {
  4453. var _this;
  4454. _this = _BasePlaylistControll.call(this, hls, '[level-controller]') || this;
  4455. _this._levels = [];
  4456. _this._firstLevel = -1;
  4457. _this._startLevel = void 0;
  4458. _this.currentLevelIndex = -1;
  4459. _this.manualLevelIndex = -1;
  4460. _this.onParsedComplete = void 0;
  4461. _this._registerListeners();
  4462. return _this;
  4463. }
  4464. var _proto = LevelController.prototype;
  4465. _proto._registerListeners = function _registerListeners() {
  4466. var hls = this.hls;
  4467. hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  4468. hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.LEVEL_LOADED, this.onLevelLoaded, this);
  4469. hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  4470. hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.FRAG_LOADED, this.onFragLoaded, this);
  4471. hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.ERROR, this.onError, this);
  4472. };
  4473. _proto._unregisterListeners = function _unregisterListeners() {
  4474. var hls = this.hls;
  4475. hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  4476. hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.LEVEL_LOADED, this.onLevelLoaded, this);
  4477. hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  4478. hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.FRAG_LOADED, this.onFragLoaded, this);
  4479. hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.ERROR, this.onError, this);
  4480. };
  4481. _proto.destroy = function destroy() {
  4482. this._unregisterListeners();
  4483. this.manualLevelIndex = -1;
  4484. this._levels.length = 0;
  4485. _BasePlaylistControll.prototype.destroy.call(this);
  4486. };
  4487. _proto.startLoad = function startLoad() {
  4488. var levels = this._levels;
  4489. // clean up live level details to force reload them, and reset load errors
  4490. levels.forEach(function (level) {
  4491. level.loadError = 0;
  4492. });
  4493. _BasePlaylistControll.prototype.startLoad.call(this);
  4494. };
  4495. _proto.onManifestLoaded = function onManifestLoaded(event, data) {
  4496. var levels = [];
  4497. var audioTracks = [];
  4498. var subtitleTracks = [];
  4499. var bitrateStart;
  4500. var levelSet = {};
  4501. var levelFromSet;
  4502. var resolutionFound = false;
  4503. var videoCodecFound = false;
  4504. var audioCodecFound = false;
  4505. // regroup redundant levels together
  4506. data.levels.forEach(function (levelParsed) {
  4507. var attributes = levelParsed.attrs;
  4508. resolutionFound = resolutionFound || !!(levelParsed.width && levelParsed.height);
  4509. videoCodecFound = videoCodecFound || !!levelParsed.videoCodec;
  4510. audioCodecFound = audioCodecFound || !!levelParsed.audioCodec;
  4511. // erase audio codec info if browser does not support mp4a.40.34.
  4512. // demuxer will autodetect codec and fallback to mpeg/audio
  4513. if (chromeOrFirefox && levelParsed.audioCodec && levelParsed.audioCodec.indexOf('mp4a.40.34') !== -1) {
  4514. levelParsed.audioCodec = undefined;
  4515. }
  4516. var levelKey = levelParsed.bitrate + "-" + levelParsed.attrs.RESOLUTION + "-" + levelParsed.attrs.CODECS;
  4517. levelFromSet = levelSet[levelKey];
  4518. if (!levelFromSet) {
  4519. levelFromSet = new _types_level__WEBPACK_IMPORTED_MODULE_0__.Level(levelParsed);
  4520. levelSet[levelKey] = levelFromSet;
  4521. levels.push(levelFromSet);
  4522. } else {
  4523. levelFromSet.url.push(levelParsed.url);
  4524. }
  4525. if (attributes) {
  4526. if (attributes.AUDIO) {
  4527. (0,_level_helper__WEBPACK_IMPORTED_MODULE_4__.addGroupId)(levelFromSet, 'audio', attributes.AUDIO);
  4528. }
  4529. if (attributes.SUBTITLES) {
  4530. (0,_level_helper__WEBPACK_IMPORTED_MODULE_4__.addGroupId)(levelFromSet, 'text', attributes.SUBTITLES);
  4531. }
  4532. }
  4533. });
  4534. // remove audio-only level if we also have levels with video codecs or RESOLUTION signalled
  4535. if ((resolutionFound || videoCodecFound) && audioCodecFound) {
  4536. levels = levels.filter(function (_ref) {
  4537. var videoCodec = _ref.videoCodec,
  4538. width = _ref.width,
  4539. height = _ref.height;
  4540. return !!videoCodec || !!(width && height);
  4541. });
  4542. }
  4543. // only keep levels with supported audio/video codecs
  4544. levels = levels.filter(function (_ref2) {
  4545. var audioCodec = _ref2.audioCodec,
  4546. videoCodec = _ref2.videoCodec;
  4547. return (!audioCodec || (0,_utils_codecs__WEBPACK_IMPORTED_MODULE_3__.isCodecSupportedInMp4)(audioCodec, 'audio')) && (!videoCodec || (0,_utils_codecs__WEBPACK_IMPORTED_MODULE_3__.isCodecSupportedInMp4)(videoCodec, 'video'));
  4548. });
  4549. if (data.audioTracks) {
  4550. audioTracks = data.audioTracks.filter(function (track) {
  4551. return !track.audioCodec || (0,_utils_codecs__WEBPACK_IMPORTED_MODULE_3__.isCodecSupportedInMp4)(track.audioCodec, 'audio');
  4552. });
  4553. // Assign ids after filtering as array indices by group-id
  4554. (0,_level_helper__WEBPACK_IMPORTED_MODULE_4__.assignTrackIdsByGroup)(audioTracks);
  4555. }
  4556. if (data.subtitles) {
  4557. subtitleTracks = data.subtitles;
  4558. (0,_level_helper__WEBPACK_IMPORTED_MODULE_4__.assignTrackIdsByGroup)(subtitleTracks);
  4559. }
  4560. if (levels.length > 0) {
  4561. // start bitrate is the first bitrate of the manifest
  4562. bitrateStart = levels[0].bitrate;
  4563. // sort level on bitrate
  4564. levels.sort(function (a, b) {
  4565. return a.bitrate - b.bitrate;
  4566. });
  4567. this._levels = levels;
  4568. // find index of first level in sorted levels
  4569. for (var i = 0; i < levels.length; i++) {
  4570. if (levels[i].bitrate === bitrateStart) {
  4571. this._firstLevel = i;
  4572. this.log("manifest loaded, " + levels.length + " level(s) found, first bitrate: " + bitrateStart);
  4573. break;
  4574. }
  4575. }
  4576. // Audio is only alternate if manifest include a URI along with the audio group tag,
  4577. // and this is not an audio-only stream where levels contain audio-only
  4578. var audioOnly = audioCodecFound && !videoCodecFound;
  4579. var edata = {
  4580. levels: levels,
  4581. audioTracks: audioTracks,
  4582. subtitleTracks: subtitleTracks,
  4583. firstLevel: this._firstLevel,
  4584. stats: data.stats,
  4585. audio: audioCodecFound,
  4586. video: videoCodecFound,
  4587. altAudio: !audioOnly && audioTracks.some(function (t) {
  4588. return !!t.url;
  4589. })
  4590. };
  4591. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.MANIFEST_PARSED, edata);
  4592. // Initiate loading after all controllers have received MANIFEST_PARSED
  4593. if (this.hls.config.autoStartLoad || this.hls.forceStartLoad) {
  4594. this.hls.startLoad(this.hls.config.startPosition);
  4595. }
  4596. } else {
  4597. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.ERROR, {
  4598. type: _errors__WEBPACK_IMPORTED_MODULE_2__.ErrorTypes.MEDIA_ERROR,
  4599. details: _errors__WEBPACK_IMPORTED_MODULE_2__.ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,
  4600. fatal: true,
  4601. url: data.url,
  4602. reason: 'no level with compatible codecs found in manifest'
  4603. });
  4604. }
  4605. };
  4606. _proto.onError = function onError(event, data) {
  4607. var _data$level;
  4608. _BasePlaylistControll.prototype.onError.call(this, event, data);
  4609. if (data.fatal) {
  4610. return;
  4611. }
  4612. // Switch to redundant level when track fails to load
  4613. var context = data.context;
  4614. var level = this._levels[this.currentLevelIndex];
  4615. if (context && (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistContextType.AUDIO_TRACK && level.audioGroupIds && context.groupId === level.audioGroupIds[level.urlId] || context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistContextType.SUBTITLE_TRACK && level.textGroupIds && context.groupId === level.textGroupIds[level.urlId])) {
  4616. this.redundantFailover(this.currentLevelIndex);
  4617. return;
  4618. }
  4619. var levelError = false;
  4620. var levelSwitch = true;
  4621. var levelIndex;
  4622. // try to recover not fatal errors
  4623. switch (data.details) {
  4624. case _errors__WEBPACK_IMPORTED_MODULE_2__.ErrorDetails.FRAG_LOAD_ERROR:
  4625. case _errors__WEBPACK_IMPORTED_MODULE_2__.ErrorDetails.FRAG_LOAD_TIMEOUT:
  4626. case _errors__WEBPACK_IMPORTED_MODULE_2__.ErrorDetails.KEY_LOAD_ERROR:
  4627. case _errors__WEBPACK_IMPORTED_MODULE_2__.ErrorDetails.KEY_LOAD_TIMEOUT:
  4628. if (data.frag) {
  4629. // Share fragment error count accross media options (main, audio, subs)
  4630. // This allows for level based rendition switching when media option assets fail
  4631. var variantLevelIndex = data.frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistLevelType.MAIN ? data.frag.level : this.currentLevelIndex;
  4632. var _level = this._levels[variantLevelIndex];
  4633. // Set levelIndex when we're out of fragment retries
  4634. if (_level) {
  4635. _level.fragmentError++;
  4636. if (_level.fragmentError > this.hls.config.fragLoadingMaxRetry) {
  4637. levelIndex = variantLevelIndex;
  4638. }
  4639. } else {
  4640. levelIndex = variantLevelIndex;
  4641. }
  4642. }
  4643. break;
  4644. case _errors__WEBPACK_IMPORTED_MODULE_2__.ErrorDetails.LEVEL_LOAD_ERROR:
  4645. case _errors__WEBPACK_IMPORTED_MODULE_2__.ErrorDetails.LEVEL_LOAD_TIMEOUT:
  4646. // Do not perform level switch if an error occurred using delivery directives
  4647. // Attempt to reload level without directives first
  4648. if (context) {
  4649. if (context.deliveryDirectives) {
  4650. levelSwitch = false;
  4651. }
  4652. levelIndex = context.level;
  4653. }
  4654. levelError = true;
  4655. break;
  4656. case _errors__WEBPACK_IMPORTED_MODULE_2__.ErrorDetails.REMUX_ALLOC_ERROR:
  4657. levelIndex = (_data$level = data.level) != null ? _data$level : this.currentLevelIndex;
  4658. levelError = true;
  4659. break;
  4660. }
  4661. if (levelIndex !== undefined) {
  4662. this.recoverLevel(data, levelIndex, levelError, levelSwitch);
  4663. }
  4664. }
  4665. /**
  4666. * Switch to a redundant stream if any available.
  4667. * If redundant stream is not available, emergency switch down if ABR mode is enabled.
  4668. */;
  4669. _proto.recoverLevel = function recoverLevel(errorEvent, levelIndex, levelError, levelSwitch) {
  4670. var errorDetails = errorEvent.details;
  4671. var level = this._levels[levelIndex];
  4672. level.loadError++;
  4673. if (levelError) {
  4674. var retrying = this.retryLoadingOrFail(errorEvent);
  4675. if (retrying) {
  4676. // boolean used to inform stream controller not to switch back to IDLE on non fatal error
  4677. errorEvent.levelRetry = true;
  4678. } else {
  4679. this.currentLevelIndex = -1;
  4680. return;
  4681. }
  4682. }
  4683. if (levelSwitch) {
  4684. var redundantLevels = level.url.length;
  4685. // Try redundant fail-over until level.loadError reaches redundantLevels
  4686. if (redundantLevels > 1 && level.loadError < redundantLevels) {
  4687. errorEvent.levelRetry = true;
  4688. this.redundantFailover(levelIndex);
  4689. } else if (this.manualLevelIndex === -1) {
  4690. // Search for next level to retry
  4691. var nextLevel = -1;
  4692. var levels = this._levels;
  4693. for (var i = levels.length; i--;) {
  4694. var candidate = (i + this.currentLevelIndex) % levels.length;
  4695. if (candidate !== this.currentLevelIndex && levels[candidate].loadError === 0) {
  4696. nextLevel = candidate;
  4697. break;
  4698. }
  4699. }
  4700. if (nextLevel > -1 && this.currentLevelIndex !== nextLevel) {
  4701. this.warn(errorDetails + ": switch to " + nextLevel);
  4702. errorEvent.levelRetry = true;
  4703. this.hls.nextAutoLevel = nextLevel;
  4704. }
  4705. }
  4706. }
  4707. };
  4708. _proto.redundantFailover = function redundantFailover(levelIndex) {
  4709. var level = this._levels[levelIndex];
  4710. var redundantLevels = level.url.length;
  4711. if (redundantLevels > 1) {
  4712. // Update the url id of all levels so that we stay on the same set of variants when level switching
  4713. var newUrlId = (level.urlId + 1) % redundantLevels;
  4714. this.warn("Switching to redundant URL-id " + newUrlId);
  4715. this._levels.forEach(function (level) {
  4716. level.urlId = newUrlId;
  4717. });
  4718. this.level = levelIndex;
  4719. }
  4720. }
  4721. // reset errors on the successful load of a fragment
  4722. ;
  4723. _proto.onFragLoaded = function onFragLoaded(event, _ref3) {
  4724. var frag = _ref3.frag;
  4725. if (frag !== undefined && frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistLevelType.MAIN) {
  4726. var level = this._levels[frag.level];
  4727. if (level !== undefined) {
  4728. level.fragmentError = 0;
  4729. level.loadError = 0;
  4730. }
  4731. }
  4732. };
  4733. _proto.onLevelLoaded = function onLevelLoaded(event, data) {
  4734. var _data$deliveryDirecti2;
  4735. var level = data.level,
  4736. details = data.details;
  4737. var curLevel = this._levels[level];
  4738. if (!curLevel) {
  4739. var _data$deliveryDirecti;
  4740. this.warn("Invalid level index " + level);
  4741. if ((_data$deliveryDirecti = data.deliveryDirectives) !== null && _data$deliveryDirecti !== void 0 && _data$deliveryDirecti.skip) {
  4742. details.deltaUpdateFailed = true;
  4743. }
  4744. return;
  4745. }
  4746. // only process level loaded events matching with expected level
  4747. if (level === this.currentLevelIndex) {
  4748. // reset level load error counter on successful level loaded only if there is no issues with fragments
  4749. if (curLevel.fragmentError === 0) {
  4750. curLevel.loadError = 0;
  4751. this.retryCount = 0;
  4752. }
  4753. this.playlistLoaded(level, data, curLevel.details);
  4754. } else if ((_data$deliveryDirecti2 = data.deliveryDirectives) !== null && _data$deliveryDirecti2 !== void 0 && _data$deliveryDirecti2.skip) {
  4755. // received a delta playlist update that cannot be merged
  4756. details.deltaUpdateFailed = true;
  4757. }
  4758. };
  4759. _proto.onAudioTrackSwitched = function onAudioTrackSwitched(event, data) {
  4760. var currentLevel = this.hls.levels[this.currentLevelIndex];
  4761. if (!currentLevel) {
  4762. return;
  4763. }
  4764. if (currentLevel.audioGroupIds) {
  4765. var urlId = -1;
  4766. var audioGroupId = this.hls.audioTracks[data.id].groupId;
  4767. for (var i = 0; i < currentLevel.audioGroupIds.length; i++) {
  4768. if (currentLevel.audioGroupIds[i] === audioGroupId) {
  4769. urlId = i;
  4770. break;
  4771. }
  4772. }
  4773. if (urlId !== currentLevel.urlId) {
  4774. currentLevel.urlId = urlId;
  4775. this.startLoad();
  4776. }
  4777. }
  4778. };
  4779. _proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {
  4780. _BasePlaylistControll.prototype.loadPlaylist.call(this);
  4781. var level = this.currentLevelIndex;
  4782. var currentLevel = this._levels[level];
  4783. if (this.canLoad && currentLevel && currentLevel.url.length > 0) {
  4784. var id = currentLevel.urlId;
  4785. var url = currentLevel.url[id];
  4786. if (hlsUrlParameters) {
  4787. try {
  4788. url = hlsUrlParameters.addDirectives(url);
  4789. } catch (error) {
  4790. this.warn("Could not construct new URL with HLS Delivery Directives: " + error);
  4791. }
  4792. }
  4793. this.log("Attempt loading level index " + level + (hlsUrlParameters ? ' at sn ' + hlsUrlParameters.msn + ' part ' + hlsUrlParameters.part : '') + " with URL-id " + id + " " + url);
  4794. // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
  4795. // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);
  4796. this.clearTimer();
  4797. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.LEVEL_LOADING, {
  4798. url: url,
  4799. level: level,
  4800. id: id,
  4801. deliveryDirectives: hlsUrlParameters || null
  4802. });
  4803. }
  4804. };
  4805. _proto.removeLevel = function removeLevel(levelIndex, urlId) {
  4806. var filterLevelAndGroupByIdIndex = function filterLevelAndGroupByIdIndex(url, id) {
  4807. return id !== urlId;
  4808. };
  4809. var levels = this._levels.filter(function (level, index) {
  4810. if (index !== levelIndex) {
  4811. return true;
  4812. }
  4813. if (level.url.length > 1 && urlId !== undefined) {
  4814. level.url = level.url.filter(filterLevelAndGroupByIdIndex);
  4815. if (level.audioGroupIds) {
  4816. level.audioGroupIds = level.audioGroupIds.filter(filterLevelAndGroupByIdIndex);
  4817. }
  4818. if (level.textGroupIds) {
  4819. level.textGroupIds = level.textGroupIds.filter(filterLevelAndGroupByIdIndex);
  4820. }
  4821. level.urlId = 0;
  4822. return true;
  4823. }
  4824. return false;
  4825. }).map(function (level, index) {
  4826. var details = level.details;
  4827. if (details !== null && details !== void 0 && details.fragments) {
  4828. details.fragments.forEach(function (fragment) {
  4829. fragment.level = index;
  4830. });
  4831. }
  4832. return level;
  4833. });
  4834. this._levels = levels;
  4835. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.LEVELS_UPDATED, {
  4836. levels: levels
  4837. });
  4838. };
  4839. _createClass(LevelController, [{
  4840. key: "levels",
  4841. get: function get() {
  4842. if (this._levels.length === 0) {
  4843. return null;
  4844. }
  4845. return this._levels;
  4846. }
  4847. }, {
  4848. key: "level",
  4849. get: function get() {
  4850. return this.currentLevelIndex;
  4851. },
  4852. set: function set(newLevel) {
  4853. var _levels$newLevel;
  4854. var levels = this._levels;
  4855. if (levels.length === 0) {
  4856. return;
  4857. }
  4858. if (this.currentLevelIndex === newLevel && (_levels$newLevel = levels[newLevel]) !== null && _levels$newLevel !== void 0 && _levels$newLevel.details) {
  4859. return;
  4860. }
  4861. // check if level idx is valid
  4862. if (newLevel < 0 || newLevel >= levels.length) {
  4863. // invalid level id given, trigger error
  4864. var fatal = newLevel < 0;
  4865. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.ERROR, {
  4866. type: _errors__WEBPACK_IMPORTED_MODULE_2__.ErrorTypes.OTHER_ERROR,
  4867. details: _errors__WEBPACK_IMPORTED_MODULE_2__.ErrorDetails.LEVEL_SWITCH_ERROR,
  4868. level: newLevel,
  4869. fatal: fatal,
  4870. reason: 'invalid level idx'
  4871. });
  4872. if (fatal) {
  4873. return;
  4874. }
  4875. newLevel = Math.min(newLevel, levels.length - 1);
  4876. }
  4877. // stopping live reloading timer if any
  4878. this.clearTimer();
  4879. var lastLevelIndex = this.currentLevelIndex;
  4880. var lastLevel = levels[lastLevelIndex];
  4881. var level = levels[newLevel];
  4882. this.log("switching to level " + newLevel + " from " + lastLevelIndex);
  4883. this.currentLevelIndex = newLevel;
  4884. var levelSwitchingData = _extends({}, level, {
  4885. level: newLevel,
  4886. maxBitrate: level.maxBitrate,
  4887. uri: level.uri,
  4888. urlId: level.urlId
  4889. });
  4890. // @ts-ignore
  4891. delete levelSwitchingData._urlId;
  4892. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.LEVEL_SWITCHING, levelSwitchingData);
  4893. // check if we need to load playlist for this level
  4894. var levelDetails = level.details;
  4895. if (!levelDetails || levelDetails.live) {
  4896. // level not retrieved yet, or live playlist we need to (re)load it
  4897. var hlsUrlParameters = this.switchParams(level.uri, lastLevel === null || lastLevel === void 0 ? void 0 : lastLevel.details);
  4898. this.loadPlaylist(hlsUrlParameters);
  4899. }
  4900. }
  4901. }, {
  4902. key: "manualLevel",
  4903. get: function get() {
  4904. return this.manualLevelIndex;
  4905. },
  4906. set: function set(newLevel) {
  4907. this.manualLevelIndex = newLevel;
  4908. if (this._startLevel === undefined) {
  4909. this._startLevel = newLevel;
  4910. }
  4911. if (newLevel !== -1) {
  4912. this.level = newLevel;
  4913. }
  4914. }
  4915. }, {
  4916. key: "firstLevel",
  4917. get: function get() {
  4918. return this._firstLevel;
  4919. },
  4920. set: function set(newLevel) {
  4921. this._firstLevel = newLevel;
  4922. }
  4923. }, {
  4924. key: "startLevel",
  4925. get: function get() {
  4926. // hls.startLevel takes precedence over config.startLevel
  4927. // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)
  4928. if (this._startLevel === undefined) {
  4929. var configStartLevel = this.hls.config.startLevel;
  4930. if (configStartLevel !== undefined) {
  4931. return configStartLevel;
  4932. } else {
  4933. return this._firstLevel;
  4934. }
  4935. } else {
  4936. return this._startLevel;
  4937. }
  4938. },
  4939. set: function set(newLevel) {
  4940. this._startLevel = newLevel;
  4941. }
  4942. }, {
  4943. key: "nextLoadLevel",
  4944. get: function get() {
  4945. if (this.manualLevelIndex !== -1) {
  4946. return this.manualLevelIndex;
  4947. } else {
  4948. return this.hls.nextAutoLevel;
  4949. }
  4950. },
  4951. set: function set(nextLevel) {
  4952. this.level = nextLevel;
  4953. if (this.manualLevelIndex === -1) {
  4954. this.hls.nextAutoLevel = nextLevel;
  4955. }
  4956. }
  4957. }]);
  4958. return LevelController;
  4959. }(_base_playlist_controller__WEBPACK_IMPORTED_MODULE_5__["default"]);
  4960. /***/ }),
  4961. /***/ "./src/controller/level-helper.ts":
  4962. /*!****************************************!*\
  4963. !*** ./src/controller/level-helper.ts ***!
  4964. \****************************************/
  4965. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  4966. "use strict";
  4967. __webpack_require__.r(__webpack_exports__);
  4968. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  4969. /* harmony export */ "addGroupId": () => (/* binding */ addGroupId),
  4970. /* harmony export */ "addSliding": () => (/* binding */ addSliding),
  4971. /* harmony export */ "adjustSliding": () => (/* binding */ adjustSliding),
  4972. /* harmony export */ "assignTrackIdsByGroup": () => (/* binding */ assignTrackIdsByGroup),
  4973. /* harmony export */ "computeReloadInterval": () => (/* binding */ computeReloadInterval),
  4974. /* harmony export */ "getFragmentWithSN": () => (/* binding */ getFragmentWithSN),
  4975. /* harmony export */ "getPartWith": () => (/* binding */ getPartWith),
  4976. /* harmony export */ "mapFragmentIntersection": () => (/* binding */ mapFragmentIntersection),
  4977. /* harmony export */ "mapPartIntersection": () => (/* binding */ mapPartIntersection),
  4978. /* harmony export */ "mergeDetails": () => (/* binding */ mergeDetails),
  4979. /* harmony export */ "updateFragPTSDTS": () => (/* binding */ updateFragPTSDTS),
  4980. /* harmony export */ "updatePTS": () => (/* binding */ updatePTS)
  4981. /* harmony export */ });
  4982. /* harmony import */ var _Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
  4983. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
  4984. /* harmony import */ var _loader_date_range__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../loader/date-range */ "./src/loader/date-range.ts");
  4985. function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
  4986. /**
  4987. * @module LevelHelper
  4988. * Providing methods dealing with playlist sliding and drift
  4989. * */
  4990. function addGroupId(level, type, id) {
  4991. switch (type) {
  4992. case 'audio':
  4993. if (!level.audioGroupIds) {
  4994. level.audioGroupIds = [];
  4995. }
  4996. level.audioGroupIds.push(id);
  4997. break;
  4998. case 'text':
  4999. if (!level.textGroupIds) {
  5000. level.textGroupIds = [];
  5001. }
  5002. level.textGroupIds.push(id);
  5003. break;
  5004. }
  5005. }
  5006. function assignTrackIdsByGroup(tracks) {
  5007. var groups = {};
  5008. tracks.forEach(function (track) {
  5009. var groupId = track.groupId || '';
  5010. track.id = groups[groupId] = groups[groupId] || 0;
  5011. groups[groupId]++;
  5012. });
  5013. }
  5014. function updatePTS(fragments, fromIdx, toIdx) {
  5015. var fragFrom = fragments[fromIdx];
  5016. var fragTo = fragments[toIdx];
  5017. updateFromToPTS(fragFrom, fragTo);
  5018. }
  5019. function updateFromToPTS(fragFrom, fragTo) {
  5020. var fragToPTS = fragTo.startPTS;
  5021. // if we know startPTS[toIdx]
  5022. if ((0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(fragToPTS)) {
  5023. // update fragment duration.
  5024. // it helps to fix drifts between playlist reported duration and fragment real duration
  5025. var duration = 0;
  5026. var frag;
  5027. if (fragTo.sn > fragFrom.sn) {
  5028. duration = fragToPTS - fragFrom.start;
  5029. frag = fragFrom;
  5030. } else {
  5031. duration = fragFrom.start - fragToPTS;
  5032. frag = fragTo;
  5033. }
  5034. // TODO? Drift can go either way, or the playlist could be completely accurate
  5035. // console.assert(duration > 0,
  5036. // `duration of ${duration} computed for frag ${frag.sn}, level ${frag.level}, there should be some duration drift between playlist and fragment!`);
  5037. if (frag.duration !== duration) {
  5038. frag.duration = duration;
  5039. }
  5040. // we dont know startPTS[toIdx]
  5041. } else if (fragTo.sn > fragFrom.sn) {
  5042. var contiguous = fragFrom.cc === fragTo.cc;
  5043. // TODO: With part-loading end/durations we need to confirm the whole fragment is loaded before using (or setting) minEndPTS
  5044. if (contiguous && fragFrom.minEndPTS) {
  5045. fragTo.start = fragFrom.start + (fragFrom.minEndPTS - fragFrom.start);
  5046. } else {
  5047. fragTo.start = fragFrom.start + fragFrom.duration;
  5048. }
  5049. } else {
  5050. fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);
  5051. }
  5052. }
  5053. function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
  5054. var parsedMediaDuration = endPTS - startPTS;
  5055. if (parsedMediaDuration <= 0) {
  5056. _utils_logger__WEBPACK_IMPORTED_MODULE_1__.logger.warn('Fragment should have a positive duration', frag);
  5057. endPTS = startPTS + frag.duration;
  5058. endDTS = startDTS + frag.duration;
  5059. }
  5060. var maxStartPTS = startPTS;
  5061. var minEndPTS = endPTS;
  5062. var fragStartPts = frag.startPTS;
  5063. var fragEndPts = frag.endPTS;
  5064. if ((0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(fragStartPts)) {
  5065. // delta PTS between audio and video
  5066. var deltaPTS = Math.abs(fragStartPts - startPTS);
  5067. if (!(0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(frag.deltaPTS)) {
  5068. frag.deltaPTS = deltaPTS;
  5069. } else {
  5070. frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
  5071. }
  5072. maxStartPTS = Math.max(startPTS, fragStartPts);
  5073. startPTS = Math.min(startPTS, fragStartPts);
  5074. startDTS = Math.min(startDTS, frag.startDTS);
  5075. minEndPTS = Math.min(endPTS, fragEndPts);
  5076. endPTS = Math.max(endPTS, fragEndPts);
  5077. endDTS = Math.max(endDTS, frag.endDTS);
  5078. }
  5079. frag.duration = endPTS - startPTS;
  5080. var drift = startPTS - frag.start;
  5081. frag.start = frag.startPTS = startPTS;
  5082. frag.maxStartPTS = maxStartPTS;
  5083. frag.startDTS = startDTS;
  5084. frag.endPTS = endPTS;
  5085. frag.minEndPTS = minEndPTS;
  5086. frag.endDTS = endDTS;
  5087. var sn = frag.sn; // 'initSegment'
  5088. // exit if sn out of range
  5089. if (!details || sn < details.startSN || sn > details.endSN) {
  5090. return 0;
  5091. }
  5092. var i;
  5093. var fragIdx = sn - details.startSN;
  5094. var fragments = details.fragments;
  5095. // update frag reference in fragments array
  5096. // rationale is that fragments array might not contain this frag object.
  5097. // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()
  5098. // if we don't update frag, we won't be able to propagate PTS info on the playlist
  5099. // resulting in invalid sliding computation
  5100. fragments[fragIdx] = frag;
  5101. // adjust fragment PTS/duration from seqnum-1 to frag 0
  5102. for (i = fragIdx; i > 0; i--) {
  5103. updateFromToPTS(fragments[i], fragments[i - 1]);
  5104. }
  5105. // adjust fragment PTS/duration from seqnum to last frag
  5106. for (i = fragIdx; i < fragments.length - 1; i++) {
  5107. updateFromToPTS(fragments[i], fragments[i + 1]);
  5108. }
  5109. if (details.fragmentHint) {
  5110. updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint);
  5111. }
  5112. details.PTSKnown = details.alignedSliding = true;
  5113. return drift;
  5114. }
  5115. function mergeDetails(oldDetails, newDetails) {
  5116. // Track the last initSegment processed. Initialize it to the last one on the timeline.
  5117. var currentInitSegment = null;
  5118. var oldFragments = oldDetails.fragments;
  5119. for (var i = oldFragments.length - 1; i >= 0; i--) {
  5120. var oldInit = oldFragments[i].initSegment;
  5121. if (oldInit) {
  5122. currentInitSegment = oldInit;
  5123. break;
  5124. }
  5125. }
  5126. if (oldDetails.fragmentHint) {
  5127. // prevent PTS and duration from being adjusted on the next hint
  5128. delete oldDetails.fragmentHint.endPTS;
  5129. }
  5130. // check if old/new playlists have fragments in common
  5131. // loop through overlapping SN and update startPTS , cc, and duration if any found
  5132. var ccOffset = 0;
  5133. var PTSFrag;
  5134. mapFragmentIntersection(oldDetails, newDetails, function (oldFrag, newFrag) {
  5135. if (oldFrag.relurl) {
  5136. // Do not compare CC if the old fragment has no url. This is a level.fragmentHint used by LL-HLS parts.
  5137. // It maybe be off by 1 if it was created before any parts or discontinuity tags were appended to the end
  5138. // of the playlist.
  5139. ccOffset = oldFrag.cc - newFrag.cc;
  5140. }
  5141. if ((0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(oldFrag.startPTS) && (0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(oldFrag.endPTS)) {
  5142. newFrag.start = newFrag.startPTS = oldFrag.startPTS;
  5143. newFrag.startDTS = oldFrag.startDTS;
  5144. newFrag.appendedPTS = oldFrag.appendedPTS;
  5145. newFrag.maxStartPTS = oldFrag.maxStartPTS;
  5146. newFrag.endPTS = oldFrag.endPTS;
  5147. newFrag.endDTS = oldFrag.endDTS;
  5148. newFrag.minEndPTS = oldFrag.minEndPTS;
  5149. newFrag.duration = oldFrag.endPTS - oldFrag.startPTS;
  5150. if (newFrag.duration) {
  5151. PTSFrag = newFrag;
  5152. }
  5153. // PTS is known when any segment has startPTS and endPTS
  5154. newDetails.PTSKnown = newDetails.alignedSliding = true;
  5155. }
  5156. newFrag.elementaryStreams = oldFrag.elementaryStreams;
  5157. newFrag.loader = oldFrag.loader;
  5158. newFrag.stats = oldFrag.stats;
  5159. newFrag.urlId = oldFrag.urlId;
  5160. if (oldFrag.initSegment) {
  5161. newFrag.initSegment = oldFrag.initSegment;
  5162. currentInitSegment = oldFrag.initSegment;
  5163. }
  5164. });
  5165. if (currentInitSegment) {
  5166. var fragmentsToCheck = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
  5167. fragmentsToCheck.forEach(function (frag) {
  5168. var _currentInitSegment;
  5169. if (!frag.initSegment || frag.initSegment.relurl === ((_currentInitSegment = currentInitSegment) === null || _currentInitSegment === void 0 ? void 0 : _currentInitSegment.relurl)) {
  5170. frag.initSegment = currentInitSegment;
  5171. }
  5172. });
  5173. }
  5174. if (newDetails.skippedSegments) {
  5175. newDetails.deltaUpdateFailed = newDetails.fragments.some(function (frag) {
  5176. return !frag;
  5177. });
  5178. if (newDetails.deltaUpdateFailed) {
  5179. _utils_logger__WEBPACK_IMPORTED_MODULE_1__.logger.warn('[level-helper] Previous playlist missing segments skipped in delta playlist');
  5180. for (var _i = newDetails.skippedSegments; _i--;) {
  5181. newDetails.fragments.shift();
  5182. }
  5183. newDetails.startSN = newDetails.fragments[0].sn;
  5184. newDetails.startCC = newDetails.fragments[0].cc;
  5185. } else if (newDetails.canSkipDateRanges) {
  5186. newDetails.dateRanges = mergeDateRanges(oldDetails.dateRanges, newDetails.dateRanges, newDetails.recentlyRemovedDateranges);
  5187. }
  5188. }
  5189. var newFragments = newDetails.fragments;
  5190. if (ccOffset) {
  5191. _utils_logger__WEBPACK_IMPORTED_MODULE_1__.logger.warn('discontinuity sliding from playlist, take drift into account');
  5192. for (var _i2 = 0; _i2 < newFragments.length; _i2++) {
  5193. newFragments[_i2].cc += ccOffset;
  5194. }
  5195. }
  5196. if (newDetails.skippedSegments) {
  5197. newDetails.startCC = newDetails.fragments[0].cc;
  5198. }
  5199. // Merge parts
  5200. mapPartIntersection(oldDetails.partList, newDetails.partList, function (oldPart, newPart) {
  5201. newPart.elementaryStreams = oldPart.elementaryStreams;
  5202. newPart.stats = oldPart.stats;
  5203. });
  5204. // if at least one fragment contains PTS info, recompute PTS information for all fragments
  5205. if (PTSFrag) {
  5206. updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
  5207. } else {
  5208. // ensure that delta is within oldFragments range
  5209. // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])
  5210. // in that case we also need to adjust start offset of all fragments
  5211. adjustSliding(oldDetails, newDetails);
  5212. }
  5213. if (newFragments.length) {
  5214. newDetails.totalduration = newDetails.edge - newFragments[0].start;
  5215. }
  5216. newDetails.driftStartTime = oldDetails.driftStartTime;
  5217. newDetails.driftStart = oldDetails.driftStart;
  5218. var advancedDateTime = newDetails.advancedDateTime;
  5219. if (newDetails.advanced && advancedDateTime) {
  5220. var edge = newDetails.edge;
  5221. if (!newDetails.driftStart) {
  5222. newDetails.driftStartTime = advancedDateTime;
  5223. newDetails.driftStart = edge;
  5224. }
  5225. newDetails.driftEndTime = advancedDateTime;
  5226. newDetails.driftEnd = edge;
  5227. } else {
  5228. newDetails.driftEndTime = oldDetails.driftEndTime;
  5229. newDetails.driftEnd = oldDetails.driftEnd;
  5230. newDetails.advancedDateTime = oldDetails.advancedDateTime;
  5231. }
  5232. }
  5233. function mergeDateRanges(oldDateRanges, deltaDateRanges, recentlyRemovedDateranges) {
  5234. var dateRanges = _extends({}, oldDateRanges);
  5235. if (recentlyRemovedDateranges) {
  5236. recentlyRemovedDateranges.forEach(function (id) {
  5237. delete dateRanges[id];
  5238. });
  5239. }
  5240. Object.keys(deltaDateRanges).forEach(function (id) {
  5241. var dateRange = new _loader_date_range__WEBPACK_IMPORTED_MODULE_2__.DateRange(deltaDateRanges[id].attr, dateRanges[id]);
  5242. if (dateRange.isValid) {
  5243. dateRanges[id] = dateRange;
  5244. } else {
  5245. _utils_logger__WEBPACK_IMPORTED_MODULE_1__.logger.warn("Ignoring invalid Playlist Delta Update DATERANGE tag: \"" + JSON.stringify(deltaDateRanges[id].attr) + "\"");
  5246. }
  5247. });
  5248. return dateRanges;
  5249. }
  5250. function mapPartIntersection(oldParts, newParts, intersectionFn) {
  5251. if (oldParts && newParts) {
  5252. var delta = 0;
  5253. for (var i = 0, len = oldParts.length; i <= len; i++) {
  5254. var _oldPart = oldParts[i];
  5255. var _newPart = newParts[i + delta];
  5256. if (_oldPart && _newPart && _oldPart.index === _newPart.index && _oldPart.fragment.sn === _newPart.fragment.sn) {
  5257. intersectionFn(_oldPart, _newPart);
  5258. } else {
  5259. delta--;
  5260. }
  5261. }
  5262. }
  5263. }
  5264. function mapFragmentIntersection(oldDetails, newDetails, intersectionFn) {
  5265. var skippedSegments = newDetails.skippedSegments;
  5266. var start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;
  5267. var end = (oldDetails.fragmentHint ? 1 : 0) + (skippedSegments ? newDetails.endSN : Math.min(oldDetails.endSN, newDetails.endSN)) - newDetails.startSN;
  5268. var delta = newDetails.startSN - oldDetails.startSN;
  5269. var newFrags = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
  5270. var oldFrags = oldDetails.fragmentHint ? oldDetails.fragments.concat(oldDetails.fragmentHint) : oldDetails.fragments;
  5271. for (var i = start; i <= end; i++) {
  5272. var _oldFrag = oldFrags[delta + i];
  5273. var _newFrag = newFrags[i];
  5274. if (skippedSegments && !_newFrag && i < skippedSegments) {
  5275. // Fill in skipped segments in delta playlist
  5276. _newFrag = newDetails.fragments[i] = _oldFrag;
  5277. }
  5278. if (_oldFrag && _newFrag) {
  5279. intersectionFn(_oldFrag, _newFrag);
  5280. }
  5281. }
  5282. }
  5283. function adjustSliding(oldDetails, newDetails) {
  5284. var delta = newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN;
  5285. var oldFragments = oldDetails.fragments;
  5286. if (delta < 0 || delta >= oldFragments.length) {
  5287. return;
  5288. }
  5289. addSliding(newDetails, oldFragments[delta].start);
  5290. }
  5291. function addSliding(details, start) {
  5292. if (start) {
  5293. var fragments = details.fragments;
  5294. for (var i = details.skippedSegments; i < fragments.length; i++) {
  5295. fragments[i].start += start;
  5296. }
  5297. if (details.fragmentHint) {
  5298. details.fragmentHint.start += start;
  5299. }
  5300. }
  5301. }
  5302. function computeReloadInterval(newDetails, distanceToLiveEdgeMs) {
  5303. if (distanceToLiveEdgeMs === void 0) {
  5304. distanceToLiveEdgeMs = Infinity;
  5305. }
  5306. var reloadInterval = 1000 * newDetails.targetduration;
  5307. if (newDetails.updated) {
  5308. // Use last segment duration when shorter than target duration and near live edge
  5309. var fragments = newDetails.fragments;
  5310. var liveEdgeMaxTargetDurations = 4;
  5311. if (fragments.length && reloadInterval * liveEdgeMaxTargetDurations > distanceToLiveEdgeMs) {
  5312. var lastSegmentDuration = fragments[fragments.length - 1].duration * 1000;
  5313. if (lastSegmentDuration < reloadInterval) {
  5314. reloadInterval = lastSegmentDuration;
  5315. }
  5316. }
  5317. } else {
  5318. // estimate = 'miss half average';
  5319. // follow HLS Spec, If the client reloads a Playlist file and finds that it has not
  5320. // changed then it MUST wait for a period of one-half the target
  5321. // duration before retrying.
  5322. reloadInterval /= 2;
  5323. }
  5324. return Math.round(reloadInterval);
  5325. }
  5326. function getFragmentWithSN(level, sn, fragCurrent) {
  5327. if (!level || !level.details) {
  5328. return null;
  5329. }
  5330. var levelDetails = level.details;
  5331. var fragment = levelDetails.fragments[sn - levelDetails.startSN];
  5332. if (fragment) {
  5333. return fragment;
  5334. }
  5335. fragment = levelDetails.fragmentHint;
  5336. if (fragment && fragment.sn === sn) {
  5337. return fragment;
  5338. }
  5339. if (sn < levelDetails.startSN && fragCurrent && fragCurrent.sn === sn) {
  5340. return fragCurrent;
  5341. }
  5342. return null;
  5343. }
  5344. function getPartWith(level, sn, partIndex) {
  5345. if (!level || !level.details) {
  5346. return null;
  5347. }
  5348. var partList = level.details.partList;
  5349. if (partList) {
  5350. for (var i = partList.length; i--;) {
  5351. var part = partList[i];
  5352. if (part.index === partIndex && part.fragment.sn === sn) {
  5353. return part;
  5354. }
  5355. }
  5356. }
  5357. return null;
  5358. }
  5359. /***/ }),
  5360. /***/ "./src/controller/stream-controller.ts":
  5361. /*!*********************************************!*\
  5362. !*** ./src/controller/stream-controller.ts ***!
  5363. \*********************************************/
  5364. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  5365. "use strict";
  5366. __webpack_require__.r(__webpack_exports__);
  5367. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  5368. /* harmony export */ "default": () => (/* binding */ StreamController)
  5369. /* harmony export */ });
  5370. /* harmony import */ var _Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
  5371. /* harmony import */ var _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./base-stream-controller */ "./src/controller/base-stream-controller.ts");
  5372. /* harmony import */ var _is_supported__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../is-supported */ "./src/is-supported.ts");
  5373. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../events */ "./src/events.ts");
  5374. /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
  5375. /* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.ts");
  5376. /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
  5377. /* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
  5378. /* harmony import */ var _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../demux/transmuxer-interface */ "./src/demux/transmuxer-interface.ts");
  5379. /* harmony import */ var _types_transmuxer__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../types/transmuxer */ "./src/types/transmuxer.ts");
  5380. /* harmony import */ var _gap_controller__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./gap-controller */ "./src/controller/gap-controller.ts");
  5381. /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
  5382. 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, _toPropertyKey(descriptor.key), descriptor); } }
  5383. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  5384. function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
  5385. function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
  5386. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5387. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5388. var TICK_INTERVAL = 100; // how often to tick in ms
  5389. var StreamController = /*#__PURE__*/function (_BaseStreamController) {
  5390. _inheritsLoose(StreamController, _BaseStreamController);
  5391. function StreamController(hls, fragmentTracker) {
  5392. var _this;
  5393. _this = _BaseStreamController.call(this, hls, fragmentTracker, '[stream-controller]') || this;
  5394. _this.audioCodecSwap = false;
  5395. _this.gapController = null;
  5396. _this.level = -1;
  5397. _this._forceStartLoad = false;
  5398. _this.altAudio = false;
  5399. _this.audioOnly = false;
  5400. _this.fragPlaying = null;
  5401. _this.onvplaying = null;
  5402. _this.onvseeked = null;
  5403. _this.fragLastKbps = 0;
  5404. _this.couldBacktrack = false;
  5405. _this.backtrackFragment = null;
  5406. _this.audioCodecSwitch = false;
  5407. _this.videoBuffer = null;
  5408. _this._registerListeners();
  5409. return _this;
  5410. }
  5411. var _proto = StreamController.prototype;
  5412. _proto._registerListeners = function _registerListeners() {
  5413. var hls = this.hls;
  5414. hls.on(_events__WEBPACK_IMPORTED_MODULE_3__.Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  5415. hls.on(_events__WEBPACK_IMPORTED_MODULE_3__.Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  5416. hls.on(_events__WEBPACK_IMPORTED_MODULE_3__.Events.MANIFEST_LOADING, this.onManifestLoading, this);
  5417. hls.on(_events__WEBPACK_IMPORTED_MODULE_3__.Events.MANIFEST_PARSED, this.onManifestParsed, this);
  5418. hls.on(_events__WEBPACK_IMPORTED_MODULE_3__.Events.LEVEL_LOADING, this.onLevelLoading, this);
  5419. hls.on(_events__WEBPACK_IMPORTED_MODULE_3__.Events.LEVEL_LOADED, this.onLevelLoaded, this);
  5420. hls.on(_events__WEBPACK_IMPORTED_MODULE_3__.Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  5421. hls.on(_events__WEBPACK_IMPORTED_MODULE_3__.Events.ERROR, this.onError, this);
  5422. hls.on(_events__WEBPACK_IMPORTED_MODULE_3__.Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  5423. hls.on(_events__WEBPACK_IMPORTED_MODULE_3__.Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  5424. hls.on(_events__WEBPACK_IMPORTED_MODULE_3__.Events.BUFFER_CREATED, this.onBufferCreated, this);
  5425. hls.on(_events__WEBPACK_IMPORTED_MODULE_3__.Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  5426. hls.on(_events__WEBPACK_IMPORTED_MODULE_3__.Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  5427. hls.on(_events__WEBPACK_IMPORTED_MODULE_3__.Events.FRAG_BUFFERED, this.onFragBuffered, this);
  5428. };
  5429. _proto._unregisterListeners = function _unregisterListeners() {
  5430. var hls = this.hls;
  5431. hls.off(_events__WEBPACK_IMPORTED_MODULE_3__.Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  5432. hls.off(_events__WEBPACK_IMPORTED_MODULE_3__.Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  5433. hls.off(_events__WEBPACK_IMPORTED_MODULE_3__.Events.MANIFEST_LOADING, this.onManifestLoading, this);
  5434. hls.off(_events__WEBPACK_IMPORTED_MODULE_3__.Events.MANIFEST_PARSED, this.onManifestParsed, this);
  5435. hls.off(_events__WEBPACK_IMPORTED_MODULE_3__.Events.LEVEL_LOADED, this.onLevelLoaded, this);
  5436. hls.off(_events__WEBPACK_IMPORTED_MODULE_3__.Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  5437. hls.off(_events__WEBPACK_IMPORTED_MODULE_3__.Events.ERROR, this.onError, this);
  5438. hls.off(_events__WEBPACK_IMPORTED_MODULE_3__.Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  5439. hls.off(_events__WEBPACK_IMPORTED_MODULE_3__.Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  5440. hls.off(_events__WEBPACK_IMPORTED_MODULE_3__.Events.BUFFER_CREATED, this.onBufferCreated, this);
  5441. hls.off(_events__WEBPACK_IMPORTED_MODULE_3__.Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  5442. hls.off(_events__WEBPACK_IMPORTED_MODULE_3__.Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  5443. hls.off(_events__WEBPACK_IMPORTED_MODULE_3__.Events.FRAG_BUFFERED, this.onFragBuffered, this);
  5444. };
  5445. _proto.onHandlerDestroying = function onHandlerDestroying() {
  5446. this._unregisterListeners();
  5447. this.onMediaDetaching();
  5448. };
  5449. _proto.startLoad = function startLoad(startPosition) {
  5450. if (this.levels) {
  5451. var lastCurrentTime = this.lastCurrentTime,
  5452. hls = this.hls;
  5453. this.stopLoad();
  5454. this.setInterval(TICK_INTERVAL);
  5455. this.level = -1;
  5456. this.fragLoadError = 0;
  5457. if (!this.startFragRequested) {
  5458. // determine load level
  5459. var startLevel = hls.startLevel;
  5460. if (startLevel === -1) {
  5461. if (hls.config.testBandwidth && this.levels.length > 1) {
  5462. // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
  5463. startLevel = 0;
  5464. this.bitrateTest = true;
  5465. } else {
  5466. startLevel = hls.nextAutoLevel;
  5467. }
  5468. }
  5469. // set new level to playlist loader : this will trigger start level load
  5470. // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
  5471. this.level = hls.nextLoadLevel = startLevel;
  5472. this.loadedmetadata = false;
  5473. }
  5474. // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime
  5475. if (lastCurrentTime > 0 && startPosition === -1) {
  5476. this.log("Override startPosition with lastCurrentTime @" + lastCurrentTime.toFixed(3));
  5477. startPosition = lastCurrentTime;
  5478. }
  5479. this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.IDLE;
  5480. this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
  5481. this.tick();
  5482. } else {
  5483. this._forceStartLoad = true;
  5484. this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.STOPPED;
  5485. }
  5486. };
  5487. _proto.stopLoad = function stopLoad() {
  5488. this._forceStartLoad = false;
  5489. _BaseStreamController.prototype.stopLoad.call(this);
  5490. };
  5491. _proto.doTick = function doTick() {
  5492. switch (this.state) {
  5493. case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.IDLE:
  5494. this.doTickIdle();
  5495. break;
  5496. case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.WAITING_LEVEL:
  5497. {
  5498. var _levels$level;
  5499. var levels = this.levels,
  5500. level = this.level;
  5501. var details = levels === null || levels === void 0 ? void 0 : (_levels$level = levels[level]) === null || _levels$level === void 0 ? void 0 : _levels$level.details;
  5502. if (details && (!details.live || this.levelLastLoaded === this.level)) {
  5503. if (this.waitForCdnTuneIn(details)) {
  5504. break;
  5505. }
  5506. this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.IDLE;
  5507. break;
  5508. }
  5509. break;
  5510. }
  5511. case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.FRAG_LOADING_WAITING_RETRY:
  5512. {
  5513. var _this$media;
  5514. var now = self.performance.now();
  5515. var retryDate = this.retryDate;
  5516. // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  5517. if (!retryDate || now >= retryDate || (_this$media = this.media) !== null && _this$media !== void 0 && _this$media.seeking) {
  5518. this.log('retryDate reached, switch back to IDLE state');
  5519. this.resetStartWhenNotLoaded(this.level);
  5520. this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.IDLE;
  5521. }
  5522. }
  5523. break;
  5524. default:
  5525. break;
  5526. }
  5527. // check buffer
  5528. // check/update current fragment
  5529. this.onTickEnd();
  5530. };
  5531. _proto.onTickEnd = function onTickEnd() {
  5532. _BaseStreamController.prototype.onTickEnd.call(this);
  5533. this.checkBuffer();
  5534. this.checkFragmentChanged();
  5535. };
  5536. _proto.doTickIdle = function doTickIdle() {
  5537. var hls = this.hls,
  5538. levelLastLoaded = this.levelLastLoaded,
  5539. levels = this.levels,
  5540. media = this.media;
  5541. var config = hls.config,
  5542. level = hls.nextLoadLevel;
  5543. // if start level not parsed yet OR
  5544. // if video not attached AND start fragment already requested OR start frag prefetch not enabled
  5545. // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment
  5546. if (levelLastLoaded === null || !media && (this.startFragRequested || !config.startFragPrefetch)) {
  5547. return;
  5548. }
  5549. // If the "main" level is audio-only but we are loading an alternate track in the same group, do not load anything
  5550. if (this.altAudio && this.audioOnly) {
  5551. return;
  5552. }
  5553. if (!levels || !levels[level]) {
  5554. return;
  5555. }
  5556. var levelInfo = levels[level];
  5557. // if buffer length is less than maxBufLen try to load a new fragment
  5558. // set next load level : this will trigger a playlist load if needed
  5559. this.level = hls.nextLoadLevel = level;
  5560. var levelDetails = levelInfo.details;
  5561. // if level info not retrieved yet, switch state and wait for level retrieval
  5562. // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
  5563. // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
  5564. if (!levelDetails || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.WAITING_LEVEL || levelDetails.live && this.levelLastLoaded !== level) {
  5565. this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.WAITING_LEVEL;
  5566. return;
  5567. }
  5568. var bufferInfo = this.getMainFwdBufferInfo();
  5569. if (bufferInfo === null) {
  5570. return;
  5571. }
  5572. var bufferLen = bufferInfo.len;
  5573. // compute max Buffer Length that we could get from this load level, based on level bitrate. don't buffer more than 60 MB and more than 30s
  5574. var maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate);
  5575. // Stay idle if we are still with buffer margins
  5576. if (bufferLen >= maxBufLen) {
  5577. return;
  5578. }
  5579. if (this._streamEnded(bufferInfo, levelDetails)) {
  5580. var data = {};
  5581. if (this.altAudio) {
  5582. data.type = 'video';
  5583. }
  5584. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__.Events.BUFFER_EOS, data);
  5585. this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.ENDED;
  5586. return;
  5587. }
  5588. if (this.backtrackFragment && this.backtrackFragment.start > bufferInfo.end) {
  5589. this.backtrackFragment = null;
  5590. }
  5591. var targetBufferTime = this.backtrackFragment ? this.backtrackFragment.start : bufferInfo.end;
  5592. var frag = this.getNextFragment(targetBufferTime, levelDetails);
  5593. // Avoid backtracking by loading an earlier segment in streams with segments that do not start with a key frame (flagged by `couldBacktrack`)
  5594. if (this.couldBacktrack && !this.fragPrevious && frag && frag.sn !== 'initSegment' && this.fragmentTracker.getState(frag) !== _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__.FragmentState.OK) {
  5595. var _this$backtrackFragme;
  5596. var backtrackSn = ((_this$backtrackFragme = this.backtrackFragment) != null ? _this$backtrackFragme : frag).sn;
  5597. var fragIdx = backtrackSn - levelDetails.startSN;
  5598. var backtrackFrag = levelDetails.fragments[fragIdx - 1];
  5599. if (backtrackFrag && frag.cc === backtrackFrag.cc) {
  5600. frag = backtrackFrag;
  5601. this.fragmentTracker.removeFragment(backtrackFrag);
  5602. }
  5603. } else if (this.backtrackFragment && bufferInfo.len) {
  5604. this.backtrackFragment = null;
  5605. }
  5606. // Avoid loop loading by using nextLoadPosition set for backtracking
  5607. if (frag && this.fragmentTracker.getState(frag) === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__.FragmentState.OK && this.nextLoadPosition > targetBufferTime) {
  5608. // Cleanup the fragment tracker before trying to find the next unbuffered fragment
  5609. var type = this.audioOnly && !this.altAudio ? _loader_fragment__WEBPACK_IMPORTED_MODULE_7__.ElementaryStreamTypes.AUDIO : _loader_fragment__WEBPACK_IMPORTED_MODULE_7__.ElementaryStreamTypes.VIDEO;
  5610. if (media) {
  5611. this.afterBufferFlushed(media, type, _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistLevelType.MAIN);
  5612. }
  5613. frag = this.getNextFragment(this.nextLoadPosition, levelDetails);
  5614. }
  5615. if (!frag) {
  5616. return;
  5617. }
  5618. if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) {
  5619. frag = frag.initSegment;
  5620. }
  5621. this.loadFragment(frag, levelDetails, targetBufferTime);
  5622. };
  5623. _proto.loadFragment = function loadFragment(frag, levelDetails, targetBufferTime) {
  5624. var _this$media2;
  5625. // Check if fragment is not loaded
  5626. var fragState = this.fragmentTracker.getState(frag);
  5627. this.fragCurrent = frag;
  5628. if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__.FragmentState.NOT_LOADED) {
  5629. if (frag.sn === 'initSegment') {
  5630. this._loadInitSegment(frag, levelDetails);
  5631. } else if (this.bitrateTest) {
  5632. this.log("Fragment " + frag.sn + " of level " + frag.level + " is being downloaded to test bitrate and will not be buffered");
  5633. this._loadBitrateTestFrag(frag, levelDetails);
  5634. } else {
  5635. this.startFragRequested = true;
  5636. _BaseStreamController.prototype.loadFragment.call(this, frag, levelDetails, targetBufferTime);
  5637. }
  5638. } else if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__.FragmentState.APPENDING) {
  5639. // Lower the buffer size and try again
  5640. if (this.reduceMaxBufferLength(frag.duration)) {
  5641. this.fragmentTracker.removeFragment(frag);
  5642. }
  5643. } else if (((_this$media2 = this.media) === null || _this$media2 === void 0 ? void 0 : _this$media2.buffered.length) === 0) {
  5644. // Stop gap for bad tracker / buffer flush behavior
  5645. this.fragmentTracker.removeAllFragments();
  5646. }
  5647. };
  5648. _proto.getAppendedFrag = function getAppendedFrag(position) {
  5649. var fragOrPart = this.fragmentTracker.getAppendedFrag(position, _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistLevelType.MAIN);
  5650. if (fragOrPart && 'fragment' in fragOrPart) {
  5651. return fragOrPart.fragment;
  5652. }
  5653. return fragOrPart;
  5654. };
  5655. _proto.getBufferedFrag = function getBufferedFrag(position) {
  5656. return this.fragmentTracker.getBufferedFrag(position, _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistLevelType.MAIN);
  5657. };
  5658. _proto.followingBufferedFrag = function followingBufferedFrag(frag) {
  5659. if (frag) {
  5660. // try to get range of next fragment (500ms after this range)
  5661. return this.getBufferedFrag(frag.end + 0.5);
  5662. }
  5663. return null;
  5664. }
  5665. /*
  5666. on immediate level switch :
  5667. - pause playback if playing
  5668. - cancel any pending load request
  5669. - and trigger a buffer flush
  5670. */;
  5671. _proto.immediateLevelSwitch = function immediateLevelSwitch() {
  5672. this.abortCurrentFrag();
  5673. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  5674. }
  5675. /**
  5676. * try to switch ASAP without breaking video playback:
  5677. * in order to ensure smooth but quick level switching,
  5678. * we need to find the next flushable buffer range
  5679. * we should take into account new segment fetch time
  5680. */;
  5681. _proto.nextLevelSwitch = function nextLevelSwitch() {
  5682. var levels = this.levels,
  5683. media = this.media;
  5684. // ensure that media is defined and that metadata are available (to retrieve currentTime)
  5685. if (media !== null && media !== void 0 && media.readyState) {
  5686. var fetchdelay;
  5687. var fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
  5688. if (fragPlayingCurrent && fragPlayingCurrent.start > 1) {
  5689. // flush buffer preceding current fragment (flush until current fragment start offset)
  5690. // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
  5691. this.flushMainBuffer(0, fragPlayingCurrent.start - 1);
  5692. }
  5693. if (!media.paused && levels) {
  5694. // add a safety delay of 1s
  5695. var nextLevelId = this.hls.nextLoadLevel;
  5696. var nextLevel = levels[nextLevelId];
  5697. var fragLastKbps = this.fragLastKbps;
  5698. if (fragLastKbps && this.fragCurrent) {
  5699. fetchdelay = this.fragCurrent.duration * nextLevel.maxBitrate / (1000 * fragLastKbps) + 1;
  5700. } else {
  5701. fetchdelay = 0;
  5702. }
  5703. } else {
  5704. fetchdelay = 0;
  5705. }
  5706. // this.log('fetchdelay:'+fetchdelay);
  5707. // find buffer range that will be reached once new fragment will be fetched
  5708. var bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
  5709. if (bufferedFrag) {
  5710. // we can flush buffer range following this one without stalling playback
  5711. var nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);
  5712. if (nextBufferedFrag) {
  5713. // if we are here, we can also cancel any loading/demuxing in progress, as they are useless
  5714. this.abortCurrentFrag();
  5715. // start flush position is in next buffered frag. Leave some padding for non-independent segments and smoother playback.
  5716. var maxStart = nextBufferedFrag.maxStartPTS ? nextBufferedFrag.maxStartPTS : nextBufferedFrag.start;
  5717. var fragDuration = nextBufferedFrag.duration;
  5718. var startPts = Math.max(bufferedFrag.end, maxStart + Math.min(Math.max(fragDuration - this.config.maxFragLookUpTolerance, fragDuration * 0.5), fragDuration * 0.75));
  5719. this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);
  5720. }
  5721. }
  5722. }
  5723. };
  5724. _proto.abortCurrentFrag = function abortCurrentFrag() {
  5725. var fragCurrent = this.fragCurrent;
  5726. this.fragCurrent = null;
  5727. this.backtrackFragment = null;
  5728. if (fragCurrent) {
  5729. fragCurrent.abortRequests();
  5730. }
  5731. switch (this.state) {
  5732. case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.KEY_LOADING:
  5733. case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.FRAG_LOADING:
  5734. case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.FRAG_LOADING_WAITING_RETRY:
  5735. case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.PARSING:
  5736. case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.PARSED:
  5737. this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.IDLE;
  5738. break;
  5739. }
  5740. this.nextLoadPosition = this.getLoadPosition();
  5741. };
  5742. _proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset) {
  5743. _BaseStreamController.prototype.flushMainBuffer.call(this, startOffset, endOffset, this.altAudio ? 'video' : null);
  5744. };
  5745. _proto.onMediaAttached = function onMediaAttached(event, data) {
  5746. _BaseStreamController.prototype.onMediaAttached.call(this, event, data);
  5747. var media = data.media;
  5748. this.onvplaying = this.onMediaPlaying.bind(this);
  5749. this.onvseeked = this.onMediaSeeked.bind(this);
  5750. media.addEventListener('playing', this.onvplaying);
  5751. media.addEventListener('seeked', this.onvseeked);
  5752. this.gapController = new _gap_controller__WEBPACK_IMPORTED_MODULE_10__["default"](this.config, media, this.fragmentTracker, this.hls);
  5753. };
  5754. _proto.onMediaDetaching = function onMediaDetaching() {
  5755. var media = this.media;
  5756. if (media && this.onvplaying && this.onvseeked) {
  5757. media.removeEventListener('playing', this.onvplaying);
  5758. media.removeEventListener('seeked', this.onvseeked);
  5759. this.onvplaying = this.onvseeked = null;
  5760. this.videoBuffer = null;
  5761. }
  5762. this.fragPlaying = null;
  5763. if (this.gapController) {
  5764. this.gapController.destroy();
  5765. this.gapController = null;
  5766. }
  5767. _BaseStreamController.prototype.onMediaDetaching.call(this);
  5768. };
  5769. _proto.onMediaPlaying = function onMediaPlaying() {
  5770. // tick to speed up FRAG_CHANGED triggering
  5771. this.tick();
  5772. };
  5773. _proto.onMediaSeeked = function onMediaSeeked() {
  5774. var media = this.media;
  5775. var currentTime = media ? media.currentTime : null;
  5776. if ((0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(currentTime)) {
  5777. this.log("Media seeked to " + currentTime.toFixed(3));
  5778. }
  5779. // tick to speed up FRAG_CHANGED triggering
  5780. this.tick();
  5781. };
  5782. _proto.onManifestLoading = function onManifestLoading() {
  5783. // reset buffer on manifest loading
  5784. this.log('Trigger BUFFER_RESET');
  5785. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__.Events.BUFFER_RESET, undefined);
  5786. this.fragmentTracker.removeAllFragments();
  5787. this.couldBacktrack = false;
  5788. this.startPosition = this.lastCurrentTime = 0;
  5789. this.fragPlaying = null;
  5790. this.backtrackFragment = null;
  5791. };
  5792. _proto.onManifestParsed = function onManifestParsed(event, data) {
  5793. var aac = false;
  5794. var heaac = false;
  5795. var codec;
  5796. data.levels.forEach(function (level) {
  5797. // detect if we have different kind of audio codecs used amongst playlists
  5798. codec = level.audioCodec;
  5799. if (codec) {
  5800. if (codec.indexOf('mp4a.40.2') !== -1) {
  5801. aac = true;
  5802. }
  5803. if (codec.indexOf('mp4a.40.5') !== -1) {
  5804. heaac = true;
  5805. }
  5806. }
  5807. });
  5808. this.audioCodecSwitch = aac && heaac && !(0,_is_supported__WEBPACK_IMPORTED_MODULE_2__.changeTypeSupported)();
  5809. if (this.audioCodecSwitch) {
  5810. this.log('Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
  5811. }
  5812. this.levels = data.levels;
  5813. this.startFragRequested = false;
  5814. };
  5815. _proto.onLevelLoading = function onLevelLoading(event, data) {
  5816. var levels = this.levels;
  5817. if (!levels || this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.IDLE) {
  5818. return;
  5819. }
  5820. var level = levels[data.level];
  5821. if (!level.details || level.details.live && this.levelLastLoaded !== data.level || this.waitForCdnTuneIn(level.details)) {
  5822. this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.WAITING_LEVEL;
  5823. }
  5824. };
  5825. _proto.onLevelLoaded = function onLevelLoaded(event, data) {
  5826. var _curLevel$details;
  5827. var levels = this.levels;
  5828. var newLevelId = data.level;
  5829. var newDetails = data.details;
  5830. var duration = newDetails.totalduration;
  5831. if (!levels) {
  5832. this.warn("Levels were reset while loading level " + newLevelId);
  5833. return;
  5834. }
  5835. this.log("Level " + newLevelId + " loaded [" + newDetails.startSN + "," + newDetails.endSN + "], cc [" + newDetails.startCC + ", " + newDetails.endCC + "] duration:" + duration);
  5836. var fragCurrent = this.fragCurrent;
  5837. if (fragCurrent && (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.FRAG_LOADING || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.FRAG_LOADING_WAITING_RETRY)) {
  5838. if (fragCurrent.level !== data.level && fragCurrent.loader) {
  5839. this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.IDLE;
  5840. this.backtrackFragment = null;
  5841. fragCurrent.abortRequests();
  5842. }
  5843. }
  5844. var curLevel = levels[newLevelId];
  5845. var sliding = 0;
  5846. if (newDetails.live || (_curLevel$details = curLevel.details) !== null && _curLevel$details !== void 0 && _curLevel$details.live) {
  5847. if (!newDetails.fragments[0]) {
  5848. newDetails.deltaUpdateFailed = true;
  5849. }
  5850. if (newDetails.deltaUpdateFailed) {
  5851. return;
  5852. }
  5853. sliding = this.alignPlaylists(newDetails, curLevel.details);
  5854. }
  5855. // override level info
  5856. curLevel.details = newDetails;
  5857. this.levelLastLoaded = newLevelId;
  5858. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__.Events.LEVEL_UPDATED, {
  5859. details: newDetails,
  5860. level: newLevelId
  5861. });
  5862. // only switch back to IDLE state if we were waiting for level to start downloading a new fragment
  5863. if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.WAITING_LEVEL) {
  5864. if (this.waitForCdnTuneIn(newDetails)) {
  5865. // Wait for Low-Latency CDN Tune-in
  5866. return;
  5867. }
  5868. this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.IDLE;
  5869. }
  5870. if (!this.startFragRequested) {
  5871. this.setStartPosition(newDetails, sliding);
  5872. } else if (newDetails.live) {
  5873. this.synchronizeToLiveEdge(newDetails);
  5874. }
  5875. // trigger handler right now
  5876. this.tick();
  5877. };
  5878. _proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(data) {
  5879. var _frag$initSegment;
  5880. var frag = data.frag,
  5881. part = data.part,
  5882. payload = data.payload;
  5883. var levels = this.levels;
  5884. if (!levels) {
  5885. this.warn("Levels were reset while fragment load was in progress. Fragment " + frag.sn + " of level " + frag.level + " will not be buffered");
  5886. return;
  5887. }
  5888. var currentLevel = levels[frag.level];
  5889. var details = currentLevel.details;
  5890. if (!details) {
  5891. this.warn("Dropping fragment " + frag.sn + " of level " + frag.level + " after level details were reset");
  5892. return;
  5893. }
  5894. var videoCodec = currentLevel.videoCodec;
  5895. // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
  5896. var accurateTimeOffset = details.PTSKnown || !details.live;
  5897. var initSegmentData = (_frag$initSegment = frag.initSegment) === null || _frag$initSegment === void 0 ? void 0 : _frag$initSegment.data;
  5898. var audioCodec = this._getAudioCodec(currentLevel);
  5899. // transmux the MPEG-TS data to ISO-BMFF segments
  5900. // this.log(`Transmuxing ${frag.sn} of [${details.startSN} ,${details.endSN}],level ${frag.level}, cc ${frag.cc}`);
  5901. var transmuxer = this.transmuxer = this.transmuxer || new _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_8__["default"](this.hls, _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistLevelType.MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
  5902. var partIndex = part ? part.index : -1;
  5903. var partial = partIndex !== -1;
  5904. var chunkMeta = new _types_transmuxer__WEBPACK_IMPORTED_MODULE_9__.ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
  5905. var initPTS = this.initPTS[frag.cc];
  5906. transmuxer.push(payload, initSegmentData, audioCodec, videoCodec, frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
  5907. };
  5908. _proto.onAudioTrackSwitching = function onAudioTrackSwitching(event, data) {
  5909. // if any URL found on new audio track, it is an alternate audio track
  5910. var fromAltAudio = this.altAudio;
  5911. var altAudio = !!data.url;
  5912. var trackId = data.id;
  5913. // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered
  5914. // don't do anything if we switch to alt audio: audio stream controller is handling it.
  5915. // we will just have to change buffer scheduling on audioTrackSwitched
  5916. if (!altAudio) {
  5917. if (this.mediaBuffer !== this.media) {
  5918. this.log('Switching on main audio, use media.buffered to schedule main fragment loading');
  5919. this.mediaBuffer = this.media;
  5920. var fragCurrent = this.fragCurrent;
  5921. // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch
  5922. if (fragCurrent) {
  5923. this.log('Switching to main audio track, cancel main fragment load');
  5924. fragCurrent.abortRequests();
  5925. }
  5926. // destroy transmuxer to force init segment generation (following audio switch)
  5927. this.resetTransmuxer();
  5928. // switch to IDLE state to load new fragment
  5929. this.resetLoadingState();
  5930. } else if (this.audioOnly) {
  5931. // Reset audio transmuxer so when switching back to main audio we're not still appending where we left off
  5932. this.resetTransmuxer();
  5933. }
  5934. var hls = this.hls;
  5935. // If switching from alt to main audio, flush all audio and trigger track switched
  5936. if (fromAltAudio) {
  5937. hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__.Events.BUFFER_FLUSHING, {
  5938. startOffset: 0,
  5939. endOffset: Number.POSITIVE_INFINITY,
  5940. type: 'audio'
  5941. });
  5942. }
  5943. hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__.Events.AUDIO_TRACK_SWITCHED, {
  5944. id: trackId
  5945. });
  5946. }
  5947. };
  5948. _proto.onAudioTrackSwitched = function onAudioTrackSwitched(event, data) {
  5949. var trackId = data.id;
  5950. var altAudio = !!this.hls.audioTracks[trackId].url;
  5951. if (altAudio) {
  5952. var videoBuffer = this.videoBuffer;
  5953. // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered
  5954. if (videoBuffer && this.mediaBuffer !== videoBuffer) {
  5955. this.log('Switching on alternate audio, use video.buffered to schedule main fragment loading');
  5956. this.mediaBuffer = videoBuffer;
  5957. }
  5958. }
  5959. this.altAudio = altAudio;
  5960. this.tick();
  5961. };
  5962. _proto.onBufferCreated = function onBufferCreated(event, data) {
  5963. var tracks = data.tracks;
  5964. var mediaTrack;
  5965. var name;
  5966. var alternate = false;
  5967. for (var type in tracks) {
  5968. var track = tracks[type];
  5969. if (track.id === 'main') {
  5970. name = type;
  5971. mediaTrack = track;
  5972. // keep video source buffer reference
  5973. if (type === 'video') {
  5974. var videoTrack = tracks[type];
  5975. if (videoTrack) {
  5976. this.videoBuffer = videoTrack.buffer;
  5977. }
  5978. }
  5979. } else {
  5980. alternate = true;
  5981. }
  5982. }
  5983. if (alternate && mediaTrack) {
  5984. this.log("Alternate track found, use " + name + ".buffered to schedule main fragment loading");
  5985. this.mediaBuffer = mediaTrack.buffer;
  5986. } else {
  5987. this.mediaBuffer = this.media;
  5988. }
  5989. };
  5990. _proto.onFragBuffered = function onFragBuffered(event, data) {
  5991. var frag = data.frag,
  5992. part = data.part;
  5993. if (frag && frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistLevelType.MAIN) {
  5994. return;
  5995. }
  5996. if (this.fragContextChanged(frag)) {
  5997. // If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion
  5998. // Avoid setting state back to IDLE, since that will interfere with a level switch
  5999. this.warn("Fragment " + frag.sn + (part ? ' p: ' + part.index : '') + " of level " + frag.level + " finished buffering, but was aborted. state: " + this.state);
  6000. if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.PARSED) {
  6001. this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.IDLE;
  6002. }
  6003. return;
  6004. }
  6005. var stats = part ? part.stats : frag.stats;
  6006. this.fragLastKbps = Math.round(8 * stats.total / (stats.buffering.end - stats.loading.first));
  6007. if (frag.sn !== 'initSegment') {
  6008. this.fragPrevious = frag;
  6009. }
  6010. this.fragBufferedComplete(frag, part);
  6011. };
  6012. _proto.onError = function onError(event, data) {
  6013. switch (data.details) {
  6014. case _errors__WEBPACK_IMPORTED_MODULE_11__.ErrorDetails.FRAG_LOAD_ERROR:
  6015. case _errors__WEBPACK_IMPORTED_MODULE_11__.ErrorDetails.FRAG_LOAD_TIMEOUT:
  6016. case _errors__WEBPACK_IMPORTED_MODULE_11__.ErrorDetails.KEY_LOAD_ERROR:
  6017. case _errors__WEBPACK_IMPORTED_MODULE_11__.ErrorDetails.KEY_LOAD_TIMEOUT:
  6018. this.onFragmentOrKeyLoadError(_types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistLevelType.MAIN, data);
  6019. break;
  6020. case _errors__WEBPACK_IMPORTED_MODULE_11__.ErrorDetails.LEVEL_LOAD_ERROR:
  6021. case _errors__WEBPACK_IMPORTED_MODULE_11__.ErrorDetails.LEVEL_LOAD_TIMEOUT:
  6022. if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.ERROR) {
  6023. if (data.fatal) {
  6024. // if fatal error, stop processing
  6025. this.warn("" + data.details);
  6026. this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.ERROR;
  6027. } else {
  6028. // in case of non fatal error while loading level, if level controller is not retrying to load level , switch back to IDLE
  6029. if (!data.levelRetry && this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.WAITING_LEVEL) {
  6030. this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.IDLE;
  6031. }
  6032. }
  6033. }
  6034. break;
  6035. case _errors__WEBPACK_IMPORTED_MODULE_11__.ErrorDetails.BUFFER_FULL_ERROR:
  6036. // if in appending state
  6037. if (data.parent === 'main' && (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.PARSING || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.PARSED)) {
  6038. var flushBuffer = true;
  6039. var bufferedInfo = this.getFwdBufferInfo(this.media, _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistLevelType.MAIN);
  6040. // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
  6041. // reduce max buf len if current position is buffered
  6042. if (bufferedInfo && bufferedInfo.len > 0.5) {
  6043. flushBuffer = !this.reduceMaxBufferLength(bufferedInfo.len);
  6044. }
  6045. if (flushBuffer) {
  6046. // current position is not buffered, but browser is still complaining about buffer full error
  6047. // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
  6048. // in that case flush the whole buffer to recover
  6049. this.warn('buffer full error also media.currentTime is not buffered, flush main');
  6050. // flush main buffer
  6051. this.immediateLevelSwitch();
  6052. }
  6053. this.resetLoadingState();
  6054. }
  6055. break;
  6056. default:
  6057. break;
  6058. }
  6059. }
  6060. // Checks the health of the buffer and attempts to resolve playback stalls.
  6061. ;
  6062. _proto.checkBuffer = function checkBuffer() {
  6063. var media = this.media,
  6064. gapController = this.gapController;
  6065. if (!media || !gapController || !media.readyState) {
  6066. // Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)
  6067. return;
  6068. }
  6069. if (this.loadedmetadata || !_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__.BufferHelper.getBuffered(media).length) {
  6070. // Resolve gaps using the main buffer, whose ranges are the intersections of the A/V sourcebuffers
  6071. var activeFrag = this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.IDLE ? this.fragCurrent : null;
  6072. gapController.poll(this.lastCurrentTime, activeFrag);
  6073. }
  6074. this.lastCurrentTime = media.currentTime;
  6075. };
  6076. _proto.onFragLoadEmergencyAborted = function onFragLoadEmergencyAborted() {
  6077. this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.IDLE;
  6078. // if loadedmetadata is not set, it means that we are emergency switch down on first frag
  6079. // in that case, reset startFragRequested flag
  6080. if (!this.loadedmetadata) {
  6081. this.startFragRequested = false;
  6082. this.nextLoadPosition = this.startPosition;
  6083. }
  6084. this.tickImmediate();
  6085. };
  6086. _proto.onBufferFlushed = function onBufferFlushed(event, _ref) {
  6087. var type = _ref.type;
  6088. if (type !== _loader_fragment__WEBPACK_IMPORTED_MODULE_7__.ElementaryStreamTypes.AUDIO || this.audioOnly && !this.altAudio) {
  6089. var media = (type === _loader_fragment__WEBPACK_IMPORTED_MODULE_7__.ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  6090. this.afterBufferFlushed(media, type, _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistLevelType.MAIN);
  6091. }
  6092. };
  6093. _proto.onLevelsUpdated = function onLevelsUpdated(event, data) {
  6094. this.levels = data.levels;
  6095. };
  6096. _proto.swapAudioCodec = function swapAudioCodec() {
  6097. this.audioCodecSwap = !this.audioCodecSwap;
  6098. }
  6099. /**
  6100. * Seeks to the set startPosition if not equal to the mediaElement's current time.
  6101. */;
  6102. _proto.seekToStartPos = function seekToStartPos() {
  6103. var media = this.media;
  6104. if (!media) {
  6105. return;
  6106. }
  6107. var currentTime = media.currentTime;
  6108. var startPosition = this.startPosition;
  6109. // only adjust currentTime if different from startPosition or if startPosition not buffered
  6110. // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered
  6111. if (startPosition >= 0 && currentTime < startPosition) {
  6112. if (media.seeking) {
  6113. this.log("could not seek to " + startPosition + ", already seeking at " + currentTime);
  6114. return;
  6115. }
  6116. var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__.BufferHelper.getBuffered(media);
  6117. var bufferStart = buffered.length ? buffered.start(0) : 0;
  6118. var delta = bufferStart - startPosition;
  6119. if (delta > 0 && (delta < this.config.maxBufferHole || delta < this.config.maxFragLookUpTolerance)) {
  6120. this.log("adjusting start position by " + delta + " to match buffer start");
  6121. startPosition += delta;
  6122. this.startPosition = startPosition;
  6123. }
  6124. this.log("seek to target start position " + startPosition + " from current time " + currentTime);
  6125. media.currentTime = startPosition;
  6126. }
  6127. };
  6128. _proto._getAudioCodec = function _getAudioCodec(currentLevel) {
  6129. var audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
  6130. if (this.audioCodecSwap && audioCodec) {
  6131. this.log('Swapping audio codec');
  6132. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  6133. audioCodec = 'mp4a.40.2';
  6134. } else {
  6135. audioCodec = 'mp4a.40.5';
  6136. }
  6137. }
  6138. return audioCodec;
  6139. };
  6140. _proto._loadBitrateTestFrag = function _loadBitrateTestFrag(frag, levelDetails) {
  6141. var _this2 = this;
  6142. frag.bitrateTest = true;
  6143. this._doFragLoad(frag, levelDetails).then(function (data) {
  6144. var hls = _this2.hls;
  6145. if (!data || hls.nextLoadLevel || _this2.fragContextChanged(frag)) {
  6146. return;
  6147. }
  6148. _this2.fragLoadError = 0;
  6149. _this2.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.IDLE;
  6150. _this2.startFragRequested = false;
  6151. _this2.bitrateTest = false;
  6152. var stats = frag.stats;
  6153. // Bitrate tests fragments are neither parsed nor buffered
  6154. stats.parsing.start = stats.parsing.end = stats.buffering.start = stats.buffering.end = self.performance.now();
  6155. hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__.Events.FRAG_LOADED, data);
  6156. frag.bitrateTest = false;
  6157. });
  6158. };
  6159. _proto._handleTransmuxComplete = function _handleTransmuxComplete(transmuxResult) {
  6160. var _id3$samples;
  6161. var id = 'main';
  6162. var hls = this.hls;
  6163. var remuxResult = transmuxResult.remuxResult,
  6164. chunkMeta = transmuxResult.chunkMeta;
  6165. var context = this.getCurrentContext(chunkMeta);
  6166. if (!context) {
  6167. this.warn("The loading context changed while buffering fragment " + chunkMeta.sn + " of level " + chunkMeta.level + ". This chunk will not be buffered.");
  6168. this.resetStartWhenNotLoaded(chunkMeta.level);
  6169. return;
  6170. }
  6171. var frag = context.frag,
  6172. part = context.part,
  6173. level = context.level;
  6174. var video = remuxResult.video,
  6175. text = remuxResult.text,
  6176. id3 = remuxResult.id3,
  6177. initSegment = remuxResult.initSegment;
  6178. var details = level.details;
  6179. // The audio-stream-controller handles audio buffering if Hls.js is playing an alternate audio track
  6180. var audio = this.altAudio ? undefined : remuxResult.audio;
  6181. // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.
  6182. // If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.
  6183. if (this.fragContextChanged(frag)) {
  6184. return;
  6185. }
  6186. this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.PARSING;
  6187. if (initSegment) {
  6188. if (initSegment.tracks) {
  6189. this._bufferInitSegment(level, initSegment.tracks, frag, chunkMeta);
  6190. hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__.Events.FRAG_PARSING_INIT_SEGMENT, {
  6191. frag: frag,
  6192. id: id,
  6193. tracks: initSegment.tracks
  6194. });
  6195. }
  6196. // This would be nice if Number.isFinite acted as a typeguard, but it doesn't. See: https://github.com/Microsoft/TypeScript/issues/10038
  6197. var initPTS = initSegment.initPTS;
  6198. var timescale = initSegment.timescale;
  6199. if ((0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(initPTS)) {
  6200. this.initPTS[frag.cc] = initPTS;
  6201. hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__.Events.INIT_PTS_FOUND, {
  6202. frag: frag,
  6203. id: id,
  6204. initPTS: initPTS,
  6205. timescale: timescale
  6206. });
  6207. }
  6208. }
  6209. // Avoid buffering if backtracking this fragment
  6210. if (video && remuxResult.independent !== false) {
  6211. if (details) {
  6212. var startPTS = video.startPTS,
  6213. endPTS = video.endPTS,
  6214. startDTS = video.startDTS,
  6215. endDTS = video.endDTS;
  6216. if (part) {
  6217. part.elementaryStreams[video.type] = {
  6218. startPTS: startPTS,
  6219. endPTS: endPTS,
  6220. startDTS: startDTS,
  6221. endDTS: endDTS
  6222. };
  6223. } else {
  6224. if (video.firstKeyFrame && video.independent && chunkMeta.id === 1) {
  6225. this.couldBacktrack = true;
  6226. }
  6227. if (video.dropped && video.independent) {
  6228. // Backtrack if dropped frames create a gap after currentTime
  6229. var bufferInfo = this.getMainFwdBufferInfo();
  6230. var targetBufferTime = (bufferInfo ? bufferInfo.end : this.getLoadPosition()) + this.config.maxBufferHole;
  6231. var startTime = video.firstKeyFramePTS ? video.firstKeyFramePTS : startPTS;
  6232. if (targetBufferTime < startTime - this.config.maxBufferHole) {
  6233. this.backtrack(frag);
  6234. return;
  6235. }
  6236. // Set video stream start to fragment start so that truncated samples do not distort the timeline, and mark it partial
  6237. frag.setElementaryStreamInfo(video.type, frag.start, endPTS, frag.start, endDTS, true);
  6238. }
  6239. }
  6240. frag.setElementaryStreamInfo(video.type, startPTS, endPTS, startDTS, endDTS);
  6241. if (this.backtrackFragment) {
  6242. this.backtrackFragment = frag;
  6243. }
  6244. this.bufferFragmentData(video, frag, part, chunkMeta);
  6245. }
  6246. } else if (remuxResult.independent === false) {
  6247. this.backtrack(frag);
  6248. return;
  6249. }
  6250. if (audio) {
  6251. var _startPTS = audio.startPTS,
  6252. _endPTS = audio.endPTS,
  6253. _startDTS = audio.startDTS,
  6254. _endDTS = audio.endDTS;
  6255. if (part) {
  6256. part.elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_7__.ElementaryStreamTypes.AUDIO] = {
  6257. startPTS: _startPTS,
  6258. endPTS: _endPTS,
  6259. startDTS: _startDTS,
  6260. endDTS: _endDTS
  6261. };
  6262. }
  6263. frag.setElementaryStreamInfo(_loader_fragment__WEBPACK_IMPORTED_MODULE_7__.ElementaryStreamTypes.AUDIO, _startPTS, _endPTS, _startDTS, _endDTS);
  6264. this.bufferFragmentData(audio, frag, part, chunkMeta);
  6265. }
  6266. if (details && id3 !== null && id3 !== void 0 && (_id3$samples = id3.samples) !== null && _id3$samples !== void 0 && _id3$samples.length) {
  6267. var emittedID3 = {
  6268. id: id,
  6269. frag: frag,
  6270. details: details,
  6271. samples: id3.samples
  6272. };
  6273. hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__.Events.FRAG_PARSING_METADATA, emittedID3);
  6274. }
  6275. if (details && text) {
  6276. var emittedText = {
  6277. id: id,
  6278. frag: frag,
  6279. details: details,
  6280. samples: text.samples
  6281. };
  6282. hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__.Events.FRAG_PARSING_USERDATA, emittedText);
  6283. }
  6284. };
  6285. _proto._bufferInitSegment = function _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
  6286. var _this3 = this;
  6287. if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.PARSING) {
  6288. return;
  6289. }
  6290. this.audioOnly = !!tracks.audio && !tracks.video;
  6291. // if audio track is expected to come from audio stream controller, discard any coming from main
  6292. if (this.altAudio && !this.audioOnly) {
  6293. delete tracks.audio;
  6294. }
  6295. // include levelCodec in audio and video tracks
  6296. var audio = tracks.audio,
  6297. video = tracks.video,
  6298. audiovideo = tracks.audiovideo;
  6299. if (audio) {
  6300. var audioCodec = currentLevel.audioCodec;
  6301. var ua = navigator.userAgent.toLowerCase();
  6302. if (this.audioCodecSwitch) {
  6303. if (audioCodec) {
  6304. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  6305. audioCodec = 'mp4a.40.2';
  6306. } else {
  6307. audioCodec = 'mp4a.40.5';
  6308. }
  6309. }
  6310. // In the case that AAC and HE-AAC audio codecs are signalled in manifest,
  6311. // force HE-AAC, as it seems that most browsers prefers it.
  6312. // don't force HE-AAC if mono stream, or in Firefox
  6313. if (audio.metadata.channelCount !== 1 && ua.indexOf('firefox') === -1) {
  6314. audioCodec = 'mp4a.40.5';
  6315. }
  6316. }
  6317. // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise
  6318. if (ua.indexOf('android') !== -1 && audio.container !== 'audio/mpeg') {
  6319. // Exclude mpeg audio
  6320. audioCodec = 'mp4a.40.2';
  6321. this.log("Android: force audio codec to " + audioCodec);
  6322. }
  6323. if (currentLevel.audioCodec && currentLevel.audioCodec !== audioCodec) {
  6324. this.log("Swapping manifest audio codec \"" + currentLevel.audioCodec + "\" for \"" + audioCodec + "\"");
  6325. }
  6326. audio.levelCodec = audioCodec;
  6327. audio.id = 'main';
  6328. this.log("Init audio buffer, container:" + audio.container + ", codecs[selected/level/parsed]=[" + (audioCodec || '') + "/" + (currentLevel.audioCodec || '') + "/" + audio.codec + "]");
  6329. }
  6330. if (video) {
  6331. video.levelCodec = currentLevel.videoCodec;
  6332. video.id = 'main';
  6333. this.log("Init video buffer, container:" + video.container + ", codecs[level/parsed]=[" + (currentLevel.videoCodec || '') + "/" + video.codec + "]");
  6334. }
  6335. if (audiovideo) {
  6336. this.log("Init audiovideo buffer, container:" + audiovideo.container + ", codecs[level/parsed]=[" + (currentLevel.attrs.CODECS || '') + "/" + audiovideo.codec + "]");
  6337. }
  6338. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__.Events.BUFFER_CODECS, tracks);
  6339. // loop through tracks that are going to be provided to bufferController
  6340. Object.keys(tracks).forEach(function (trackName) {
  6341. var track = tracks[trackName];
  6342. var initSegment = track.initSegment;
  6343. if (initSegment !== null && initSegment !== void 0 && initSegment.byteLength) {
  6344. _this3.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__.Events.BUFFER_APPENDING, {
  6345. type: trackName,
  6346. data: initSegment,
  6347. frag: frag,
  6348. part: null,
  6349. chunkMeta: chunkMeta,
  6350. parent: frag.type
  6351. });
  6352. }
  6353. });
  6354. // trigger handler right now
  6355. this.tick();
  6356. };
  6357. _proto.getMainFwdBufferInfo = function getMainFwdBufferInfo() {
  6358. return this.getFwdBufferInfo(this.mediaBuffer ? this.mediaBuffer : this.media, _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistLevelType.MAIN);
  6359. };
  6360. _proto.backtrack = function backtrack(frag) {
  6361. this.couldBacktrack = true;
  6362. // Causes findFragments to backtrack through fragments to find the keyframe
  6363. this.backtrackFragment = frag;
  6364. this.resetTransmuxer();
  6365. this.flushBufferGap(frag);
  6366. this.fragmentTracker.removeFragment(frag);
  6367. this.fragPrevious = null;
  6368. this.nextLoadPosition = frag.start;
  6369. this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__.State.IDLE;
  6370. };
  6371. _proto.checkFragmentChanged = function checkFragmentChanged() {
  6372. var video = this.media;
  6373. var fragPlayingCurrent = null;
  6374. if (video && video.readyState > 1 && video.seeking === false) {
  6375. var currentTime = video.currentTime;
  6376. /* if video element is in seeked state, currentTime can only increase.
  6377. (assuming that playback rate is positive ...)
  6378. As sometimes currentTime jumps back to zero after a
  6379. media decode error, check this, to avoid seeking back to
  6380. wrong position after a media decode error
  6381. */
  6382. if (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__.BufferHelper.isBuffered(video, currentTime)) {
  6383. fragPlayingCurrent = this.getAppendedFrag(currentTime);
  6384. } else if (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__.BufferHelper.isBuffered(video, currentTime + 0.1)) {
  6385. /* ensure that FRAG_CHANGED event is triggered at startup,
  6386. when first video frame is displayed and playback is paused.
  6387. add a tolerance of 100ms, in case current position is not buffered,
  6388. check if current pos+100ms is buffered and use that buffer range
  6389. for FRAG_CHANGED event reporting */
  6390. fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1);
  6391. }
  6392. if (fragPlayingCurrent) {
  6393. this.backtrackFragment = null;
  6394. var fragPlaying = this.fragPlaying;
  6395. var fragCurrentLevel = fragPlayingCurrent.level;
  6396. if (!fragPlaying || fragPlayingCurrent.sn !== fragPlaying.sn || fragPlaying.level !== fragCurrentLevel || fragPlayingCurrent.urlId !== fragPlaying.urlId) {
  6397. this.fragPlaying = fragPlayingCurrent;
  6398. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__.Events.FRAG_CHANGED, {
  6399. frag: fragPlayingCurrent
  6400. });
  6401. if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) {
  6402. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__.Events.LEVEL_SWITCHED, {
  6403. level: fragCurrentLevel
  6404. });
  6405. }
  6406. }
  6407. }
  6408. }
  6409. };
  6410. _createClass(StreamController, [{
  6411. key: "nextLevel",
  6412. get: function get() {
  6413. var frag = this.nextBufferedFrag;
  6414. if (frag) {
  6415. return frag.level;
  6416. }
  6417. return -1;
  6418. }
  6419. }, {
  6420. key: "currentFrag",
  6421. get: function get() {
  6422. var media = this.media;
  6423. if (media) {
  6424. return this.fragPlaying || this.getAppendedFrag(media.currentTime);
  6425. }
  6426. return null;
  6427. }
  6428. }, {
  6429. key: "currentProgramDateTime",
  6430. get: function get() {
  6431. var media = this.media;
  6432. if (media) {
  6433. var currentTime = media.currentTime;
  6434. var frag = this.currentFrag;
  6435. if (frag && (0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(currentTime) && (0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(frag.programDateTime)) {
  6436. var epocMs = frag.programDateTime + (currentTime - frag.start) * 1000;
  6437. return new Date(epocMs);
  6438. }
  6439. }
  6440. return null;
  6441. }
  6442. }, {
  6443. key: "currentLevel",
  6444. get: function get() {
  6445. var frag = this.currentFrag;
  6446. if (frag) {
  6447. return frag.level;
  6448. }
  6449. return -1;
  6450. }
  6451. }, {
  6452. key: "nextBufferedFrag",
  6453. get: function get() {
  6454. var frag = this.currentFrag;
  6455. if (frag) {
  6456. return this.followingBufferedFrag(frag);
  6457. }
  6458. return null;
  6459. }
  6460. }, {
  6461. key: "forceStartLoad",
  6462. get: function get() {
  6463. return this._forceStartLoad;
  6464. }
  6465. }]);
  6466. return StreamController;
  6467. }(_base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["default"]);
  6468. /***/ }),
  6469. /***/ "./src/crypt/aes-crypto.ts":
  6470. /*!*********************************!*\
  6471. !*** ./src/crypt/aes-crypto.ts ***!
  6472. \*********************************/
  6473. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  6474. "use strict";
  6475. __webpack_require__.r(__webpack_exports__);
  6476. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  6477. /* harmony export */ "default": () => (/* binding */ AESCrypto)
  6478. /* harmony export */ });
  6479. var AESCrypto = /*#__PURE__*/function () {
  6480. function AESCrypto(subtle, iv) {
  6481. this.subtle = void 0;
  6482. this.aesIV = void 0;
  6483. this.subtle = subtle;
  6484. this.aesIV = iv;
  6485. }
  6486. var _proto = AESCrypto.prototype;
  6487. _proto.decrypt = function decrypt(data, key) {
  6488. return this.subtle.decrypt({
  6489. name: 'AES-CBC',
  6490. iv: this.aesIV
  6491. }, key, data);
  6492. };
  6493. return AESCrypto;
  6494. }();
  6495. /***/ }),
  6496. /***/ "./src/crypt/aes-decryptor.ts":
  6497. /*!************************************!*\
  6498. !*** ./src/crypt/aes-decryptor.ts ***!
  6499. \************************************/
  6500. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  6501. "use strict";
  6502. __webpack_require__.r(__webpack_exports__);
  6503. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  6504. /* harmony export */ "default": () => (/* binding */ AESDecryptor),
  6505. /* harmony export */ "removePadding": () => (/* binding */ removePadding)
  6506. /* harmony export */ });
  6507. /* harmony import */ var _utils_typed_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/typed-array */ "./src/utils/typed-array.ts");
  6508. // PKCS7
  6509. function removePadding(array) {
  6510. var outputBytes = array.byteLength;
  6511. var paddingBytes = outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1);
  6512. if (paddingBytes) {
  6513. return (0,_utils_typed_array__WEBPACK_IMPORTED_MODULE_0__.sliceUint8)(array, 0, outputBytes - paddingBytes);
  6514. }
  6515. return array;
  6516. }
  6517. var AESDecryptor = /*#__PURE__*/function () {
  6518. function AESDecryptor() {
  6519. this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
  6520. this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  6521. this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  6522. this.sBox = new Uint32Array(256);
  6523. this.invSBox = new Uint32Array(256);
  6524. this.key = new Uint32Array(0);
  6525. this.ksRows = 0;
  6526. this.keySize = 0;
  6527. this.keySchedule = void 0;
  6528. this.invKeySchedule = void 0;
  6529. this.initTable();
  6530. }
  6531. // Using view.getUint32() also swaps the byte order.
  6532. var _proto = AESDecryptor.prototype;
  6533. _proto.uint8ArrayToUint32Array_ = function uint8ArrayToUint32Array_(arrayBuffer) {
  6534. var view = new DataView(arrayBuffer);
  6535. var newArray = new Uint32Array(4);
  6536. for (var i = 0; i < 4; i++) {
  6537. newArray[i] = view.getUint32(i * 4);
  6538. }
  6539. return newArray;
  6540. };
  6541. _proto.initTable = function initTable() {
  6542. var sBox = this.sBox;
  6543. var invSBox = this.invSBox;
  6544. var subMix = this.subMix;
  6545. var subMix0 = subMix[0];
  6546. var subMix1 = subMix[1];
  6547. var subMix2 = subMix[2];
  6548. var subMix3 = subMix[3];
  6549. var invSubMix = this.invSubMix;
  6550. var invSubMix0 = invSubMix[0];
  6551. var invSubMix1 = invSubMix[1];
  6552. var invSubMix2 = invSubMix[2];
  6553. var invSubMix3 = invSubMix[3];
  6554. var d = new Uint32Array(256);
  6555. var x = 0;
  6556. var xi = 0;
  6557. var i = 0;
  6558. for (i = 0; i < 256; i++) {
  6559. if (i < 128) {
  6560. d[i] = i << 1;
  6561. } else {
  6562. d[i] = i << 1 ^ 0x11b;
  6563. }
  6564. }
  6565. for (i = 0; i < 256; i++) {
  6566. var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
  6567. sx = sx >>> 8 ^ sx & 0xff ^ 0x63;
  6568. sBox[x] = sx;
  6569. invSBox[sx] = x;
  6570. // Compute multiplication
  6571. var x2 = d[x];
  6572. var x4 = d[x2];
  6573. var x8 = d[x4];
  6574. // Compute sub/invSub bytes, mix columns tables
  6575. var t = d[sx] * 0x101 ^ sx * 0x1010100;
  6576. subMix0[x] = t << 24 | t >>> 8;
  6577. subMix1[x] = t << 16 | t >>> 16;
  6578. subMix2[x] = t << 8 | t >>> 24;
  6579. subMix3[x] = t;
  6580. // Compute inv sub bytes, inv mix columns tables
  6581. t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  6582. invSubMix0[sx] = t << 24 | t >>> 8;
  6583. invSubMix1[sx] = t << 16 | t >>> 16;
  6584. invSubMix2[sx] = t << 8 | t >>> 24;
  6585. invSubMix3[sx] = t;
  6586. // Compute next counter
  6587. if (!x) {
  6588. x = xi = 1;
  6589. } else {
  6590. x = x2 ^ d[d[d[x8 ^ x2]]];
  6591. xi ^= d[d[xi]];
  6592. }
  6593. }
  6594. };
  6595. _proto.expandKey = function expandKey(keyBuffer) {
  6596. // convert keyBuffer to Uint32Array
  6597. var key = this.uint8ArrayToUint32Array_(keyBuffer);
  6598. var sameKey = true;
  6599. var offset = 0;
  6600. while (offset < key.length && sameKey) {
  6601. sameKey = key[offset] === this.key[offset];
  6602. offset++;
  6603. }
  6604. if (sameKey) {
  6605. return;
  6606. }
  6607. this.key = key;
  6608. var keySize = this.keySize = key.length;
  6609. if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
  6610. throw new Error('Invalid aes key size=' + keySize);
  6611. }
  6612. var ksRows = this.ksRows = (keySize + 6 + 1) * 4;
  6613. var ksRow;
  6614. var invKsRow;
  6615. var keySchedule = this.keySchedule = new Uint32Array(ksRows);
  6616. var invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
  6617. var sbox = this.sBox;
  6618. var rcon = this.rcon;
  6619. var invSubMix = this.invSubMix;
  6620. var invSubMix0 = invSubMix[0];
  6621. var invSubMix1 = invSubMix[1];
  6622. var invSubMix2 = invSubMix[2];
  6623. var invSubMix3 = invSubMix[3];
  6624. var prev;
  6625. var t;
  6626. for (ksRow = 0; ksRow < ksRows; ksRow++) {
  6627. if (ksRow < keySize) {
  6628. prev = keySchedule[ksRow] = key[ksRow];
  6629. continue;
  6630. }
  6631. t = prev;
  6632. if (ksRow % keySize === 0) {
  6633. // Rot word
  6634. t = t << 8 | t >>> 24;
  6635. // Sub word
  6636. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  6637. // Mix Rcon
  6638. t ^= rcon[ksRow / keySize | 0] << 24;
  6639. } else if (keySize > 6 && ksRow % keySize === 4) {
  6640. // Sub word
  6641. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  6642. }
  6643. keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
  6644. }
  6645. for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
  6646. ksRow = ksRows - invKsRow;
  6647. if (invKsRow & 3) {
  6648. t = keySchedule[ksRow];
  6649. } else {
  6650. t = keySchedule[ksRow - 4];
  6651. }
  6652. if (invKsRow < 4 || ksRow <= 4) {
  6653. invKeySchedule[invKsRow] = t;
  6654. } else {
  6655. invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]];
  6656. }
  6657. invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
  6658. }
  6659. }
  6660. // Adding this as a method greatly improves performance.
  6661. ;
  6662. _proto.networkToHostOrderSwap = function networkToHostOrderSwap(word) {
  6663. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  6664. };
  6665. _proto.decrypt = function decrypt(inputArrayBuffer, offset, aesIV) {
  6666. var nRounds = this.keySize + 6;
  6667. var invKeySchedule = this.invKeySchedule;
  6668. var invSBOX = this.invSBox;
  6669. var invSubMix = this.invSubMix;
  6670. var invSubMix0 = invSubMix[0];
  6671. var invSubMix1 = invSubMix[1];
  6672. var invSubMix2 = invSubMix[2];
  6673. var invSubMix3 = invSubMix[3];
  6674. var initVector = this.uint8ArrayToUint32Array_(aesIV);
  6675. var initVector0 = initVector[0];
  6676. var initVector1 = initVector[1];
  6677. var initVector2 = initVector[2];
  6678. var initVector3 = initVector[3];
  6679. var inputInt32 = new Int32Array(inputArrayBuffer);
  6680. var outputInt32 = new Int32Array(inputInt32.length);
  6681. var t0, t1, t2, t3;
  6682. var s0, s1, s2, s3;
  6683. var inputWords0, inputWords1, inputWords2, inputWords3;
  6684. var ksRow, i;
  6685. var swapWord = this.networkToHostOrderSwap;
  6686. while (offset < inputInt32.length) {
  6687. inputWords0 = swapWord(inputInt32[offset]);
  6688. inputWords1 = swapWord(inputInt32[offset + 1]);
  6689. inputWords2 = swapWord(inputInt32[offset + 2]);
  6690. inputWords3 = swapWord(inputInt32[offset + 3]);
  6691. s0 = inputWords0 ^ invKeySchedule[0];
  6692. s1 = inputWords3 ^ invKeySchedule[1];
  6693. s2 = inputWords2 ^ invKeySchedule[2];
  6694. s3 = inputWords1 ^ invKeySchedule[3];
  6695. ksRow = 4;
  6696. // Iterate through the rounds of decryption
  6697. for (i = 1; i < nRounds; i++) {
  6698. t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];
  6699. t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  6700. t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  6701. t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  6702. // Update state
  6703. s0 = t0;
  6704. s1 = t1;
  6705. s2 = t2;
  6706. s3 = t3;
  6707. ksRow = ksRow + 4;
  6708. }
  6709. // Shift rows, sub bytes, add round key
  6710. t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow];
  6711. t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  6712. t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  6713. t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  6714. // Write
  6715. outputInt32[offset] = swapWord(t0 ^ initVector0);
  6716. outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
  6717. outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
  6718. outputInt32[offset + 3] = swapWord(t1 ^ initVector3);
  6719. // reset initVector to last 4 unsigned int
  6720. initVector0 = inputWords0;
  6721. initVector1 = inputWords1;
  6722. initVector2 = inputWords2;
  6723. initVector3 = inputWords3;
  6724. offset = offset + 4;
  6725. }
  6726. return outputInt32.buffer;
  6727. };
  6728. return AESDecryptor;
  6729. }();
  6730. /***/ }),
  6731. /***/ "./src/crypt/decrypter.ts":
  6732. /*!********************************!*\
  6733. !*** ./src/crypt/decrypter.ts ***!
  6734. \********************************/
  6735. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  6736. "use strict";
  6737. __webpack_require__.r(__webpack_exports__);
  6738. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  6739. /* harmony export */ "default": () => (/* binding */ Decrypter)
  6740. /* harmony export */ });
  6741. /* harmony import */ var _aes_crypto__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./aes-crypto */ "./src/crypt/aes-crypto.ts");
  6742. /* harmony import */ var _fast_aes_key__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./fast-aes-key */ "./src/crypt/fast-aes-key.ts");
  6743. /* harmony import */ var _aes_decryptor__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./aes-decryptor */ "./src/crypt/aes-decryptor.ts");
  6744. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
  6745. /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
  6746. /* harmony import */ var _utils_typed_array__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/typed-array */ "./src/utils/typed-array.ts");
  6747. var CHUNK_SIZE = 16; // 16 bytes, 128 bits
  6748. var Decrypter = /*#__PURE__*/function () {
  6749. function Decrypter(config, _temp) {
  6750. var _ref = _temp === void 0 ? {} : _temp,
  6751. _ref$removePKCS7Paddi = _ref.removePKCS7Padding,
  6752. removePKCS7Padding = _ref$removePKCS7Paddi === void 0 ? true : _ref$removePKCS7Paddi;
  6753. this.logEnabled = true;
  6754. this.removePKCS7Padding = void 0;
  6755. this.subtle = null;
  6756. this.softwareDecrypter = null;
  6757. this.key = null;
  6758. this.fastAesKey = null;
  6759. this.remainderData = null;
  6760. this.currentIV = null;
  6761. this.currentResult = null;
  6762. this.useSoftware = void 0;
  6763. this.useSoftware = config.enableSoftwareAES;
  6764. this.removePKCS7Padding = removePKCS7Padding;
  6765. // built in decryptor expects PKCS7 padding
  6766. if (removePKCS7Padding) {
  6767. try {
  6768. var browserCrypto = self.crypto;
  6769. if (browserCrypto) {
  6770. this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
  6771. }
  6772. } catch (e) {
  6773. /* no-op */
  6774. }
  6775. }
  6776. if (this.subtle === null) {
  6777. this.useSoftware = true;
  6778. }
  6779. }
  6780. var _proto = Decrypter.prototype;
  6781. _proto.destroy = function destroy() {
  6782. this.subtle = null;
  6783. this.softwareDecrypter = null;
  6784. this.key = null;
  6785. this.fastAesKey = null;
  6786. this.remainderData = null;
  6787. this.currentIV = null;
  6788. this.currentResult = null;
  6789. };
  6790. _proto.isSync = function isSync() {
  6791. return this.useSoftware;
  6792. };
  6793. _proto.flush = function flush() {
  6794. var currentResult = this.currentResult,
  6795. remainderData = this.remainderData;
  6796. if (!currentResult || remainderData) {
  6797. _utils_logger__WEBPACK_IMPORTED_MODULE_3__.logger.error("[softwareDecrypt] " + (remainderData ? 'overflow bytes: ' + remainderData.byteLength : 'no result'));
  6798. this.reset();
  6799. return null;
  6800. }
  6801. var data = new Uint8Array(currentResult);
  6802. this.reset();
  6803. if (this.removePKCS7Padding) {
  6804. return (0,_aes_decryptor__WEBPACK_IMPORTED_MODULE_2__.removePadding)(data);
  6805. }
  6806. return data;
  6807. };
  6808. _proto.reset = function reset() {
  6809. this.currentResult = null;
  6810. this.currentIV = null;
  6811. this.remainderData = null;
  6812. if (this.softwareDecrypter) {
  6813. this.softwareDecrypter = null;
  6814. }
  6815. };
  6816. _proto.decrypt = function decrypt(data, key, iv) {
  6817. var _this = this;
  6818. if (this.useSoftware) {
  6819. return new Promise(function (resolve, reject) {
  6820. _this.softwareDecrypt(new Uint8Array(data), key, iv);
  6821. var decryptResult = _this.flush();
  6822. if (decryptResult) {
  6823. resolve(decryptResult.buffer);
  6824. } else {
  6825. reject(new Error('[softwareDecrypt] Failed to decrypt data'));
  6826. }
  6827. });
  6828. }
  6829. return this.webCryptoDecrypt(new Uint8Array(data), key, iv);
  6830. }
  6831. // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
  6832. // data is handled in the flush() call
  6833. ;
  6834. _proto.softwareDecrypt = function softwareDecrypt(data, key, iv) {
  6835. var currentIV = this.currentIV,
  6836. currentResult = this.currentResult,
  6837. remainderData = this.remainderData;
  6838. this.logOnce('JS AES decrypt');
  6839. // The output is staggered during progressive parsing - the current result is cached, and emitted on the next call
  6840. // This is done in order to strip PKCS7 padding, which is found at the end of each segment. We only know we've reached
  6841. // the end on flush(), but by that time we have already received all bytes for the segment.
  6842. // Progressive decryption does not work with WebCrypto
  6843. if (remainderData) {
  6844. data = (0,_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__.appendUint8Array)(remainderData, data);
  6845. this.remainderData = null;
  6846. }
  6847. // Byte length must be a multiple of 16 (AES-128 = 128 bit blocks = 16 bytes)
  6848. var currentChunk = this.getValidChunk(data);
  6849. if (!currentChunk.length) {
  6850. return null;
  6851. }
  6852. if (currentIV) {
  6853. iv = currentIV;
  6854. }
  6855. var softwareDecrypter = this.softwareDecrypter;
  6856. if (!softwareDecrypter) {
  6857. softwareDecrypter = this.softwareDecrypter = new _aes_decryptor__WEBPACK_IMPORTED_MODULE_2__["default"]();
  6858. }
  6859. softwareDecrypter.expandKey(key);
  6860. var result = currentResult;
  6861. this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv);
  6862. this.currentIV = (0,_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__.sliceUint8)(currentChunk, -16).buffer;
  6863. if (!result) {
  6864. return null;
  6865. }
  6866. return result;
  6867. };
  6868. _proto.webCryptoDecrypt = function webCryptoDecrypt(data, key, iv) {
  6869. var _this2 = this;
  6870. var subtle = this.subtle;
  6871. if (this.key !== key || !this.fastAesKey) {
  6872. this.key = key;
  6873. this.fastAesKey = new _fast_aes_key__WEBPACK_IMPORTED_MODULE_1__["default"](subtle, key);
  6874. }
  6875. return this.fastAesKey.expandKey().then(function (aesKey) {
  6876. // decrypt using web crypto
  6877. if (!subtle) {
  6878. return Promise.reject(new Error('web crypto not initialized'));
  6879. }
  6880. _this2.logOnce('WebCrypto AES decrypt');
  6881. var crypto = new _aes_crypto__WEBPACK_IMPORTED_MODULE_0__["default"](subtle, new Uint8Array(iv));
  6882. return crypto.decrypt(data.buffer, aesKey);
  6883. }).catch(function (err) {
  6884. _utils_logger__WEBPACK_IMPORTED_MODULE_3__.logger.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, " + err.name + ": " + err.message);
  6885. return _this2.onWebCryptoError(data, key, iv);
  6886. });
  6887. };
  6888. _proto.onWebCryptoError = function onWebCryptoError(data, key, iv) {
  6889. this.useSoftware = true;
  6890. this.logEnabled = true;
  6891. this.softwareDecrypt(data, key, iv);
  6892. var decryptResult = this.flush();
  6893. if (decryptResult) {
  6894. return decryptResult.buffer;
  6895. }
  6896. throw new Error('WebCrypto and softwareDecrypt: failed to decrypt data');
  6897. };
  6898. _proto.getValidChunk = function getValidChunk(data) {
  6899. var currentChunk = data;
  6900. var splitPoint = data.length - data.length % CHUNK_SIZE;
  6901. if (splitPoint !== data.length) {
  6902. currentChunk = (0,_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__.sliceUint8)(data, 0, splitPoint);
  6903. this.remainderData = (0,_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__.sliceUint8)(data, splitPoint);
  6904. }
  6905. return currentChunk;
  6906. };
  6907. _proto.logOnce = function logOnce(msg) {
  6908. if (!this.logEnabled) {
  6909. return;
  6910. }
  6911. _utils_logger__WEBPACK_IMPORTED_MODULE_3__.logger.log("[decrypter]: " + msg);
  6912. this.logEnabled = false;
  6913. };
  6914. return Decrypter;
  6915. }();
  6916. /***/ }),
  6917. /***/ "./src/crypt/fast-aes-key.ts":
  6918. /*!***********************************!*\
  6919. !*** ./src/crypt/fast-aes-key.ts ***!
  6920. \***********************************/
  6921. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  6922. "use strict";
  6923. __webpack_require__.r(__webpack_exports__);
  6924. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  6925. /* harmony export */ "default": () => (/* binding */ FastAESKey)
  6926. /* harmony export */ });
  6927. var FastAESKey = /*#__PURE__*/function () {
  6928. function FastAESKey(subtle, key) {
  6929. this.subtle = void 0;
  6930. this.key = void 0;
  6931. this.subtle = subtle;
  6932. this.key = key;
  6933. }
  6934. var _proto = FastAESKey.prototype;
  6935. _proto.expandKey = function expandKey() {
  6936. return this.subtle.importKey('raw', this.key, {
  6937. name: 'AES-CBC'
  6938. }, false, ['encrypt', 'decrypt']);
  6939. };
  6940. return FastAESKey;
  6941. }();
  6942. /***/ }),
  6943. /***/ "./src/demux/aacdemuxer.ts":
  6944. /*!*********************************!*\
  6945. !*** ./src/demux/aacdemuxer.ts ***!
  6946. \*********************************/
  6947. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  6948. "use strict";
  6949. __webpack_require__.r(__webpack_exports__);
  6950. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  6951. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  6952. /* harmony export */ });
  6953. /* harmony import */ var _base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base-audio-demuxer */ "./src/demux/base-audio-demuxer.ts");
  6954. /* harmony import */ var _adts__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./adts */ "./src/demux/adts.ts");
  6955. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
  6956. /* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
  6957. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  6958. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  6959. /**
  6960. * AAC demuxer
  6961. */
  6962. var AACDemuxer = /*#__PURE__*/function (_BaseAudioDemuxer) {
  6963. _inheritsLoose(AACDemuxer, _BaseAudioDemuxer);
  6964. function AACDemuxer(observer, config) {
  6965. var _this;
  6966. _this = _BaseAudioDemuxer.call(this) || this;
  6967. _this.observer = void 0;
  6968. _this.config = void 0;
  6969. _this.observer = observer;
  6970. _this.config = config;
  6971. return _this;
  6972. }
  6973. var _proto = AACDemuxer.prototype;
  6974. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  6975. _BaseAudioDemuxer.prototype.resetInitSegment.call(this, initSegment, audioCodec, videoCodec, trackDuration);
  6976. this._audioTrack = {
  6977. container: 'audio/adts',
  6978. type: 'audio',
  6979. id: 2,
  6980. pid: -1,
  6981. sequenceNumber: 0,
  6982. segmentCodec: 'aac',
  6983. samples: [],
  6984. manifestCodec: audioCodec,
  6985. duration: trackDuration,
  6986. inputTimeScale: 90000,
  6987. dropped: 0
  6988. };
  6989. }
  6990. // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS
  6991. ;
  6992. AACDemuxer.probe = function probe(data) {
  6993. if (!data) {
  6994. return false;
  6995. }
  6996. // Check for the ADTS sync word
  6997. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  6998. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  6999. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  7000. var id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_3__.getID3Data(data, 0) || [];
  7001. var offset = id3Data.length;
  7002. for (var length = data.length; offset < length; offset++) {
  7003. if (_adts__WEBPACK_IMPORTED_MODULE_1__.probe(data, offset)) {
  7004. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.log('ADTS sync word found !');
  7005. return true;
  7006. }
  7007. }
  7008. return false;
  7009. };
  7010. _proto.canParse = function canParse(data, offset) {
  7011. return _adts__WEBPACK_IMPORTED_MODULE_1__.canParse(data, offset);
  7012. };
  7013. _proto.appendFrame = function appendFrame(track, data, offset) {
  7014. _adts__WEBPACK_IMPORTED_MODULE_1__.initTrackConfig(track, this.observer, data, offset, track.manifestCodec);
  7015. var frame = _adts__WEBPACK_IMPORTED_MODULE_1__.appendFrame(track, data, offset, this.basePTS, this.frameIndex);
  7016. if (frame && frame.missing === 0) {
  7017. return frame;
  7018. }
  7019. };
  7020. return AACDemuxer;
  7021. }(_base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__["default"]);
  7022. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (AACDemuxer);
  7023. /***/ }),
  7024. /***/ "./src/demux/adts.ts":
  7025. /*!***************************!*\
  7026. !*** ./src/demux/adts.ts ***!
  7027. \***************************/
  7028. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  7029. "use strict";
  7030. __webpack_require__.r(__webpack_exports__);
  7031. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  7032. /* harmony export */ "appendFrame": () => (/* binding */ appendFrame),
  7033. /* harmony export */ "canGetFrameLength": () => (/* binding */ canGetFrameLength),
  7034. /* harmony export */ "canParse": () => (/* binding */ canParse),
  7035. /* harmony export */ "getAudioConfig": () => (/* binding */ getAudioConfig),
  7036. /* harmony export */ "getFrameDuration": () => (/* binding */ getFrameDuration),
  7037. /* harmony export */ "getFullFrameLength": () => (/* binding */ getFullFrameLength),
  7038. /* harmony export */ "getHeaderLength": () => (/* binding */ getHeaderLength),
  7039. /* harmony export */ "initTrackConfig": () => (/* binding */ initTrackConfig),
  7040. /* harmony export */ "isHeader": () => (/* binding */ isHeader),
  7041. /* harmony export */ "isHeaderPattern": () => (/* binding */ isHeaderPattern),
  7042. /* harmony export */ "parseFrameHeader": () => (/* binding */ parseFrameHeader),
  7043. /* harmony export */ "probe": () => (/* binding */ probe)
  7044. /* harmony export */ });
  7045. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
  7046. /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
  7047. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts");
  7048. /**
  7049. * ADTS parser helper
  7050. * @link https://wiki.multimedia.cx/index.php?title=ADTS
  7051. */
  7052. function getAudioConfig(observer, data, offset, audioCodec) {
  7053. var adtsObjectType;
  7054. var adtsExtensionSamplingIndex;
  7055. var adtsChannelConfig;
  7056. var config;
  7057. var userAgent = navigator.userAgent.toLowerCase();
  7058. var manifestCodec = audioCodec;
  7059. var adtsSamplingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  7060. // byte 2
  7061. adtsObjectType = ((data[offset + 2] & 0xc0) >>> 6) + 1;
  7062. var adtsSamplingIndex = (data[offset + 2] & 0x3c) >>> 2;
  7063. if (adtsSamplingIndex > adtsSamplingRates.length - 1) {
  7064. observer.trigger(_events__WEBPACK_IMPORTED_MODULE_2__.Events.ERROR, {
  7065. type: _errors__WEBPACK_IMPORTED_MODULE_1__.ErrorTypes.MEDIA_ERROR,
  7066. details: _errors__WEBPACK_IMPORTED_MODULE_1__.ErrorDetails.FRAG_PARSING_ERROR,
  7067. fatal: true,
  7068. reason: "invalid ADTS sampling index:" + adtsSamplingIndex
  7069. });
  7070. return;
  7071. }
  7072. adtsChannelConfig = (data[offset + 2] & 0x01) << 2;
  7073. // byte 3
  7074. adtsChannelConfig |= (data[offset + 3] & 0xc0) >>> 6;
  7075. _utils_logger__WEBPACK_IMPORTED_MODULE_0__.logger.log("manifest codec:" + audioCodec + ", ADTS type:" + adtsObjectType + ", samplingIndex:" + adtsSamplingIndex);
  7076. // firefox: freq less than 24kHz = AAC SBR (HE-AAC)
  7077. if (/firefox/i.test(userAgent)) {
  7078. if (adtsSamplingIndex >= 6) {
  7079. adtsObjectType = 5;
  7080. config = new Array(4);
  7081. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  7082. // there is a factor 2 between frame sample rate and output sample rate
  7083. // multiply frequency by 2 (see table below, equivalent to substract 3)
  7084. adtsExtensionSamplingIndex = adtsSamplingIndex - 3;
  7085. } else {
  7086. adtsObjectType = 2;
  7087. config = new Array(2);
  7088. adtsExtensionSamplingIndex = adtsSamplingIndex;
  7089. }
  7090. // Android : always use AAC
  7091. } else if (userAgent.indexOf('android') !== -1) {
  7092. adtsObjectType = 2;
  7093. config = new Array(2);
  7094. adtsExtensionSamplingIndex = adtsSamplingIndex;
  7095. } else {
  7096. /* for other browsers (Chrome/Vivaldi/Opera ...)
  7097. always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)
  7098. */
  7099. adtsObjectType = 5;
  7100. config = new Array(4);
  7101. // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)
  7102. if (audioCodec && (audioCodec.indexOf('mp4a.40.29') !== -1 || audioCodec.indexOf('mp4a.40.5') !== -1) || !audioCodec && adtsSamplingIndex >= 6) {
  7103. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  7104. // there is a factor 2 between frame sample rate and output sample rate
  7105. // multiply frequency by 2 (see table below, equivalent to substract 3)
  7106. adtsExtensionSamplingIndex = adtsSamplingIndex - 3;
  7107. } else {
  7108. // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)
  7109. // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.
  7110. if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && (adtsSamplingIndex >= 6 && adtsChannelConfig === 1 || /vivaldi/i.test(userAgent)) || !audioCodec && adtsChannelConfig === 1) {
  7111. adtsObjectType = 2;
  7112. config = new Array(2);
  7113. }
  7114. adtsExtensionSamplingIndex = adtsSamplingIndex;
  7115. }
  7116. }
  7117. /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config
  7118. ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()
  7119. Audio Profile / Audio Object Type
  7120. 0: Null
  7121. 1: AAC Main
  7122. 2: AAC LC (Low Complexity)
  7123. 3: AAC SSR (Scalable Sample Rate)
  7124. 4: AAC LTP (Long Term Prediction)
  7125. 5: SBR (Spectral Band Replication)
  7126. 6: AAC Scalable
  7127. sampling freq
  7128. 0: 96000 Hz
  7129. 1: 88200 Hz
  7130. 2: 64000 Hz
  7131. 3: 48000 Hz
  7132. 4: 44100 Hz
  7133. 5: 32000 Hz
  7134. 6: 24000 Hz
  7135. 7: 22050 Hz
  7136. 8: 16000 Hz
  7137. 9: 12000 Hz
  7138. 10: 11025 Hz
  7139. 11: 8000 Hz
  7140. 12: 7350 Hz
  7141. 13: Reserved
  7142. 14: Reserved
  7143. 15: frequency is written explictly
  7144. Channel Configurations
  7145. These are the channel configurations:
  7146. 0: Defined in AOT Specifc Config
  7147. 1: 1 channel: front-center
  7148. 2: 2 channels: front-left, front-right
  7149. */
  7150. // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1
  7151. config[0] = adtsObjectType << 3;
  7152. // samplingFrequencyIndex
  7153. config[0] |= (adtsSamplingIndex & 0x0e) >> 1;
  7154. config[1] |= (adtsSamplingIndex & 0x01) << 7;
  7155. // channelConfiguration
  7156. config[1] |= adtsChannelConfig << 3;
  7157. if (adtsObjectType === 5) {
  7158. // adtsExtensionSamplingIndex
  7159. config[1] |= (adtsExtensionSamplingIndex & 0x0e) >> 1;
  7160. config[2] = (adtsExtensionSamplingIndex & 0x01) << 7;
  7161. // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???
  7162. // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc
  7163. config[2] |= 2 << 2;
  7164. config[3] = 0;
  7165. }
  7166. return {
  7167. config: config,
  7168. samplerate: adtsSamplingRates[adtsSamplingIndex],
  7169. channelCount: adtsChannelConfig,
  7170. codec: 'mp4a.40.' + adtsObjectType,
  7171. manifestCodec: manifestCodec
  7172. };
  7173. }
  7174. function isHeaderPattern(data, offset) {
  7175. return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;
  7176. }
  7177. function getHeaderLength(data, offset) {
  7178. return data[offset + 1] & 0x01 ? 7 : 9;
  7179. }
  7180. function getFullFrameLength(data, offset) {
  7181. return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xe0) >>> 5;
  7182. }
  7183. function canGetFrameLength(data, offset) {
  7184. return offset + 5 < data.length;
  7185. }
  7186. function isHeader(data, offset) {
  7187. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  7188. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  7189. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  7190. return offset + 1 < data.length && isHeaderPattern(data, offset);
  7191. }
  7192. function canParse(data, offset) {
  7193. return canGetFrameLength(data, offset) && isHeaderPattern(data, offset) && getFullFrameLength(data, offset) <= data.length - offset;
  7194. }
  7195. function probe(data, offset) {
  7196. // same as isHeader but we also check that ADTS frame follows last ADTS frame
  7197. // or end of data is reached
  7198. if (isHeader(data, offset)) {
  7199. // ADTS header Length
  7200. var headerLength = getHeaderLength(data, offset);
  7201. if (offset + headerLength >= data.length) {
  7202. return false;
  7203. }
  7204. // ADTS frame Length
  7205. var frameLength = getFullFrameLength(data, offset);
  7206. if (frameLength <= headerLength) {
  7207. return false;
  7208. }
  7209. var newOffset = offset + frameLength;
  7210. return newOffset === data.length || isHeader(data, newOffset);
  7211. }
  7212. return false;
  7213. }
  7214. function initTrackConfig(track, observer, data, offset, audioCodec) {
  7215. if (!track.samplerate) {
  7216. var config = getAudioConfig(observer, data, offset, audioCodec);
  7217. if (!config) {
  7218. return;
  7219. }
  7220. track.config = config.config;
  7221. track.samplerate = config.samplerate;
  7222. track.channelCount = config.channelCount;
  7223. track.codec = config.codec;
  7224. track.manifestCodec = config.manifestCodec;
  7225. _utils_logger__WEBPACK_IMPORTED_MODULE_0__.logger.log("parsed codec:" + track.codec + ", rate:" + config.samplerate + ", channels:" + config.channelCount);
  7226. }
  7227. }
  7228. function getFrameDuration(samplerate) {
  7229. return 1024 * 90000 / samplerate;
  7230. }
  7231. function parseFrameHeader(data, offset) {
  7232. // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
  7233. var headerLength = getHeaderLength(data, offset);
  7234. if (offset + headerLength <= data.length) {
  7235. // retrieve frame size
  7236. var frameLength = getFullFrameLength(data, offset) - headerLength;
  7237. if (frameLength > 0) {
  7238. // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}`);
  7239. return {
  7240. headerLength: headerLength,
  7241. frameLength: frameLength
  7242. };
  7243. }
  7244. }
  7245. }
  7246. function appendFrame(track, data, offset, pts, frameIndex) {
  7247. var frameDuration = getFrameDuration(track.samplerate);
  7248. var stamp = pts + frameIndex * frameDuration;
  7249. var header = parseFrameHeader(data, offset);
  7250. var unit;
  7251. if (header) {
  7252. var frameLength = header.frameLength,
  7253. headerLength = header.headerLength;
  7254. var _length = headerLength + frameLength;
  7255. var missing = Math.max(0, offset + _length - data.length);
  7256. // logger.log(`AAC frame ${frameIndex}, pts:${stamp} length@offset/total: ${frameLength}@${offset+headerLength}/${data.byteLength} missing: ${missing}`);
  7257. if (missing) {
  7258. unit = new Uint8Array(_length - headerLength);
  7259. unit.set(data.subarray(offset + headerLength, data.length), 0);
  7260. } else {
  7261. unit = data.subarray(offset + headerLength, offset + _length);
  7262. }
  7263. var _sample = {
  7264. unit: unit,
  7265. pts: stamp
  7266. };
  7267. if (!missing) {
  7268. track.samples.push(_sample);
  7269. }
  7270. return {
  7271. sample: _sample,
  7272. length: _length,
  7273. missing: missing
  7274. };
  7275. }
  7276. // overflow incomplete header
  7277. var length = data.length - offset;
  7278. unit = new Uint8Array(length);
  7279. unit.set(data.subarray(offset, data.length), 0);
  7280. var sample = {
  7281. unit: unit,
  7282. pts: stamp
  7283. };
  7284. return {
  7285. sample: sample,
  7286. length: length,
  7287. missing: -1
  7288. };
  7289. }
  7290. /***/ }),
  7291. /***/ "./src/demux/base-audio-demuxer.ts":
  7292. /*!*****************************************!*\
  7293. !*** ./src/demux/base-audio-demuxer.ts ***!
  7294. \*****************************************/
  7295. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  7296. "use strict";
  7297. __webpack_require__.r(__webpack_exports__);
  7298. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  7299. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__),
  7300. /* harmony export */ "initPTSFn": () => (/* binding */ initPTSFn)
  7301. /* harmony export */ });
  7302. /* harmony import */ var _Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
  7303. /* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
  7304. /* harmony import */ var _types_demuxer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../types/demuxer */ "./src/types/demuxer.ts");
  7305. /* harmony import */ var _dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./dummy-demuxed-track */ "./src/demux/dummy-demuxed-track.ts");
  7306. /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
  7307. /* harmony import */ var _utils_typed_array__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/typed-array */ "./src/utils/typed-array.ts");
  7308. var BaseAudioDemuxer = /*#__PURE__*/function () {
  7309. function BaseAudioDemuxer() {
  7310. this._audioTrack = void 0;
  7311. this._id3Track = void 0;
  7312. this.frameIndex = 0;
  7313. this.cachedData = null;
  7314. this.basePTS = null;
  7315. this.initPTS = null;
  7316. this.lastPTS = null;
  7317. }
  7318. var _proto = BaseAudioDemuxer.prototype;
  7319. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  7320. this._id3Track = {
  7321. type: 'id3',
  7322. id: 3,
  7323. pid: -1,
  7324. inputTimeScale: 90000,
  7325. sequenceNumber: 0,
  7326. samples: [],
  7327. dropped: 0
  7328. };
  7329. };
  7330. _proto.resetTimeStamp = function resetTimeStamp(deaultTimestamp) {
  7331. this.initPTS = deaultTimestamp;
  7332. this.resetContiguity();
  7333. };
  7334. _proto.resetContiguity = function resetContiguity() {
  7335. this.basePTS = null;
  7336. this.lastPTS = null;
  7337. this.frameIndex = 0;
  7338. };
  7339. _proto.canParse = function canParse(data, offset) {
  7340. return false;
  7341. };
  7342. _proto.appendFrame = function appendFrame(track, data, offset) {}
  7343. // feed incoming data to the front of the parsing pipeline
  7344. ;
  7345. _proto.demux = function demux(data, timeOffset) {
  7346. if (this.cachedData) {
  7347. data = (0,_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__.appendUint8Array)(this.cachedData, data);
  7348. this.cachedData = null;
  7349. }
  7350. var id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_1__.getID3Data(data, 0);
  7351. var offset = id3Data ? id3Data.length : 0;
  7352. var lastDataIndex;
  7353. var track = this._audioTrack;
  7354. var id3Track = this._id3Track;
  7355. var timestamp = id3Data ? _demux_id3__WEBPACK_IMPORTED_MODULE_1__.getTimeStamp(id3Data) : undefined;
  7356. var length = data.length;
  7357. if (this.basePTS === null || this.frameIndex === 0 && (0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(timestamp)) {
  7358. this.basePTS = initPTSFn(timestamp, timeOffset, this.initPTS);
  7359. this.lastPTS = this.basePTS;
  7360. }
  7361. if (this.lastPTS === null) {
  7362. this.lastPTS = this.basePTS;
  7363. }
  7364. // more expressive than alternative: id3Data?.length
  7365. if (id3Data && id3Data.length > 0) {
  7366. id3Track.samples.push({
  7367. pts: this.lastPTS,
  7368. dts: this.lastPTS,
  7369. data: id3Data,
  7370. type: _types_demuxer__WEBPACK_IMPORTED_MODULE_2__.MetadataSchema.audioId3,
  7371. duration: Number.POSITIVE_INFINITY
  7372. });
  7373. }
  7374. while (offset < length) {
  7375. if (this.canParse(data, offset)) {
  7376. var frame = this.appendFrame(track, data, offset);
  7377. if (frame) {
  7378. this.frameIndex++;
  7379. this.lastPTS = frame.sample.pts;
  7380. offset += frame.length;
  7381. lastDataIndex = offset;
  7382. } else {
  7383. offset = length;
  7384. }
  7385. } else if (_demux_id3__WEBPACK_IMPORTED_MODULE_1__.canParse(data, offset)) {
  7386. // after a ID3.canParse, a call to ID3.getID3Data *should* always returns some data
  7387. id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_1__.getID3Data(data, offset);
  7388. id3Track.samples.push({
  7389. pts: this.lastPTS,
  7390. dts: this.lastPTS,
  7391. data: id3Data,
  7392. type: _types_demuxer__WEBPACK_IMPORTED_MODULE_2__.MetadataSchema.audioId3,
  7393. duration: Number.POSITIVE_INFINITY
  7394. });
  7395. offset += id3Data.length;
  7396. lastDataIndex = offset;
  7397. } else {
  7398. offset++;
  7399. }
  7400. if (offset === length && lastDataIndex !== length) {
  7401. var partialData = (0,_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__.sliceUint8)(data, lastDataIndex);
  7402. if (this.cachedData) {
  7403. this.cachedData = (0,_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__.appendUint8Array)(this.cachedData, partialData);
  7404. } else {
  7405. this.cachedData = partialData;
  7406. }
  7407. }
  7408. }
  7409. return {
  7410. audioTrack: track,
  7411. videoTrack: (0,_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_3__.dummyTrack)(),
  7412. id3Track: id3Track,
  7413. textTrack: (0,_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_3__.dummyTrack)()
  7414. };
  7415. };
  7416. _proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
  7417. return Promise.reject(new Error("[" + this + "] This demuxer does not support Sample-AES decryption"));
  7418. };
  7419. _proto.flush = function flush(timeOffset) {
  7420. // Parse cache in case of remaining frames.
  7421. var cachedData = this.cachedData;
  7422. if (cachedData) {
  7423. this.cachedData = null;
  7424. this.demux(cachedData, 0);
  7425. }
  7426. return {
  7427. audioTrack: this._audioTrack,
  7428. videoTrack: (0,_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_3__.dummyTrack)(),
  7429. id3Track: this._id3Track,
  7430. textTrack: (0,_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_3__.dummyTrack)()
  7431. };
  7432. };
  7433. _proto.destroy = function destroy() {};
  7434. return BaseAudioDemuxer;
  7435. }();
  7436. /**
  7437. * Initialize PTS
  7438. * <p>
  7439. * use timestamp unless it is undefined, NaN or Infinity
  7440. * </p>
  7441. */
  7442. var initPTSFn = function initPTSFn(timestamp, timeOffset, initPTS) {
  7443. if ((0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(timestamp)) {
  7444. return timestamp * 90;
  7445. }
  7446. return timeOffset * 90000 + (initPTS || 0);
  7447. };
  7448. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (BaseAudioDemuxer);
  7449. /***/ }),
  7450. /***/ "./src/demux/chunk-cache.ts":
  7451. /*!**********************************!*\
  7452. !*** ./src/demux/chunk-cache.ts ***!
  7453. \**********************************/
  7454. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  7455. "use strict";
  7456. __webpack_require__.r(__webpack_exports__);
  7457. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  7458. /* harmony export */ "default": () => (/* binding */ ChunkCache)
  7459. /* harmony export */ });
  7460. var ChunkCache = /*#__PURE__*/function () {
  7461. function ChunkCache() {
  7462. this.chunks = [];
  7463. this.dataLength = 0;
  7464. }
  7465. var _proto = ChunkCache.prototype;
  7466. _proto.push = function push(chunk) {
  7467. this.chunks.push(chunk);
  7468. this.dataLength += chunk.length;
  7469. };
  7470. _proto.flush = function flush() {
  7471. var chunks = this.chunks,
  7472. dataLength = this.dataLength;
  7473. var result;
  7474. if (!chunks.length) {
  7475. return new Uint8Array(0);
  7476. } else if (chunks.length === 1) {
  7477. result = chunks[0];
  7478. } else {
  7479. result = concatUint8Arrays(chunks, dataLength);
  7480. }
  7481. this.reset();
  7482. return result;
  7483. };
  7484. _proto.reset = function reset() {
  7485. this.chunks.length = 0;
  7486. this.dataLength = 0;
  7487. };
  7488. return ChunkCache;
  7489. }();
  7490. function concatUint8Arrays(chunks, dataLength) {
  7491. var result = new Uint8Array(dataLength);
  7492. var offset = 0;
  7493. for (var i = 0; i < chunks.length; i++) {
  7494. var chunk = chunks[i];
  7495. result.set(chunk, offset);
  7496. offset += chunk.length;
  7497. }
  7498. return result;
  7499. }
  7500. /***/ }),
  7501. /***/ "./src/demux/dummy-demuxed-track.ts":
  7502. /*!******************************************!*\
  7503. !*** ./src/demux/dummy-demuxed-track.ts ***!
  7504. \******************************************/
  7505. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  7506. "use strict";
  7507. __webpack_require__.r(__webpack_exports__);
  7508. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  7509. /* harmony export */ "dummyTrack": () => (/* binding */ dummyTrack)
  7510. /* harmony export */ });
  7511. function dummyTrack(type, inputTimeScale) {
  7512. if (type === void 0) {
  7513. type = '';
  7514. }
  7515. if (inputTimeScale === void 0) {
  7516. inputTimeScale = 90000;
  7517. }
  7518. return {
  7519. type: type,
  7520. id: -1,
  7521. pid: -1,
  7522. inputTimeScale: inputTimeScale,
  7523. sequenceNumber: -1,
  7524. samples: [],
  7525. dropped: 0
  7526. };
  7527. }
  7528. /***/ }),
  7529. /***/ "./src/demux/exp-golomb.ts":
  7530. /*!*********************************!*\
  7531. !*** ./src/demux/exp-golomb.ts ***!
  7532. \*********************************/
  7533. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  7534. "use strict";
  7535. __webpack_require__.r(__webpack_exports__);
  7536. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  7537. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  7538. /* harmony export */ });
  7539. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
  7540. /**
  7541. * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
  7542. */
  7543. var ExpGolomb = /*#__PURE__*/function () {
  7544. function ExpGolomb(data) {
  7545. this.data = void 0;
  7546. this.bytesAvailable = void 0;
  7547. this.word = void 0;
  7548. this.bitsAvailable = void 0;
  7549. this.data = data;
  7550. // the number of bytes left to examine in this.data
  7551. this.bytesAvailable = data.byteLength;
  7552. // the current word being examined
  7553. this.word = 0; // :uint
  7554. // the number of bits left to examine in the current word
  7555. this.bitsAvailable = 0; // :uint
  7556. }
  7557. // ():void
  7558. var _proto = ExpGolomb.prototype;
  7559. _proto.loadWord = function loadWord() {
  7560. var data = this.data;
  7561. var bytesAvailable = this.bytesAvailable;
  7562. var position = data.byteLength - bytesAvailable;
  7563. var workingBytes = new Uint8Array(4);
  7564. var availableBytes = Math.min(4, bytesAvailable);
  7565. if (availableBytes === 0) {
  7566. throw new Error('no bytes available');
  7567. }
  7568. workingBytes.set(data.subarray(position, position + availableBytes));
  7569. this.word = new DataView(workingBytes.buffer).getUint32(0);
  7570. // track the amount of this.data that has been processed
  7571. this.bitsAvailable = availableBytes * 8;
  7572. this.bytesAvailable -= availableBytes;
  7573. }
  7574. // (count:int):void
  7575. ;
  7576. _proto.skipBits = function skipBits(count) {
  7577. var skipBytes; // :int
  7578. count = Math.min(count, this.bytesAvailable * 8 + this.bitsAvailable);
  7579. if (this.bitsAvailable > count) {
  7580. this.word <<= count;
  7581. this.bitsAvailable -= count;
  7582. } else {
  7583. count -= this.bitsAvailable;
  7584. skipBytes = count >> 3;
  7585. count -= skipBytes << 3;
  7586. this.bytesAvailable -= skipBytes;
  7587. this.loadWord();
  7588. this.word <<= count;
  7589. this.bitsAvailable -= count;
  7590. }
  7591. }
  7592. // (size:int):uint
  7593. ;
  7594. _proto.readBits = function readBits(size) {
  7595. var bits = Math.min(this.bitsAvailable, size); // :uint
  7596. var valu = this.word >>> 32 - bits; // :uint
  7597. if (size > 32) {
  7598. _utils_logger__WEBPACK_IMPORTED_MODULE_0__.logger.error('Cannot read more than 32 bits at a time');
  7599. }
  7600. this.bitsAvailable -= bits;
  7601. if (this.bitsAvailable > 0) {
  7602. this.word <<= bits;
  7603. } else if (this.bytesAvailable > 0) {
  7604. this.loadWord();
  7605. } else {
  7606. throw new Error('no bits available');
  7607. }
  7608. bits = size - bits;
  7609. if (bits > 0 && this.bitsAvailable) {
  7610. return valu << bits | this.readBits(bits);
  7611. } else {
  7612. return valu;
  7613. }
  7614. }
  7615. // ():uint
  7616. ;
  7617. _proto.skipLZ = function skipLZ() {
  7618. var leadingZeroCount; // :uint
  7619. for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
  7620. if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) {
  7621. // the first bit of working word is 1
  7622. this.word <<= leadingZeroCount;
  7623. this.bitsAvailable -= leadingZeroCount;
  7624. return leadingZeroCount;
  7625. }
  7626. }
  7627. // we exhausted word and still have not found a 1
  7628. this.loadWord();
  7629. return leadingZeroCount + this.skipLZ();
  7630. }
  7631. // ():void
  7632. ;
  7633. _proto.skipUEG = function skipUEG() {
  7634. this.skipBits(1 + this.skipLZ());
  7635. }
  7636. // ():void
  7637. ;
  7638. _proto.skipEG = function skipEG() {
  7639. this.skipBits(1 + this.skipLZ());
  7640. }
  7641. // ():uint
  7642. ;
  7643. _proto.readUEG = function readUEG() {
  7644. var clz = this.skipLZ(); // :uint
  7645. return this.readBits(clz + 1) - 1;
  7646. }
  7647. // ():int
  7648. ;
  7649. _proto.readEG = function readEG() {
  7650. var valu = this.readUEG(); // :int
  7651. if (0x01 & valu) {
  7652. // the number is odd if the low order bit is set
  7653. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  7654. } else {
  7655. return -1 * (valu >>> 1); // divide by two then make it negative
  7656. }
  7657. }
  7658. // Some convenience functions
  7659. // :Boolean
  7660. ;
  7661. _proto.readBoolean = function readBoolean() {
  7662. return this.readBits(1) === 1;
  7663. }
  7664. // ():int
  7665. ;
  7666. _proto.readUByte = function readUByte() {
  7667. return this.readBits(8);
  7668. }
  7669. // ():int
  7670. ;
  7671. _proto.readUShort = function readUShort() {
  7672. return this.readBits(16);
  7673. }
  7674. // ():int
  7675. ;
  7676. _proto.readUInt = function readUInt() {
  7677. return this.readBits(32);
  7678. }
  7679. /**
  7680. * Advance the ExpGolomb decoder past a scaling list. The scaling
  7681. * list is optionally transmitted as part of a sequence parameter
  7682. * set and is not relevant to transmuxing.
  7683. * @param count the number of entries in this scaling list
  7684. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  7685. */;
  7686. _proto.skipScalingList = function skipScalingList(count) {
  7687. var lastScale = 8;
  7688. var nextScale = 8;
  7689. var deltaScale;
  7690. for (var j = 0; j < count; j++) {
  7691. if (nextScale !== 0) {
  7692. deltaScale = this.readEG();
  7693. nextScale = (lastScale + deltaScale + 256) % 256;
  7694. }
  7695. lastScale = nextScale === 0 ? lastScale : nextScale;
  7696. }
  7697. }
  7698. /**
  7699. * Read a sequence parameter set and return some interesting video
  7700. * properties. A sequence parameter set is the H264 metadata that
  7701. * describes the properties of upcoming video frames.
  7702. * @param data {Uint8Array} the bytes of a sequence parameter set
  7703. * @return {object} an object with configuration parsed from the
  7704. * sequence parameter set, including the dimensions of the
  7705. * associated video frames.
  7706. */;
  7707. _proto.readSPS = function readSPS() {
  7708. var frameCropLeftOffset = 0;
  7709. var frameCropRightOffset = 0;
  7710. var frameCropTopOffset = 0;
  7711. var frameCropBottomOffset = 0;
  7712. var numRefFramesInPicOrderCntCycle;
  7713. var scalingListCount;
  7714. var i;
  7715. var readUByte = this.readUByte.bind(this);
  7716. var readBits = this.readBits.bind(this);
  7717. var readUEG = this.readUEG.bind(this);
  7718. var readBoolean = this.readBoolean.bind(this);
  7719. var skipBits = this.skipBits.bind(this);
  7720. var skipEG = this.skipEG.bind(this);
  7721. var skipUEG = this.skipUEG.bind(this);
  7722. var skipScalingList = this.skipScalingList.bind(this);
  7723. readUByte();
  7724. var profileIdc = readUByte(); // profile_idc
  7725. readBits(5); // profileCompat constraint_set[0-4]_flag, u(5)
  7726. skipBits(3); // reserved_zero_3bits u(3),
  7727. readUByte(); // level_idc u(8)
  7728. skipUEG(); // seq_parameter_set_id
  7729. // some profiles have more optional data we don't need
  7730. if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
  7731. var chromaFormatIdc = readUEG();
  7732. if (chromaFormatIdc === 3) {
  7733. skipBits(1);
  7734. } // separate_colour_plane_flag
  7735. skipUEG(); // bit_depth_luma_minus8
  7736. skipUEG(); // bit_depth_chroma_minus8
  7737. skipBits(1); // qpprime_y_zero_transform_bypass_flag
  7738. if (readBoolean()) {
  7739. // seq_scaling_matrix_present_flag
  7740. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  7741. for (i = 0; i < scalingListCount; i++) {
  7742. if (readBoolean()) {
  7743. // seq_scaling_list_present_flag[ i ]
  7744. if (i < 6) {
  7745. skipScalingList(16);
  7746. } else {
  7747. skipScalingList(64);
  7748. }
  7749. }
  7750. }
  7751. }
  7752. }
  7753. skipUEG(); // log2_max_frame_num_minus4
  7754. var picOrderCntType = readUEG();
  7755. if (picOrderCntType === 0) {
  7756. readUEG(); // log2_max_pic_order_cnt_lsb_minus4
  7757. } else if (picOrderCntType === 1) {
  7758. skipBits(1); // delta_pic_order_always_zero_flag
  7759. skipEG(); // offset_for_non_ref_pic
  7760. skipEG(); // offset_for_top_to_bottom_field
  7761. numRefFramesInPicOrderCntCycle = readUEG();
  7762. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  7763. skipEG();
  7764. } // offset_for_ref_frame[ i ]
  7765. }
  7766. skipUEG(); // max_num_ref_frames
  7767. skipBits(1); // gaps_in_frame_num_value_allowed_flag
  7768. var picWidthInMbsMinus1 = readUEG();
  7769. var picHeightInMapUnitsMinus1 = readUEG();
  7770. var frameMbsOnlyFlag = readBits(1);
  7771. if (frameMbsOnlyFlag === 0) {
  7772. skipBits(1);
  7773. } // mb_adaptive_frame_field_flag
  7774. skipBits(1); // direct_8x8_inference_flag
  7775. if (readBoolean()) {
  7776. // frame_cropping_flag
  7777. frameCropLeftOffset = readUEG();
  7778. frameCropRightOffset = readUEG();
  7779. frameCropTopOffset = readUEG();
  7780. frameCropBottomOffset = readUEG();
  7781. }
  7782. var pixelRatio = [1, 1];
  7783. if (readBoolean()) {
  7784. // vui_parameters_present_flag
  7785. if (readBoolean()) {
  7786. // aspect_ratio_info_present_flag
  7787. var aspectRatioIdc = readUByte();
  7788. switch (aspectRatioIdc) {
  7789. case 1:
  7790. pixelRatio = [1, 1];
  7791. break;
  7792. case 2:
  7793. pixelRatio = [12, 11];
  7794. break;
  7795. case 3:
  7796. pixelRatio = [10, 11];
  7797. break;
  7798. case 4:
  7799. pixelRatio = [16, 11];
  7800. break;
  7801. case 5:
  7802. pixelRatio = [40, 33];
  7803. break;
  7804. case 6:
  7805. pixelRatio = [24, 11];
  7806. break;
  7807. case 7:
  7808. pixelRatio = [20, 11];
  7809. break;
  7810. case 8:
  7811. pixelRatio = [32, 11];
  7812. break;
  7813. case 9:
  7814. pixelRatio = [80, 33];
  7815. break;
  7816. case 10:
  7817. pixelRatio = [18, 11];
  7818. break;
  7819. case 11:
  7820. pixelRatio = [15, 11];
  7821. break;
  7822. case 12:
  7823. pixelRatio = [64, 33];
  7824. break;
  7825. case 13:
  7826. pixelRatio = [160, 99];
  7827. break;
  7828. case 14:
  7829. pixelRatio = [4, 3];
  7830. break;
  7831. case 15:
  7832. pixelRatio = [3, 2];
  7833. break;
  7834. case 16:
  7835. pixelRatio = [2, 1];
  7836. break;
  7837. case 255:
  7838. {
  7839. pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
  7840. break;
  7841. }
  7842. }
  7843. }
  7844. }
  7845. return {
  7846. width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
  7847. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
  7848. pixelRatio: pixelRatio
  7849. };
  7850. };
  7851. _proto.readSliceType = function readSliceType() {
  7852. // skip NALu type
  7853. this.readUByte();
  7854. // discard first_mb_in_slice
  7855. this.readUEG();
  7856. // return slice_type
  7857. return this.readUEG();
  7858. };
  7859. return ExpGolomb;
  7860. }();
  7861. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (ExpGolomb);
  7862. /***/ }),
  7863. /***/ "./src/demux/id3.ts":
  7864. /*!**************************!*\
  7865. !*** ./src/demux/id3.ts ***!
  7866. \**************************/
  7867. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  7868. "use strict";
  7869. __webpack_require__.r(__webpack_exports__);
  7870. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  7871. /* harmony export */ "canParse": () => (/* binding */ canParse),
  7872. /* harmony export */ "decodeFrame": () => (/* binding */ decodeFrame),
  7873. /* harmony export */ "getID3Data": () => (/* binding */ getID3Data),
  7874. /* harmony export */ "getID3Frames": () => (/* binding */ getID3Frames),
  7875. /* harmony export */ "getTimeStamp": () => (/* binding */ getTimeStamp),
  7876. /* harmony export */ "isFooter": () => (/* binding */ isFooter),
  7877. /* harmony export */ "isHeader": () => (/* binding */ isHeader),
  7878. /* harmony export */ "isTimeStampFrame": () => (/* binding */ isTimeStampFrame),
  7879. /* harmony export */ "testables": () => (/* binding */ testables),
  7880. /* harmony export */ "utf8ArrayToStr": () => (/* binding */ utf8ArrayToStr)
  7881. /* harmony export */ });
  7882. // breaking up those two types in order to clarify what is happening in the decoding path.
  7883. /**
  7884. * Returns true if an ID3 header can be found at offset in data
  7885. * @param {Uint8Array} data - The data to search in
  7886. * @param {number} offset - The offset at which to start searching
  7887. * @return {boolean} - True if an ID3 header is found
  7888. */
  7889. var isHeader = function isHeader(data, offset) {
  7890. /*
  7891. * http://id3.org/id3v2.3.0
  7892. * [0] = 'I'
  7893. * [1] = 'D'
  7894. * [2] = '3'
  7895. * [3,4] = {Version}
  7896. * [5] = {Flags}
  7897. * [6-9] = {ID3 Size}
  7898. *
  7899. * An ID3v2 tag can be detected with the following pattern:
  7900. * $49 44 33 yy yy xx zz zz zz zz
  7901. * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80
  7902. */
  7903. if (offset + 10 <= data.length) {
  7904. // look for 'ID3' identifier
  7905. if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) {
  7906. // check version is within range
  7907. if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {
  7908. // check size is within range
  7909. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  7910. return true;
  7911. }
  7912. }
  7913. }
  7914. }
  7915. return false;
  7916. };
  7917. /**
  7918. * Returns true if an ID3 footer can be found at offset in data
  7919. * @param {Uint8Array} data - The data to search in
  7920. * @param {number} offset - The offset at which to start searching
  7921. * @return {boolean} - True if an ID3 footer is found
  7922. */
  7923. var isFooter = function isFooter(data, offset) {
  7924. /*
  7925. * The footer is a copy of the header, but with a different identifier
  7926. */
  7927. if (offset + 10 <= data.length) {
  7928. // look for '3DI' identifier
  7929. if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) {
  7930. // check version is within range
  7931. if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {
  7932. // check size is within range
  7933. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  7934. return true;
  7935. }
  7936. }
  7937. }
  7938. }
  7939. return false;
  7940. };
  7941. /**
  7942. * Returns any adjacent ID3 tags found in data starting at offset, as one block of data
  7943. * @param {Uint8Array} data - The data to search in
  7944. * @param {number} offset - The offset at which to start searching
  7945. * @return {Uint8Array | undefined} - The block of data containing any ID3 tags found
  7946. * or *undefined* if no header is found at the starting offset
  7947. */
  7948. var getID3Data = function getID3Data(data, offset) {
  7949. var front = offset;
  7950. var length = 0;
  7951. while (isHeader(data, offset)) {
  7952. // ID3 header is 10 bytes
  7953. length += 10;
  7954. var size = readSize(data, offset + 6);
  7955. length += size;
  7956. if (isFooter(data, offset + 10)) {
  7957. // ID3 footer is 10 bytes
  7958. length += 10;
  7959. }
  7960. offset += length;
  7961. }
  7962. if (length > 0) {
  7963. return data.subarray(front, front + length);
  7964. }
  7965. return undefined;
  7966. };
  7967. var readSize = function readSize(data, offset) {
  7968. var size = 0;
  7969. size = (data[offset] & 0x7f) << 21;
  7970. size |= (data[offset + 1] & 0x7f) << 14;
  7971. size |= (data[offset + 2] & 0x7f) << 7;
  7972. size |= data[offset + 3] & 0x7f;
  7973. return size;
  7974. };
  7975. var canParse = function canParse(data, offset) {
  7976. return isHeader(data, offset) && readSize(data, offset + 6) + 10 <= data.length - offset;
  7977. };
  7978. /**
  7979. * Searches for the Elementary Stream timestamp found in the ID3 data chunk
  7980. * @param {Uint8Array} data - Block of data containing one or more ID3 tags
  7981. * @return {number | undefined} - The timestamp
  7982. */
  7983. var getTimeStamp = function getTimeStamp(data) {
  7984. var frames = getID3Frames(data);
  7985. for (var i = 0; i < frames.length; i++) {
  7986. var frame = frames[i];
  7987. if (isTimeStampFrame(frame)) {
  7988. return readTimeStamp(frame);
  7989. }
  7990. }
  7991. return undefined;
  7992. };
  7993. /**
  7994. * Returns true if the ID3 frame is an Elementary Stream timestamp frame
  7995. * @param {ID3 frame} frame
  7996. */
  7997. var isTimeStampFrame = function isTimeStampFrame(frame) {
  7998. return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp';
  7999. };
  8000. var getFrameData = function getFrameData(data) {
  8001. /*
  8002. Frame ID $xx xx xx xx (four characters)
  8003. Size $xx xx xx xx
  8004. Flags $xx xx
  8005. */
  8006. var type = String.fromCharCode(data[0], data[1], data[2], data[3]);
  8007. var size = readSize(data, 4);
  8008. // skip frame id, size, and flags
  8009. var offset = 10;
  8010. return {
  8011. type: type,
  8012. size: size,
  8013. data: data.subarray(offset, offset + size)
  8014. };
  8015. };
  8016. /**
  8017. * Returns an array of ID3 frames found in all the ID3 tags in the id3Data
  8018. * @param {Uint8Array} id3Data - The ID3 data containing one or more ID3 tags
  8019. * @return {ID3.Frame[]} - Array of ID3 frame objects
  8020. */
  8021. var getID3Frames = function getID3Frames(id3Data) {
  8022. var offset = 0;
  8023. var frames = [];
  8024. while (isHeader(id3Data, offset)) {
  8025. var size = readSize(id3Data, offset + 6);
  8026. // skip past ID3 header
  8027. offset += 10;
  8028. var end = offset + size;
  8029. // loop through frames in the ID3 tag
  8030. while (offset + 8 < end) {
  8031. var frameData = getFrameData(id3Data.subarray(offset));
  8032. var frame = decodeFrame(frameData);
  8033. if (frame) {
  8034. frames.push(frame);
  8035. }
  8036. // skip frame header and frame data
  8037. offset += frameData.size + 10;
  8038. }
  8039. if (isFooter(id3Data, offset)) {
  8040. offset += 10;
  8041. }
  8042. }
  8043. return frames;
  8044. };
  8045. var decodeFrame = function decodeFrame(frame) {
  8046. if (frame.type === 'PRIV') {
  8047. return decodePrivFrame(frame);
  8048. } else if (frame.type[0] === 'W') {
  8049. return decodeURLFrame(frame);
  8050. }
  8051. return decodeTextFrame(frame);
  8052. };
  8053. var decodePrivFrame = function decodePrivFrame(frame) {
  8054. /*
  8055. Format: <text string>\0<binary data>
  8056. */
  8057. if (frame.size < 2) {
  8058. return undefined;
  8059. }
  8060. var owner = utf8ArrayToStr(frame.data, true);
  8061. var privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
  8062. return {
  8063. key: frame.type,
  8064. info: owner,
  8065. data: privateData.buffer
  8066. };
  8067. };
  8068. var decodeTextFrame = function decodeTextFrame(frame) {
  8069. if (frame.size < 2) {
  8070. return undefined;
  8071. }
  8072. if (frame.type === 'TXXX') {
  8073. /*
  8074. Format:
  8075. [0] = {Text Encoding}
  8076. [1-?] = {Description}\0{Value}
  8077. */
  8078. var index = 1;
  8079. var description = utf8ArrayToStr(frame.data.subarray(index), true);
  8080. index += description.length + 1;
  8081. var value = utf8ArrayToStr(frame.data.subarray(index));
  8082. return {
  8083. key: frame.type,
  8084. info: description,
  8085. data: value
  8086. };
  8087. }
  8088. /*
  8089. Format:
  8090. [0] = {Text Encoding}
  8091. [1-?] = {Value}
  8092. */
  8093. var text = utf8ArrayToStr(frame.data.subarray(1));
  8094. return {
  8095. key: frame.type,
  8096. data: text
  8097. };
  8098. };
  8099. var decodeURLFrame = function decodeURLFrame(frame) {
  8100. if (frame.type === 'WXXX') {
  8101. /*
  8102. Format:
  8103. [0] = {Text Encoding}
  8104. [1-?] = {Description}\0{URL}
  8105. */
  8106. if (frame.size < 2) {
  8107. return undefined;
  8108. }
  8109. var index = 1;
  8110. var description = utf8ArrayToStr(frame.data.subarray(index), true);
  8111. index += description.length + 1;
  8112. var value = utf8ArrayToStr(frame.data.subarray(index));
  8113. return {
  8114. key: frame.type,
  8115. info: description,
  8116. data: value
  8117. };
  8118. }
  8119. /*
  8120. Format:
  8121. [0-?] = {URL}
  8122. */
  8123. var url = utf8ArrayToStr(frame.data);
  8124. return {
  8125. key: frame.type,
  8126. data: url
  8127. };
  8128. };
  8129. var readTimeStamp = function readTimeStamp(timeStampFrame) {
  8130. if (timeStampFrame.data.byteLength === 8) {
  8131. var data = new Uint8Array(timeStampFrame.data);
  8132. // timestamp is 33 bit expressed as a big-endian eight-octet number,
  8133. // with the upper 31 bits set to zero.
  8134. var pts33Bit = data[3] & 0x1;
  8135. var timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];
  8136. timestamp /= 45;
  8137. if (pts33Bit) {
  8138. timestamp += 47721858.84;
  8139. } // 2^32 / 90
  8140. return Math.round(timestamp);
  8141. }
  8142. return undefined;
  8143. };
  8144. // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197
  8145. // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
  8146. /* utf.js - UTF-8 <=> UTF-16 convertion
  8147. *
  8148. * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
  8149. * Version: 1.0
  8150. * LastModified: Dec 25 1999
  8151. * This library is free. You can redistribute it and/or modify it.
  8152. */
  8153. var utf8ArrayToStr = function utf8ArrayToStr(array, exitOnNull) {
  8154. if (exitOnNull === void 0) {
  8155. exitOnNull = false;
  8156. }
  8157. var decoder = getTextDecoder();
  8158. if (decoder) {
  8159. var decoded = decoder.decode(array);
  8160. if (exitOnNull) {
  8161. // grab up to the first null
  8162. var idx = decoded.indexOf('\0');
  8163. return idx !== -1 ? decoded.substring(0, idx) : decoded;
  8164. }
  8165. // remove any null characters
  8166. return decoded.replace(/\0/g, '');
  8167. }
  8168. var len = array.length;
  8169. var c;
  8170. var char2;
  8171. var char3;
  8172. var out = '';
  8173. var i = 0;
  8174. while (i < len) {
  8175. c = array[i++];
  8176. if (c === 0x00 && exitOnNull) {
  8177. return out;
  8178. } else if (c === 0x00 || c === 0x03) {
  8179. // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it
  8180. continue;
  8181. }
  8182. switch (c >> 4) {
  8183. case 0:
  8184. case 1:
  8185. case 2:
  8186. case 3:
  8187. case 4:
  8188. case 5:
  8189. case 6:
  8190. case 7:
  8191. // 0xxxxxxx
  8192. out += String.fromCharCode(c);
  8193. break;
  8194. case 12:
  8195. case 13:
  8196. // 110x xxxx 10xx xxxx
  8197. char2 = array[i++];
  8198. out += String.fromCharCode((c & 0x1f) << 6 | char2 & 0x3f);
  8199. break;
  8200. case 14:
  8201. // 1110 xxxx 10xx xxxx 10xx xxxx
  8202. char2 = array[i++];
  8203. char3 = array[i++];
  8204. out += String.fromCharCode((c & 0x0f) << 12 | (char2 & 0x3f) << 6 | (char3 & 0x3f) << 0);
  8205. break;
  8206. default:
  8207. }
  8208. }
  8209. return out;
  8210. };
  8211. var testables = {
  8212. decodeTextFrame: decodeTextFrame
  8213. };
  8214. var decoder;
  8215. function getTextDecoder() {
  8216. if (!decoder && typeof self.TextDecoder !== 'undefined') {
  8217. decoder = new self.TextDecoder('utf-8');
  8218. }
  8219. return decoder;
  8220. }
  8221. /***/ }),
  8222. /***/ "./src/demux/mp3demuxer.ts":
  8223. /*!*********************************!*\
  8224. !*** ./src/demux/mp3demuxer.ts ***!
  8225. \*********************************/
  8226. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  8227. "use strict";
  8228. __webpack_require__.r(__webpack_exports__);
  8229. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  8230. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  8231. /* harmony export */ });
  8232. /* harmony import */ var _base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base-audio-demuxer */ "./src/demux/base-audio-demuxer.ts");
  8233. /* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
  8234. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
  8235. /* harmony import */ var _mpegaudio__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./mpegaudio */ "./src/demux/mpegaudio.ts");
  8236. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  8237. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  8238. /**
  8239. * MP3 demuxer
  8240. */
  8241. var MP3Demuxer = /*#__PURE__*/function (_BaseAudioDemuxer) {
  8242. _inheritsLoose(MP3Demuxer, _BaseAudioDemuxer);
  8243. function MP3Demuxer() {
  8244. return _BaseAudioDemuxer.apply(this, arguments) || this;
  8245. }
  8246. var _proto = MP3Demuxer.prototype;
  8247. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  8248. _BaseAudioDemuxer.prototype.resetInitSegment.call(this, initSegment, audioCodec, videoCodec, trackDuration);
  8249. this._audioTrack = {
  8250. container: 'audio/mpeg',
  8251. type: 'audio',
  8252. id: 2,
  8253. pid: -1,
  8254. sequenceNumber: 0,
  8255. segmentCodec: 'mp3',
  8256. samples: [],
  8257. manifestCodec: audioCodec,
  8258. duration: trackDuration,
  8259. inputTimeScale: 90000,
  8260. dropped: 0
  8261. };
  8262. };
  8263. MP3Demuxer.probe = function probe(data) {
  8264. if (!data) {
  8265. return false;
  8266. }
  8267. // check if data contains ID3 timestamp and MPEG sync word
  8268. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  8269. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  8270. // More info http://www.mp3-tech.org/programmer/frame_header.html
  8271. var id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_1__.getID3Data(data, 0) || [];
  8272. var offset = id3Data.length;
  8273. for (var length = data.length; offset < length; offset++) {
  8274. if (_mpegaudio__WEBPACK_IMPORTED_MODULE_3__.probe(data, offset)) {
  8275. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.log('MPEG Audio sync word found !');
  8276. return true;
  8277. }
  8278. }
  8279. return false;
  8280. };
  8281. _proto.canParse = function canParse(data, offset) {
  8282. return _mpegaudio__WEBPACK_IMPORTED_MODULE_3__.canParse(data, offset);
  8283. };
  8284. _proto.appendFrame = function appendFrame(track, data, offset) {
  8285. if (this.basePTS === null) {
  8286. return;
  8287. }
  8288. return _mpegaudio__WEBPACK_IMPORTED_MODULE_3__.appendFrame(track, data, offset, this.basePTS, this.frameIndex);
  8289. };
  8290. return MP3Demuxer;
  8291. }(_base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__["default"]);
  8292. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (MP3Demuxer);
  8293. /***/ }),
  8294. /***/ "./src/demux/mp4demuxer.ts":
  8295. /*!*********************************!*\
  8296. !*** ./src/demux/mp4demuxer.ts ***!
  8297. \*********************************/
  8298. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  8299. "use strict";
  8300. __webpack_require__.r(__webpack_exports__);
  8301. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  8302. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  8303. /* harmony export */ });
  8304. /* harmony import */ var _Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
  8305. /* harmony import */ var _types_demuxer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../types/demuxer */ "./src/types/demuxer.ts");
  8306. /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
  8307. /* harmony import */ var _dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./dummy-demuxed-track */ "./src/demux/dummy-demuxed-track.ts");
  8308. /**
  8309. * MP4 demuxer
  8310. */
  8311. var emsgSchemePattern = /\/emsg[-/]ID3/i;
  8312. var MP4Demuxer = /*#__PURE__*/function () {
  8313. function MP4Demuxer(observer, config) {
  8314. this.remainderData = null;
  8315. this.timeOffset = 0;
  8316. this.config = void 0;
  8317. this.videoTrack = void 0;
  8318. this.audioTrack = void 0;
  8319. this.id3Track = void 0;
  8320. this.txtTrack = void 0;
  8321. this.config = config;
  8322. }
  8323. var _proto = MP4Demuxer.prototype;
  8324. _proto.resetTimeStamp = function resetTimeStamp() {};
  8325. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  8326. var videoTrack = this.videoTrack = (0,_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_3__.dummyTrack)('video', 1);
  8327. var audioTrack = this.audioTrack = (0,_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_3__.dummyTrack)('audio', 1);
  8328. var captionTrack = this.txtTrack = (0,_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_3__.dummyTrack)('text', 1);
  8329. this.id3Track = (0,_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_3__.dummyTrack)('id3', 1);
  8330. this.timeOffset = 0;
  8331. if (!initSegment || !initSegment.byteLength) {
  8332. return;
  8333. }
  8334. var initData = (0,_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_2__.parseInitSegment)(initSegment);
  8335. if (initData.video) {
  8336. var _initData$video = initData.video,
  8337. id = _initData$video.id,
  8338. timescale = _initData$video.timescale,
  8339. codec = _initData$video.codec;
  8340. videoTrack.id = id;
  8341. videoTrack.timescale = captionTrack.timescale = timescale;
  8342. videoTrack.codec = codec;
  8343. }
  8344. if (initData.audio) {
  8345. var _initData$audio = initData.audio,
  8346. _id = _initData$audio.id,
  8347. _timescale = _initData$audio.timescale,
  8348. _codec = _initData$audio.codec;
  8349. audioTrack.id = _id;
  8350. audioTrack.timescale = _timescale;
  8351. audioTrack.codec = _codec;
  8352. }
  8353. captionTrack.id = _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_2__.RemuxerTrackIdConfig.text;
  8354. videoTrack.sampleDuration = 0;
  8355. videoTrack.duration = audioTrack.duration = trackDuration;
  8356. };
  8357. _proto.resetContiguity = function resetContiguity() {};
  8358. MP4Demuxer.probe = function probe(data) {
  8359. // ensure we find a moof box in the first 16 kB
  8360. data = data.length > 16384 ? data.subarray(0, 16384) : data;
  8361. return (0,_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_2__.findBox)(data, ['moof']).length > 0;
  8362. };
  8363. _proto.demux = function demux(data, timeOffset) {
  8364. this.timeOffset = timeOffset;
  8365. // Load all data into the avc track. The CMAF remuxer will look for the data in the samples object; the rest of the fields do not matter
  8366. var videoSamples = data;
  8367. var videoTrack = this.videoTrack;
  8368. var textTrack = this.txtTrack;
  8369. if (this.config.progressive) {
  8370. // Split the bytestream into two ranges: one encompassing all data up until the start of the last moof, and everything else.
  8371. // This is done to guarantee that we're sending valid data to MSE - when demuxing progressively, we have no guarantee
  8372. // that the fetch loader gives us flush moof+mdat pairs. If we push jagged data to MSE, it will throw an exception.
  8373. if (this.remainderData) {
  8374. videoSamples = (0,_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_2__.appendUint8Array)(this.remainderData, data);
  8375. }
  8376. var segmentedData = (0,_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_2__.segmentValidRange)(videoSamples);
  8377. this.remainderData = segmentedData.remainder;
  8378. videoTrack.samples = segmentedData.valid || new Uint8Array();
  8379. } else {
  8380. videoTrack.samples = videoSamples;
  8381. }
  8382. var id3Track = this.extractID3Track(videoTrack, timeOffset);
  8383. textTrack.samples = (0,_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_2__.parseSamples)(timeOffset, videoTrack);
  8384. return {
  8385. videoTrack: videoTrack,
  8386. audioTrack: this.audioTrack,
  8387. id3Track: id3Track,
  8388. textTrack: this.txtTrack
  8389. };
  8390. };
  8391. _proto.flush = function flush() {
  8392. var timeOffset = this.timeOffset;
  8393. var videoTrack = this.videoTrack;
  8394. var textTrack = this.txtTrack;
  8395. videoTrack.samples = this.remainderData || new Uint8Array();
  8396. this.remainderData = null;
  8397. var id3Track = this.extractID3Track(videoTrack, this.timeOffset);
  8398. textTrack.samples = (0,_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_2__.parseSamples)(timeOffset, videoTrack);
  8399. return {
  8400. videoTrack: videoTrack,
  8401. audioTrack: (0,_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_3__.dummyTrack)(),
  8402. id3Track: id3Track,
  8403. textTrack: (0,_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_3__.dummyTrack)()
  8404. };
  8405. };
  8406. _proto.extractID3Track = function extractID3Track(videoTrack, timeOffset) {
  8407. var id3Track = this.id3Track;
  8408. if (videoTrack.samples.length) {
  8409. var emsgs = (0,_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_2__.findBox)(videoTrack.samples, ['emsg']);
  8410. if (emsgs) {
  8411. emsgs.forEach(function (data) {
  8412. var emsgInfo = (0,_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_2__.parseEmsg)(data);
  8413. if (emsgSchemePattern.test(emsgInfo.schemeIdUri)) {
  8414. var pts = (0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(emsgInfo.presentationTime) ? emsgInfo.presentationTime / emsgInfo.timeScale : timeOffset + emsgInfo.presentationTimeDelta / emsgInfo.timeScale;
  8415. var duration = emsgInfo.eventDuration === 0xffffffff ? Number.POSITIVE_INFINITY : emsgInfo.eventDuration / emsgInfo.timeScale;
  8416. // Safari takes anything <= 0.001 seconds and maps it to Infinity
  8417. if (duration <= 0.001) {
  8418. duration = Number.POSITIVE_INFINITY;
  8419. }
  8420. var payload = emsgInfo.payload;
  8421. id3Track.samples.push({
  8422. data: payload,
  8423. len: payload.byteLength,
  8424. dts: pts,
  8425. pts: pts,
  8426. type: _types_demuxer__WEBPACK_IMPORTED_MODULE_1__.MetadataSchema.emsg,
  8427. duration: duration
  8428. });
  8429. }
  8430. });
  8431. }
  8432. }
  8433. return id3Track;
  8434. };
  8435. _proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
  8436. return Promise.reject(new Error('The MP4 demuxer does not support SAMPLE-AES decryption'));
  8437. };
  8438. _proto.destroy = function destroy() {};
  8439. return MP4Demuxer;
  8440. }();
  8441. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (MP4Demuxer);
  8442. /***/ }),
  8443. /***/ "./src/demux/mpegaudio.ts":
  8444. /*!********************************!*\
  8445. !*** ./src/demux/mpegaudio.ts ***!
  8446. \********************************/
  8447. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  8448. "use strict";
  8449. __webpack_require__.r(__webpack_exports__);
  8450. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  8451. /* harmony export */ "appendFrame": () => (/* binding */ appendFrame),
  8452. /* harmony export */ "canParse": () => (/* binding */ canParse),
  8453. /* harmony export */ "isHeader": () => (/* binding */ isHeader),
  8454. /* harmony export */ "isHeaderPattern": () => (/* binding */ isHeaderPattern),
  8455. /* harmony export */ "parseHeader": () => (/* binding */ parseHeader),
  8456. /* harmony export */ "probe": () => (/* binding */ probe)
  8457. /* harmony export */ });
  8458. /**
  8459. * MPEG parser helper
  8460. */
  8461. var chromeVersion = null;
  8462. var BitratesMap = [32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160];
  8463. var SamplingRateMap = [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000];
  8464. var SamplesCoefficients = [
  8465. // MPEG 2.5
  8466. [0,
  8467. // Reserved
  8468. 72,
  8469. // Layer3
  8470. 144,
  8471. // Layer2
  8472. 12 // Layer1
  8473. ],
  8474. // Reserved
  8475. [0,
  8476. // Reserved
  8477. 0,
  8478. // Layer3
  8479. 0,
  8480. // Layer2
  8481. 0 // Layer1
  8482. ],
  8483. // MPEG 2
  8484. [0,
  8485. // Reserved
  8486. 72,
  8487. // Layer3
  8488. 144,
  8489. // Layer2
  8490. 12 // Layer1
  8491. ],
  8492. // MPEG 1
  8493. [0,
  8494. // Reserved
  8495. 144,
  8496. // Layer3
  8497. 144,
  8498. // Layer2
  8499. 12 // Layer1
  8500. ]];
  8501. var BytesInSlot = [0,
  8502. // Reserved
  8503. 1,
  8504. // Layer3
  8505. 1,
  8506. // Layer2
  8507. 4 // Layer1
  8508. ];
  8509. function appendFrame(track, data, offset, pts, frameIndex) {
  8510. // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference
  8511. if (offset + 24 > data.length) {
  8512. return;
  8513. }
  8514. var header = parseHeader(data, offset);
  8515. if (header && offset + header.frameLength <= data.length) {
  8516. var frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;
  8517. var stamp = pts + frameIndex * frameDuration;
  8518. var sample = {
  8519. unit: data.subarray(offset, offset + header.frameLength),
  8520. pts: stamp,
  8521. dts: stamp
  8522. };
  8523. track.config = [];
  8524. track.channelCount = header.channelCount;
  8525. track.samplerate = header.sampleRate;
  8526. track.samples.push(sample);
  8527. return {
  8528. sample: sample,
  8529. length: header.frameLength,
  8530. missing: 0
  8531. };
  8532. }
  8533. }
  8534. function parseHeader(data, offset) {
  8535. var mpegVersion = data[offset + 1] >> 3 & 3;
  8536. var mpegLayer = data[offset + 1] >> 1 & 3;
  8537. var bitRateIndex = data[offset + 2] >> 4 & 15;
  8538. var sampleRateIndex = data[offset + 2] >> 2 & 3;
  8539. if (mpegVersion !== 1 && bitRateIndex !== 0 && bitRateIndex !== 15 && sampleRateIndex !== 3) {
  8540. var paddingBit = data[offset + 2] >> 1 & 1;
  8541. var channelMode = data[offset + 3] >> 6;
  8542. var columnInBitrates = mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4;
  8543. var bitRate = BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1000;
  8544. var columnInSampleRates = mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2;
  8545. var sampleRate = SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex];
  8546. var channelCount = channelMode === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)
  8547. var sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer];
  8548. var bytesInSlot = BytesInSlot[mpegLayer];
  8549. var samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
  8550. var frameLength = Math.floor(sampleCoefficient * bitRate / sampleRate + paddingBit) * bytesInSlot;
  8551. if (chromeVersion === null) {
  8552. var userAgent = navigator.userAgent || '';
  8553. var result = userAgent.match(/Chrome\/(\d+)/i);
  8554. chromeVersion = result ? parseInt(result[1]) : 0;
  8555. }
  8556. var needChromeFix = !!chromeVersion && chromeVersion <= 87;
  8557. if (needChromeFix && mpegLayer === 2 && bitRate >= 224000 && channelMode === 0) {
  8558. // Work around bug in Chromium by setting channelMode to dual-channel (01) instead of stereo (00)
  8559. data[offset + 3] = data[offset + 3] | 0x80;
  8560. }
  8561. return {
  8562. sampleRate: sampleRate,
  8563. channelCount: channelCount,
  8564. frameLength: frameLength,
  8565. samplesPerFrame: samplesPerFrame
  8566. };
  8567. }
  8568. }
  8569. function isHeaderPattern(data, offset) {
  8570. return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;
  8571. }
  8572. function isHeader(data, offset) {
  8573. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  8574. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  8575. // More info http://www.mp3-tech.org/programmer/frame_header.html
  8576. return offset + 1 < data.length && isHeaderPattern(data, offset);
  8577. }
  8578. function canParse(data, offset) {
  8579. var headerSize = 4;
  8580. return isHeaderPattern(data, offset) && headerSize <= data.length - offset;
  8581. }
  8582. function probe(data, offset) {
  8583. // same as isHeader but we also check that MPEG frame follows last MPEG frame
  8584. // or end of data is reached
  8585. if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
  8586. // MPEG header Length
  8587. var headerLength = 4;
  8588. // MPEG frame Length
  8589. var header = parseHeader(data, offset);
  8590. var frameLength = headerLength;
  8591. if (header !== null && header !== void 0 && header.frameLength) {
  8592. frameLength = header.frameLength;
  8593. }
  8594. var newOffset = offset + frameLength;
  8595. return newOffset === data.length || isHeader(data, newOffset);
  8596. }
  8597. return false;
  8598. }
  8599. /***/ }),
  8600. /***/ "./src/demux/sample-aes.ts":
  8601. /*!*********************************!*\
  8602. !*** ./src/demux/sample-aes.ts ***!
  8603. \*********************************/
  8604. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  8605. "use strict";
  8606. __webpack_require__.r(__webpack_exports__);
  8607. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  8608. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  8609. /* harmony export */ });
  8610. /* harmony import */ var _crypt_decrypter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../crypt/decrypter */ "./src/crypt/decrypter.ts");
  8611. /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
  8612. /**
  8613. * SAMPLE-AES decrypter
  8614. */
  8615. var SampleAesDecrypter = /*#__PURE__*/function () {
  8616. function SampleAesDecrypter(observer, config, keyData) {
  8617. this.keyData = void 0;
  8618. this.decrypter = void 0;
  8619. this.keyData = keyData;
  8620. this.decrypter = new _crypt_decrypter__WEBPACK_IMPORTED_MODULE_0__["default"](config, {
  8621. removePKCS7Padding: false
  8622. });
  8623. }
  8624. var _proto = SampleAesDecrypter.prototype;
  8625. _proto.decryptBuffer = function decryptBuffer(encryptedData) {
  8626. return this.decrypter.decrypt(encryptedData, this.keyData.key.buffer, this.keyData.iv.buffer);
  8627. }
  8628. // AAC - encrypt all full 16 bytes blocks starting from offset 16
  8629. ;
  8630. _proto.decryptAacSample = function decryptAacSample(samples, sampleIndex, callback) {
  8631. var _this = this;
  8632. var curUnit = samples[sampleIndex].unit;
  8633. if (curUnit.length <= 16) {
  8634. // No encrypted portion in this sample (first 16 bytes is not
  8635. // encrypted, see https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/HLS_Sample_Encryption/Encryption/Encryption.html),
  8636. return;
  8637. }
  8638. var encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
  8639. var encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
  8640. this.decryptBuffer(encryptedBuffer).then(function (decryptedBuffer) {
  8641. var decryptedData = new Uint8Array(decryptedBuffer);
  8642. curUnit.set(decryptedData, 16);
  8643. if (!_this.decrypter.isSync()) {
  8644. _this.decryptAacSamples(samples, sampleIndex + 1, callback);
  8645. }
  8646. });
  8647. };
  8648. _proto.decryptAacSamples = function decryptAacSamples(samples, sampleIndex, callback) {
  8649. for (;; sampleIndex++) {
  8650. if (sampleIndex >= samples.length) {
  8651. callback();
  8652. return;
  8653. }
  8654. if (samples[sampleIndex].unit.length < 32) {
  8655. continue;
  8656. }
  8657. this.decryptAacSample(samples, sampleIndex, callback);
  8658. if (!this.decrypter.isSync()) {
  8659. return;
  8660. }
  8661. }
  8662. }
  8663. // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
  8664. ;
  8665. _proto.getAvcEncryptedData = function getAvcEncryptedData(decodedData) {
  8666. var encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
  8667. var encryptedData = new Int8Array(encryptedDataLen);
  8668. var outputPos = 0;
  8669. for (var inputPos = 32; inputPos < decodedData.length - 16; inputPos += 160, outputPos += 16) {
  8670. encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
  8671. }
  8672. return encryptedData;
  8673. };
  8674. _proto.getAvcDecryptedUnit = function getAvcDecryptedUnit(decodedData, decryptedData) {
  8675. var uint8DecryptedData = new Uint8Array(decryptedData);
  8676. var inputPos = 0;
  8677. for (var outputPos = 32; outputPos < decodedData.length - 16; outputPos += 160, inputPos += 16) {
  8678. decodedData.set(uint8DecryptedData.subarray(inputPos, inputPos + 16), outputPos);
  8679. }
  8680. return decodedData;
  8681. };
  8682. _proto.decryptAvcSample = function decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit) {
  8683. var _this2 = this;
  8684. var decodedData = (0,_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__.discardEPB)(curUnit.data);
  8685. var encryptedData = this.getAvcEncryptedData(decodedData);
  8686. this.decryptBuffer(encryptedData.buffer).then(function (decryptedBuffer) {
  8687. curUnit.data = _this2.getAvcDecryptedUnit(decodedData, decryptedBuffer);
  8688. if (!_this2.decrypter.isSync()) {
  8689. _this2.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
  8690. }
  8691. });
  8692. };
  8693. _proto.decryptAvcSamples = function decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
  8694. if (samples instanceof Uint8Array) {
  8695. throw new Error('Cannot decrypt samples of type Uint8Array');
  8696. }
  8697. for (;; sampleIndex++, unitIndex = 0) {
  8698. if (sampleIndex >= samples.length) {
  8699. callback();
  8700. return;
  8701. }
  8702. var curUnits = samples[sampleIndex].units;
  8703. for (;; unitIndex++) {
  8704. if (unitIndex >= curUnits.length) {
  8705. break;
  8706. }
  8707. var curUnit = curUnits[unitIndex];
  8708. if (curUnit.data.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
  8709. continue;
  8710. }
  8711. this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit);
  8712. if (!this.decrypter.isSync()) {
  8713. return;
  8714. }
  8715. }
  8716. }
  8717. };
  8718. return SampleAesDecrypter;
  8719. }();
  8720. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (SampleAesDecrypter);
  8721. /***/ }),
  8722. /***/ "./src/demux/transmuxer-interface.ts":
  8723. /*!*******************************************!*\
  8724. !*** ./src/demux/transmuxer-interface.ts ***!
  8725. \*******************************************/
  8726. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  8727. "use strict";
  8728. __webpack_require__.r(__webpack_exports__);
  8729. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  8730. /* harmony export */ "default": () => (/* binding */ TransmuxerInterface)
  8731. /* harmony export */ });
  8732. /* harmony import */ var _webworkify_webpack__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./webworkify-webpack */ "./src/demux/webworkify-webpack.js");
  8733. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
  8734. /* harmony import */ var _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/transmuxer */ "./src/demux/transmuxer.ts");
  8735. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
  8736. /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
  8737. /* harmony import */ var _utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/mediasource-helper */ "./src/utils/mediasource-helper.ts");
  8738. /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js");
  8739. /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_6__);
  8740. var MediaSource = (0,_utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__.getMediaSource)() || {
  8741. isTypeSupported: function isTypeSupported() {
  8742. return false;
  8743. }
  8744. };
  8745. var TransmuxerInterface = /*#__PURE__*/function () {
  8746. function TransmuxerInterface(hls, id, onTransmuxComplete, onFlush) {
  8747. var _this = this;
  8748. this.hls = void 0;
  8749. this.id = void 0;
  8750. this.observer = void 0;
  8751. this.frag = null;
  8752. this.part = null;
  8753. this.useWorker = void 0;
  8754. this.worker = void 0;
  8755. this.onwmsg = void 0;
  8756. this.transmuxer = null;
  8757. this.onTransmuxComplete = void 0;
  8758. this.onFlush = void 0;
  8759. var config = hls.config;
  8760. this.hls = hls;
  8761. this.id = id;
  8762. this.useWorker = !!config.enableWorker;
  8763. this.onTransmuxComplete = onTransmuxComplete;
  8764. this.onFlush = onFlush;
  8765. var forwardMessage = function forwardMessage(ev, data) {
  8766. data = data || {};
  8767. data.frag = _this.frag;
  8768. data.id = _this.id;
  8769. _this.hls.trigger(ev, data);
  8770. };
  8771. // forward events to main thread
  8772. this.observer = new eventemitter3__WEBPACK_IMPORTED_MODULE_6__.EventEmitter();
  8773. this.observer.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.FRAG_DECRYPTED, forwardMessage);
  8774. this.observer.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.ERROR, forwardMessage);
  8775. var typeSupported = {
  8776. mp4: MediaSource.isTypeSupported('video/mp4'),
  8777. mpeg: MediaSource.isTypeSupported('audio/mpeg'),
  8778. mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"')
  8779. };
  8780. // navigator.vendor is not always available in Web Worker
  8781. // refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator
  8782. var vendor = navigator.vendor;
  8783. if (this.useWorker && typeof Worker !== 'undefined') {
  8784. _utils_logger__WEBPACK_IMPORTED_MODULE_3__.logger.log('demuxing in webworker');
  8785. var worker;
  8786. try {
  8787. worker = this.worker = (0,_webworkify_webpack__WEBPACK_IMPORTED_MODULE_0__["default"])(/*require.resolve*/(/*! ../demux/transmuxer-worker.ts */ "./src/demux/transmuxer-worker.ts"));
  8788. this.onwmsg = this.onWorkerMessage.bind(this);
  8789. worker.addEventListener('message', this.onwmsg);
  8790. worker.onerror = function (event) {
  8791. _this.useWorker = false;
  8792. _utils_logger__WEBPACK_IMPORTED_MODULE_3__.logger.warn('Exception in webworker, fallback to inline');
  8793. _this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.ERROR, {
  8794. type: _errors__WEBPACK_IMPORTED_MODULE_4__.ErrorTypes.OTHER_ERROR,
  8795. details: _errors__WEBPACK_IMPORTED_MODULE_4__.ErrorDetails.INTERNAL_EXCEPTION,
  8796. fatal: false,
  8797. event: 'demuxerWorker',
  8798. error: new Error(event.message + " (" + event.filename + ":" + event.lineno + ")")
  8799. });
  8800. };
  8801. worker.postMessage({
  8802. cmd: 'init',
  8803. typeSupported: typeSupported,
  8804. vendor: vendor,
  8805. id: id,
  8806. config: JSON.stringify(config)
  8807. });
  8808. } catch (err) {
  8809. _utils_logger__WEBPACK_IMPORTED_MODULE_3__.logger.warn('Error in worker:', err);
  8810. _utils_logger__WEBPACK_IMPORTED_MODULE_3__.logger.error('Error while initializing DemuxerWorker, fallback to inline');
  8811. if (worker) {
  8812. // revoke the Object URL that was used to create transmuxer worker, so as not to leak it
  8813. self.URL.revokeObjectURL(worker.objectURL);
  8814. }
  8815. this.transmuxer = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["default"](this.observer, typeSupported, config, vendor, id);
  8816. this.worker = null;
  8817. }
  8818. } else {
  8819. this.transmuxer = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["default"](this.observer, typeSupported, config, vendor, id);
  8820. }
  8821. }
  8822. var _proto = TransmuxerInterface.prototype;
  8823. _proto.destroy = function destroy() {
  8824. var w = this.worker;
  8825. if (w) {
  8826. w.removeEventListener('message', this.onwmsg);
  8827. w.terminate();
  8828. this.worker = null;
  8829. this.onwmsg = undefined;
  8830. } else {
  8831. var transmuxer = this.transmuxer;
  8832. if (transmuxer) {
  8833. transmuxer.destroy();
  8834. this.transmuxer = null;
  8835. }
  8836. }
  8837. var observer = this.observer;
  8838. if (observer) {
  8839. observer.removeAllListeners();
  8840. }
  8841. this.frag = null;
  8842. // @ts-ignore
  8843. this.observer = null;
  8844. // @ts-ignore
  8845. this.hls = null;
  8846. };
  8847. _proto.push = function push(data, initSegmentData, audioCodec, videoCodec, frag, part, duration, accurateTimeOffset, chunkMeta, defaultInitPTS) {
  8848. var _frag$initSegment,
  8849. _lastFrag$initSegment,
  8850. _this2 = this;
  8851. chunkMeta.transmuxing.start = self.performance.now();
  8852. var transmuxer = this.transmuxer,
  8853. worker = this.worker;
  8854. var timeOffset = part ? part.start : frag.start;
  8855. // TODO: push "clear-lead" decrypt data for unencrypted fragments in streams with encrypted ones
  8856. var decryptdata = frag.decryptdata;
  8857. var lastFrag = this.frag;
  8858. var discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
  8859. var trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level);
  8860. var snDiff = lastFrag ? chunkMeta.sn - lastFrag.sn : -1;
  8861. var partDiff = this.part ? chunkMeta.part - this.part.index : -1;
  8862. var progressive = snDiff === 0 && chunkMeta.id > 1 && chunkMeta.id === (lastFrag === null || lastFrag === void 0 ? void 0 : lastFrag.stats.chunkCount);
  8863. var contiguous = !trackSwitch && (snDiff === 1 || snDiff === 0 && (partDiff === 1 || progressive && partDiff <= 0));
  8864. var now = self.performance.now();
  8865. if (trackSwitch || snDiff || frag.stats.parsing.start === 0) {
  8866. frag.stats.parsing.start = now;
  8867. }
  8868. if (part && (partDiff || !contiguous)) {
  8869. part.stats.parsing.start = now;
  8870. }
  8871. var initSegmentChange = !(lastFrag && ((_frag$initSegment = frag.initSegment) === null || _frag$initSegment === void 0 ? void 0 : _frag$initSegment.url) === ((_lastFrag$initSegment = lastFrag.initSegment) === null || _lastFrag$initSegment === void 0 ? void 0 : _lastFrag$initSegment.url));
  8872. var state = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__.TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange);
  8873. if (!contiguous || discontinuity || initSegmentChange) {
  8874. _utils_logger__WEBPACK_IMPORTED_MODULE_3__.logger.log("[transmuxer-interface, " + frag.type + "]: Starting new transmux session for sn: " + chunkMeta.sn + " p: " + chunkMeta.part + " level: " + chunkMeta.level + " id: " + chunkMeta.id + "\n discontinuity: " + discontinuity + "\n trackSwitch: " + trackSwitch + "\n contiguous: " + contiguous + "\n accurateTimeOffset: " + accurateTimeOffset + "\n timeOffset: " + timeOffset + "\n initSegmentChange: " + initSegmentChange);
  8875. var config = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__.TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPTS);
  8876. this.configureTransmuxer(config);
  8877. }
  8878. this.frag = frag;
  8879. this.part = part;
  8880. // Frags with sn of 'initSegment' are not transmuxed
  8881. if (worker) {
  8882. // post fragment payload as transferable objects for ArrayBuffer (no copy)
  8883. worker.postMessage({
  8884. cmd: 'demux',
  8885. data: data,
  8886. decryptdata: decryptdata,
  8887. chunkMeta: chunkMeta,
  8888. state: state
  8889. }, data instanceof ArrayBuffer ? [data] : []);
  8890. } else if (transmuxer) {
  8891. var _transmuxResult = transmuxer.push(data, decryptdata, chunkMeta, state);
  8892. if ((0,_demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__.isPromise)(_transmuxResult)) {
  8893. _transmuxResult.then(function (data) {
  8894. _this2.handleTransmuxComplete(data);
  8895. });
  8896. } else {
  8897. this.handleTransmuxComplete(_transmuxResult);
  8898. }
  8899. }
  8900. };
  8901. _proto.flush = function flush(chunkMeta) {
  8902. var _this3 = this;
  8903. chunkMeta.transmuxing.start = self.performance.now();
  8904. var transmuxer = this.transmuxer,
  8905. worker = this.worker;
  8906. if (worker) {
  8907. worker.postMessage({
  8908. cmd: 'flush',
  8909. chunkMeta: chunkMeta
  8910. });
  8911. } else if (transmuxer) {
  8912. var _transmuxResult2 = transmuxer.flush(chunkMeta);
  8913. if ((0,_demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__.isPromise)(_transmuxResult2)) {
  8914. _transmuxResult2.then(function (data) {
  8915. _this3.handleFlushResult(data, chunkMeta);
  8916. });
  8917. } else {
  8918. this.handleFlushResult(_transmuxResult2, chunkMeta);
  8919. }
  8920. }
  8921. };
  8922. _proto.handleFlushResult = function handleFlushResult(results, chunkMeta) {
  8923. var _this4 = this;
  8924. results.forEach(function (result) {
  8925. _this4.handleTransmuxComplete(result);
  8926. });
  8927. this.onFlush(chunkMeta);
  8928. };
  8929. _proto.onWorkerMessage = function onWorkerMessage(ev) {
  8930. var data = ev.data;
  8931. var hls = this.hls;
  8932. switch (data.event) {
  8933. case 'init':
  8934. {
  8935. // revoke the Object URL that was used to create transmuxer worker, so as not to leak it
  8936. self.URL.revokeObjectURL(this.worker.objectURL);
  8937. break;
  8938. }
  8939. case 'transmuxComplete':
  8940. {
  8941. this.handleTransmuxComplete(data.data);
  8942. break;
  8943. }
  8944. case 'flush':
  8945. {
  8946. this.onFlush(data.data);
  8947. break;
  8948. }
  8949. // pass logs from the worker thread to the main logger
  8950. case 'workerLog':
  8951. if (_utils_logger__WEBPACK_IMPORTED_MODULE_3__.logger[data.data.logType]) {
  8952. _utils_logger__WEBPACK_IMPORTED_MODULE_3__.logger[data.data.logType](data.data.message);
  8953. }
  8954. break;
  8955. default:
  8956. {
  8957. data.data = data.data || {};
  8958. data.data.frag = this.frag;
  8959. data.data.id = this.id;
  8960. hls.trigger(data.event, data.data);
  8961. break;
  8962. }
  8963. }
  8964. };
  8965. _proto.configureTransmuxer = function configureTransmuxer(config) {
  8966. var worker = this.worker,
  8967. transmuxer = this.transmuxer;
  8968. if (worker) {
  8969. worker.postMessage({
  8970. cmd: 'configure',
  8971. config: config
  8972. });
  8973. } else if (transmuxer) {
  8974. transmuxer.configure(config);
  8975. }
  8976. };
  8977. _proto.handleTransmuxComplete = function handleTransmuxComplete(result) {
  8978. result.chunkMeta.transmuxing.end = self.performance.now();
  8979. this.onTransmuxComplete(result);
  8980. };
  8981. return TransmuxerInterface;
  8982. }();
  8983. /***/ }),
  8984. /***/ "./src/demux/transmuxer-worker.ts":
  8985. /*!****************************************!*\
  8986. !*** ./src/demux/transmuxer-worker.ts ***!
  8987. \****************************************/
  8988. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  8989. "use strict";
  8990. __webpack_require__.r(__webpack_exports__);
  8991. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  8992. /* harmony export */ "default": () => (/* binding */ TransmuxerWorker)
  8993. /* harmony export */ });
  8994. /* harmony import */ var _demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../demux/transmuxer */ "./src/demux/transmuxer.ts");
  8995. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
  8996. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
  8997. /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js");
  8998. /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_3__);
  8999. function TransmuxerWorker(self) {
  9000. var observer = new eventemitter3__WEBPACK_IMPORTED_MODULE_3__.EventEmitter();
  9001. var forwardMessage = function forwardMessage(ev, data) {
  9002. self.postMessage({
  9003. event: ev,
  9004. data: data
  9005. });
  9006. };
  9007. // forward events to main thread
  9008. observer.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.FRAG_DECRYPTED, forwardMessage);
  9009. observer.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.ERROR, forwardMessage);
  9010. // forward logger events to main thread
  9011. var forwardWorkerLogs = function forwardWorkerLogs() {
  9012. var _loop = function _loop(logFn) {
  9013. var func = function func(message) {
  9014. forwardMessage('workerLog', {
  9015. logType: logFn,
  9016. message: message
  9017. });
  9018. };
  9019. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger[logFn] = func;
  9020. };
  9021. for (var logFn in _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger) {
  9022. _loop(logFn);
  9023. }
  9024. };
  9025. self.addEventListener('message', function (ev) {
  9026. var data = ev.data;
  9027. switch (data.cmd) {
  9028. case 'init':
  9029. {
  9030. var config = JSON.parse(data.config);
  9031. self.transmuxer = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__["default"](observer, data.typeSupported, config, data.vendor, data.id);
  9032. (0,_utils_logger__WEBPACK_IMPORTED_MODULE_2__.enableLogs)(config.debug, data.id);
  9033. forwardWorkerLogs();
  9034. forwardMessage('init', null);
  9035. break;
  9036. }
  9037. case 'configure':
  9038. {
  9039. self.transmuxer.configure(data.config);
  9040. break;
  9041. }
  9042. case 'demux':
  9043. {
  9044. var transmuxResult = self.transmuxer.push(data.data, data.decryptdata, data.chunkMeta, data.state);
  9045. if ((0,_demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__.isPromise)(transmuxResult)) {
  9046. transmuxResult.then(function (data) {
  9047. emitTransmuxComplete(self, data);
  9048. });
  9049. } else {
  9050. emitTransmuxComplete(self, transmuxResult);
  9051. }
  9052. break;
  9053. }
  9054. case 'flush':
  9055. {
  9056. var id = data.chunkMeta;
  9057. var _transmuxResult = self.transmuxer.flush(id);
  9058. if ((0,_demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__.isPromise)(_transmuxResult)) {
  9059. _transmuxResult.then(function (results) {
  9060. handleFlushResult(self, results, id);
  9061. });
  9062. } else {
  9063. handleFlushResult(self, _transmuxResult, id);
  9064. }
  9065. break;
  9066. }
  9067. default:
  9068. break;
  9069. }
  9070. });
  9071. }
  9072. function emitTransmuxComplete(self, transmuxResult) {
  9073. if (isEmptyResult(transmuxResult.remuxResult)) {
  9074. return false;
  9075. }
  9076. var transferable = [];
  9077. var _transmuxResult$remux = transmuxResult.remuxResult,
  9078. audio = _transmuxResult$remux.audio,
  9079. video = _transmuxResult$remux.video;
  9080. if (audio) {
  9081. addToTransferable(transferable, audio);
  9082. }
  9083. if (video) {
  9084. addToTransferable(transferable, video);
  9085. }
  9086. self.postMessage({
  9087. event: 'transmuxComplete',
  9088. data: transmuxResult
  9089. }, transferable);
  9090. return true;
  9091. }
  9092. // Converts data to a transferable object https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast)
  9093. // in order to minimize message passing overhead
  9094. function addToTransferable(transferable, track) {
  9095. if (track.data1) {
  9096. transferable.push(track.data1.buffer);
  9097. }
  9098. if (track.data2) {
  9099. transferable.push(track.data2.buffer);
  9100. }
  9101. }
  9102. function handleFlushResult(self, results, chunkMeta) {
  9103. var parsed = results.reduce(function (parsed, result) {
  9104. return emitTransmuxComplete(self, result) || parsed;
  9105. }, false);
  9106. if (!parsed) {
  9107. // Emit at least one "transmuxComplete" message even if media is not found to update stream-controller state to PARSING
  9108. self.postMessage({
  9109. event: 'transmuxComplete',
  9110. data: results[0]
  9111. });
  9112. }
  9113. self.postMessage({
  9114. event: 'flush',
  9115. data: chunkMeta
  9116. });
  9117. }
  9118. function isEmptyResult(remuxResult) {
  9119. return !remuxResult.audio && !remuxResult.video && !remuxResult.text && !remuxResult.id3 && !remuxResult.initSegment;
  9120. }
  9121. /***/ }),
  9122. /***/ "./src/demux/transmuxer.ts":
  9123. /*!*********************************!*\
  9124. !*** ./src/demux/transmuxer.ts ***!
  9125. \*********************************/
  9126. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  9127. "use strict";
  9128. __webpack_require__.r(__webpack_exports__);
  9129. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  9130. /* harmony export */ "TransmuxConfig": () => (/* binding */ TransmuxConfig),
  9131. /* harmony export */ "TransmuxState": () => (/* binding */ TransmuxState),
  9132. /* harmony export */ "default": () => (/* binding */ Transmuxer),
  9133. /* harmony export */ "isPromise": () => (/* binding */ isPromise)
  9134. /* harmony export */ });
  9135. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
  9136. /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
  9137. /* harmony import */ var _crypt_decrypter__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../crypt/decrypter */ "./src/crypt/decrypter.ts");
  9138. /* harmony import */ var _demux_aacdemuxer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../demux/aacdemuxer */ "./src/demux/aacdemuxer.ts");
  9139. /* harmony import */ var _demux_mp4demuxer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../demux/mp4demuxer */ "./src/demux/mp4demuxer.ts");
  9140. /* harmony import */ var _demux_tsdemuxer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../demux/tsdemuxer */ "./src/demux/tsdemuxer.ts");
  9141. /* harmony import */ var _demux_mp3demuxer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../demux/mp3demuxer */ "./src/demux/mp3demuxer.ts");
  9142. /* harmony import */ var _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../remux/mp4-remuxer */ "./src/remux/mp4-remuxer.ts");
  9143. /* harmony import */ var _remux_passthrough_remuxer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../remux/passthrough-remuxer */ "./src/remux/passthrough-remuxer.ts");
  9144. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
  9145. var now;
  9146. // performance.now() not available on WebWorker, at least on Safari Desktop
  9147. try {
  9148. now = self.performance.now.bind(self.performance);
  9149. } catch (err) {
  9150. _utils_logger__WEBPACK_IMPORTED_MODULE_9__.logger.debug('Unable to use Performance API on this environment');
  9151. now = self.Date.now;
  9152. }
  9153. var muxConfig = [{
  9154. demux: _demux_tsdemuxer__WEBPACK_IMPORTED_MODULE_5__["default"],
  9155. remux: _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__["default"]
  9156. }, {
  9157. demux: _demux_mp4demuxer__WEBPACK_IMPORTED_MODULE_4__["default"],
  9158. remux: _remux_passthrough_remuxer__WEBPACK_IMPORTED_MODULE_8__["default"]
  9159. }, {
  9160. demux: _demux_aacdemuxer__WEBPACK_IMPORTED_MODULE_3__["default"],
  9161. remux: _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__["default"]
  9162. }, {
  9163. demux: _demux_mp3demuxer__WEBPACK_IMPORTED_MODULE_6__["default"],
  9164. remux: _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__["default"]
  9165. }];
  9166. var Transmuxer = /*#__PURE__*/function () {
  9167. function Transmuxer(observer, typeSupported, config, vendor, id) {
  9168. this.observer = void 0;
  9169. this.typeSupported = void 0;
  9170. this.config = void 0;
  9171. this.vendor = void 0;
  9172. this.id = void 0;
  9173. this.demuxer = void 0;
  9174. this.remuxer = void 0;
  9175. this.decrypter = void 0;
  9176. this.probe = void 0;
  9177. this.decryptionPromise = null;
  9178. this.transmuxConfig = void 0;
  9179. this.currentTransmuxState = void 0;
  9180. this.observer = observer;
  9181. this.typeSupported = typeSupported;
  9182. this.config = config;
  9183. this.vendor = vendor;
  9184. this.id = id;
  9185. }
  9186. var _proto = Transmuxer.prototype;
  9187. _proto.configure = function configure(transmuxConfig) {
  9188. this.transmuxConfig = transmuxConfig;
  9189. if (this.decrypter) {
  9190. this.decrypter.reset();
  9191. }
  9192. };
  9193. _proto.push = function push(data, decryptdata, chunkMeta, state) {
  9194. var _this = this;
  9195. var stats = chunkMeta.transmuxing;
  9196. stats.executeStart = now();
  9197. var uintData = new Uint8Array(data);
  9198. var currentTransmuxState = this.currentTransmuxState,
  9199. transmuxConfig = this.transmuxConfig;
  9200. if (state) {
  9201. this.currentTransmuxState = state;
  9202. }
  9203. var _ref = state || currentTransmuxState,
  9204. contiguous = _ref.contiguous,
  9205. discontinuity = _ref.discontinuity,
  9206. trackSwitch = _ref.trackSwitch,
  9207. accurateTimeOffset = _ref.accurateTimeOffset,
  9208. timeOffset = _ref.timeOffset,
  9209. initSegmentChange = _ref.initSegmentChange;
  9210. var audioCodec = transmuxConfig.audioCodec,
  9211. videoCodec = transmuxConfig.videoCodec,
  9212. defaultInitPts = transmuxConfig.defaultInitPts,
  9213. duration = transmuxConfig.duration,
  9214. initSegmentData = transmuxConfig.initSegmentData;
  9215. // Reset muxers before probing to ensure that their state is clean, even if flushing occurs before a successful probe
  9216. if (discontinuity || trackSwitch || initSegmentChange) {
  9217. this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration);
  9218. }
  9219. if (discontinuity || initSegmentChange) {
  9220. this.resetInitialTimestamp(defaultInitPts);
  9221. }
  9222. if (!contiguous) {
  9223. this.resetContiguity();
  9224. }
  9225. var keyData = getEncryptionType(uintData, decryptdata);
  9226. if (keyData && keyData.method === 'AES-128') {
  9227. var decrypter = this.getDecrypter();
  9228. // Software decryption is synchronous; webCrypto is not
  9229. if (decrypter.isSync()) {
  9230. // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
  9231. // data is handled in the flush() call
  9232. var decryptedData = decrypter.softwareDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer);
  9233. if (!decryptedData) {
  9234. stats.executeEnd = now();
  9235. return emptyResult(chunkMeta);
  9236. }
  9237. uintData = new Uint8Array(decryptedData);
  9238. } else {
  9239. this.decryptionPromise = decrypter.webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer).then(function (decryptedData) {
  9240. // Calling push here is important; if flush() is called while this is still resolving, this ensures that
  9241. // the decrypted data has been transmuxed
  9242. var result = _this.push(decryptedData, null, chunkMeta);
  9243. _this.decryptionPromise = null;
  9244. return result;
  9245. });
  9246. return this.decryptionPromise;
  9247. }
  9248. }
  9249. if (this.needsProbing(uintData, discontinuity, trackSwitch)) {
  9250. this.configureTransmuxer(uintData, transmuxConfig);
  9251. }
  9252. var result = this.transmux(uintData, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  9253. var currentState = this.currentTransmuxState;
  9254. currentState.contiguous = true;
  9255. currentState.discontinuity = false;
  9256. currentState.trackSwitch = false;
  9257. stats.executeEnd = now();
  9258. return result;
  9259. }
  9260. // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type)
  9261. ;
  9262. _proto.flush = function flush(chunkMeta) {
  9263. var _this2 = this;
  9264. var stats = chunkMeta.transmuxing;
  9265. stats.executeStart = now();
  9266. var decrypter = this.decrypter,
  9267. currentTransmuxState = this.currentTransmuxState,
  9268. decryptionPromise = this.decryptionPromise;
  9269. if (decryptionPromise) {
  9270. // Upon resolution, the decryption promise calls push() and returns its TransmuxerResult up the stack. Therefore
  9271. // only flushing is required for async decryption
  9272. return decryptionPromise.then(function () {
  9273. return _this2.flush(chunkMeta);
  9274. });
  9275. }
  9276. var transmuxResults = [];
  9277. var timeOffset = currentTransmuxState.timeOffset;
  9278. if (decrypter) {
  9279. // The decrypter may have data cached, which needs to be demuxed. In this case we'll have two TransmuxResults
  9280. // This happens in the case that we receive only 1 push call for a segment (either for non-progressive downloads,
  9281. // or for progressive downloads with small segments)
  9282. var decryptedData = decrypter.flush();
  9283. if (decryptedData) {
  9284. // Push always returns a TransmuxerResult if decryptdata is null
  9285. transmuxResults.push(this.push(decryptedData, null, chunkMeta));
  9286. }
  9287. }
  9288. var demuxer = this.demuxer,
  9289. remuxer = this.remuxer;
  9290. if (!demuxer || !remuxer) {
  9291. // If probing failed, then Hls.js has been given content its not able to handle
  9292. this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_0__.Events.ERROR, _events__WEBPACK_IMPORTED_MODULE_0__.Events.ERROR, {
  9293. type: _errors__WEBPACK_IMPORTED_MODULE_1__.ErrorTypes.MEDIA_ERROR,
  9294. details: _errors__WEBPACK_IMPORTED_MODULE_1__.ErrorDetails.FRAG_PARSING_ERROR,
  9295. fatal: true,
  9296. reason: 'no demux matching with content found'
  9297. });
  9298. stats.executeEnd = now();
  9299. return [emptyResult(chunkMeta)];
  9300. }
  9301. var demuxResultOrPromise = demuxer.flush(timeOffset);
  9302. if (isPromise(demuxResultOrPromise)) {
  9303. // Decrypt final SAMPLE-AES samples
  9304. return demuxResultOrPromise.then(function (demuxResult) {
  9305. _this2.flushRemux(transmuxResults, demuxResult, chunkMeta);
  9306. return transmuxResults;
  9307. });
  9308. }
  9309. this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta);
  9310. return transmuxResults;
  9311. };
  9312. _proto.flushRemux = function flushRemux(transmuxResults, demuxResult, chunkMeta) {
  9313. var audioTrack = demuxResult.audioTrack,
  9314. videoTrack = demuxResult.videoTrack,
  9315. id3Track = demuxResult.id3Track,
  9316. textTrack = demuxResult.textTrack;
  9317. var _this$currentTransmux = this.currentTransmuxState,
  9318. accurateTimeOffset = _this$currentTransmux.accurateTimeOffset,
  9319. timeOffset = _this$currentTransmux.timeOffset;
  9320. _utils_logger__WEBPACK_IMPORTED_MODULE_9__.logger.log("[transmuxer.ts]: Flushed fragment " + chunkMeta.sn + (chunkMeta.part > -1 ? ' p: ' + chunkMeta.part : '') + " of level " + chunkMeta.level);
  9321. var remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, true, this.id);
  9322. transmuxResults.push({
  9323. remuxResult: remuxResult,
  9324. chunkMeta: chunkMeta
  9325. });
  9326. chunkMeta.transmuxing.executeEnd = now();
  9327. };
  9328. _proto.resetInitialTimestamp = function resetInitialTimestamp(defaultInitPts) {
  9329. var demuxer = this.demuxer,
  9330. remuxer = this.remuxer;
  9331. if (!demuxer || !remuxer) {
  9332. return;
  9333. }
  9334. demuxer.resetTimeStamp(defaultInitPts);
  9335. remuxer.resetTimeStamp(defaultInitPts);
  9336. };
  9337. _proto.resetContiguity = function resetContiguity() {
  9338. var demuxer = this.demuxer,
  9339. remuxer = this.remuxer;
  9340. if (!demuxer || !remuxer) {
  9341. return;
  9342. }
  9343. demuxer.resetContiguity();
  9344. remuxer.resetNextTimestamp();
  9345. };
  9346. _proto.resetInitSegment = function resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration) {
  9347. var demuxer = this.demuxer,
  9348. remuxer = this.remuxer;
  9349. if (!demuxer || !remuxer) {
  9350. return;
  9351. }
  9352. demuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration);
  9353. remuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec);
  9354. };
  9355. _proto.destroy = function destroy() {
  9356. if (this.demuxer) {
  9357. this.demuxer.destroy();
  9358. this.demuxer = undefined;
  9359. }
  9360. if (this.remuxer) {
  9361. this.remuxer.destroy();
  9362. this.remuxer = undefined;
  9363. }
  9364. };
  9365. _proto.transmux = function transmux(data, keyData, timeOffset, accurateTimeOffset, chunkMeta) {
  9366. var result;
  9367. if (keyData && keyData.method === 'SAMPLE-AES') {
  9368. result = this.transmuxSampleAes(data, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  9369. } else {
  9370. result = this.transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta);
  9371. }
  9372. return result;
  9373. };
  9374. _proto.transmuxUnencrypted = function transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta) {
  9375. var _demux = this.demuxer.demux(data, timeOffset, false, !this.config.progressive),
  9376. audioTrack = _demux.audioTrack,
  9377. videoTrack = _demux.videoTrack,
  9378. id3Track = _demux.id3Track,
  9379. textTrack = _demux.textTrack;
  9380. var remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, false, this.id);
  9381. return {
  9382. remuxResult: remuxResult,
  9383. chunkMeta: chunkMeta
  9384. };
  9385. };
  9386. _proto.transmuxSampleAes = function transmuxSampleAes(data, decryptData, timeOffset, accurateTimeOffset, chunkMeta) {
  9387. var _this3 = this;
  9388. return this.demuxer.demuxSampleAes(data, decryptData, timeOffset).then(function (demuxResult) {
  9389. var remuxResult = _this3.remuxer.remux(demuxResult.audioTrack, demuxResult.videoTrack, demuxResult.id3Track, demuxResult.textTrack, timeOffset, accurateTimeOffset, false, _this3.id);
  9390. return {
  9391. remuxResult: remuxResult,
  9392. chunkMeta: chunkMeta
  9393. };
  9394. });
  9395. };
  9396. _proto.configureTransmuxer = function configureTransmuxer(data, transmuxConfig) {
  9397. var config = this.config,
  9398. observer = this.observer,
  9399. typeSupported = this.typeSupported,
  9400. vendor = this.vendor;
  9401. var audioCodec = transmuxConfig.audioCodec,
  9402. defaultInitPts = transmuxConfig.defaultInitPts,
  9403. duration = transmuxConfig.duration,
  9404. initSegmentData = transmuxConfig.initSegmentData,
  9405. videoCodec = transmuxConfig.videoCodec;
  9406. // probe for content type
  9407. var mux;
  9408. for (var i = 0, len = muxConfig.length; i < len; i++) {
  9409. if (muxConfig[i].demux.probe(data)) {
  9410. mux = muxConfig[i];
  9411. break;
  9412. }
  9413. }
  9414. if (!mux) {
  9415. // If probing previous configs fail, use mp4 passthrough
  9416. _utils_logger__WEBPACK_IMPORTED_MODULE_9__.logger.warn('Failed to find demuxer by probing frag, treating as mp4 passthrough');
  9417. mux = {
  9418. demux: _demux_mp4demuxer__WEBPACK_IMPORTED_MODULE_4__["default"],
  9419. remux: _remux_passthrough_remuxer__WEBPACK_IMPORTED_MODULE_8__["default"]
  9420. };
  9421. }
  9422. // so let's check that current remuxer and demuxer are still valid
  9423. var demuxer = this.demuxer;
  9424. var remuxer = this.remuxer;
  9425. var Remuxer = mux.remux;
  9426. var Demuxer = mux.demux;
  9427. if (!remuxer || !(remuxer instanceof Remuxer)) {
  9428. this.remuxer = new Remuxer(observer, config, typeSupported, vendor);
  9429. }
  9430. if (!demuxer || !(demuxer instanceof Demuxer)) {
  9431. this.demuxer = new Demuxer(observer, config, typeSupported);
  9432. this.probe = Demuxer.probe;
  9433. }
  9434. // Ensure that muxers are always initialized with an initSegment
  9435. this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration);
  9436. this.resetInitialTimestamp(defaultInitPts);
  9437. };
  9438. _proto.needsProbing = function needsProbing(data, discontinuity, trackSwitch) {
  9439. // in case of continuity change, or track switch
  9440. // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)
  9441. return !this.demuxer || !this.remuxer || discontinuity || trackSwitch;
  9442. };
  9443. _proto.getDecrypter = function getDecrypter() {
  9444. var decrypter = this.decrypter;
  9445. if (!decrypter) {
  9446. decrypter = this.decrypter = new _crypt_decrypter__WEBPACK_IMPORTED_MODULE_2__["default"](this.config);
  9447. }
  9448. return decrypter;
  9449. };
  9450. return Transmuxer;
  9451. }();
  9452. function getEncryptionType(data, decryptData) {
  9453. var encryptionType = null;
  9454. if (data.byteLength > 0 && decryptData != null && decryptData.key != null && decryptData.iv !== null && decryptData.method != null) {
  9455. encryptionType = decryptData;
  9456. }
  9457. return encryptionType;
  9458. }
  9459. var emptyResult = function emptyResult(chunkMeta) {
  9460. return {
  9461. remuxResult: {},
  9462. chunkMeta: chunkMeta
  9463. };
  9464. };
  9465. function isPromise(p) {
  9466. return 'then' in p && p.then instanceof Function;
  9467. }
  9468. var TransmuxConfig = function TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPts) {
  9469. this.audioCodec = void 0;
  9470. this.videoCodec = void 0;
  9471. this.initSegmentData = void 0;
  9472. this.duration = void 0;
  9473. this.defaultInitPts = void 0;
  9474. this.audioCodec = audioCodec;
  9475. this.videoCodec = videoCodec;
  9476. this.initSegmentData = initSegmentData;
  9477. this.duration = duration;
  9478. this.defaultInitPts = defaultInitPts;
  9479. };
  9480. var TransmuxState = function TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange) {
  9481. this.discontinuity = void 0;
  9482. this.contiguous = void 0;
  9483. this.accurateTimeOffset = void 0;
  9484. this.trackSwitch = void 0;
  9485. this.timeOffset = void 0;
  9486. this.initSegmentChange = void 0;
  9487. this.discontinuity = discontinuity;
  9488. this.contiguous = contiguous;
  9489. this.accurateTimeOffset = accurateTimeOffset;
  9490. this.trackSwitch = trackSwitch;
  9491. this.timeOffset = timeOffset;
  9492. this.initSegmentChange = initSegmentChange;
  9493. };
  9494. /***/ }),
  9495. /***/ "./src/demux/tsdemuxer.ts":
  9496. /*!********************************!*\
  9497. !*** ./src/demux/tsdemuxer.ts ***!
  9498. \********************************/
  9499. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  9500. "use strict";
  9501. __webpack_require__.r(__webpack_exports__);
  9502. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  9503. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  9504. /* harmony export */ });
  9505. /* harmony import */ var _adts__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./adts */ "./src/demux/adts.ts");
  9506. /* harmony import */ var _mpegaudio__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./mpegaudio */ "./src/demux/mpegaudio.ts");
  9507. /* harmony import */ var _exp_golomb__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./exp-golomb */ "./src/demux/exp-golomb.ts");
  9508. /* harmony import */ var _sample_aes__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./sample-aes */ "./src/demux/sample-aes.ts");
  9509. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../events */ "./src/events.ts");
  9510. /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
  9511. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
  9512. /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
  9513. /* harmony import */ var _types_demuxer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../types/demuxer */ "./src/types/demuxer.ts");
  9514. function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
  9515. /**
  9516. * highly optimized TS demuxer:
  9517. * parse PAT, PMT
  9518. * extract PES packet from audio and video PIDs
  9519. * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet
  9520. * trigger the remuxer upon parsing completion
  9521. * 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.
  9522. * it also controls the remuxing process :
  9523. * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.
  9524. */
  9525. var PACKET_LENGTH = 188;
  9526. var TSDemuxer = /*#__PURE__*/function () {
  9527. function TSDemuxer(observer, config, typeSupported) {
  9528. this.observer = void 0;
  9529. this.config = void 0;
  9530. this.typeSupported = void 0;
  9531. this.sampleAes = null;
  9532. this.pmtParsed = false;
  9533. this.audioCodec = void 0;
  9534. this.videoCodec = void 0;
  9535. this._duration = 0;
  9536. this._pmtId = -1;
  9537. this._avcTrack = void 0;
  9538. this._audioTrack = void 0;
  9539. this._id3Track = void 0;
  9540. this._txtTrack = void 0;
  9541. this.aacOverFlow = null;
  9542. this.avcSample = null;
  9543. this.remainderData = null;
  9544. this.observer = observer;
  9545. this.config = config;
  9546. this.typeSupported = typeSupported;
  9547. }
  9548. TSDemuxer.probe = function probe(data) {
  9549. var syncOffset = TSDemuxer.syncOffset(data);
  9550. if (syncOffset > 0) {
  9551. _utils_logger__WEBPACK_IMPORTED_MODULE_6__.logger.warn("MPEG2-TS detected but first sync word found @ offset " + syncOffset);
  9552. }
  9553. return syncOffset !== -1;
  9554. };
  9555. TSDemuxer.syncOffset = function syncOffset(data) {
  9556. var scanwindow = Math.min(PACKET_LENGTH * 5, data.length - PACKET_LENGTH * 2) + 1;
  9557. var i = 0;
  9558. while (i < scanwindow) {
  9559. // a TS init segment should contain at least 2 TS packets: PAT and PMT, each starting with 0x47
  9560. if (data[i] === 0x47 && data[i + PACKET_LENGTH] === 0x47) {
  9561. return i;
  9562. }
  9563. i++;
  9564. }
  9565. return -1;
  9566. }
  9567. /**
  9568. * Creates a track model internal to demuxer used to drive remuxing input
  9569. *
  9570. * @param type 'audio' | 'video' | 'id3' | 'text'
  9571. * @param duration
  9572. * @return TSDemuxer's internal track model
  9573. */;
  9574. TSDemuxer.createTrack = function createTrack(type, duration) {
  9575. return {
  9576. container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,
  9577. type: type,
  9578. id: _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_5__.RemuxerTrackIdConfig[type],
  9579. pid: -1,
  9580. inputTimeScale: 90000,
  9581. sequenceNumber: 0,
  9582. samples: [],
  9583. dropped: 0,
  9584. duration: type === 'audio' ? duration : undefined
  9585. };
  9586. }
  9587. /**
  9588. * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
  9589. * Resets all internal track instances of the demuxer.
  9590. */;
  9591. var _proto = TSDemuxer.prototype;
  9592. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  9593. this.pmtParsed = false;
  9594. this._pmtId = -1;
  9595. this._avcTrack = TSDemuxer.createTrack('video');
  9596. this._audioTrack = TSDemuxer.createTrack('audio', trackDuration);
  9597. this._id3Track = TSDemuxer.createTrack('id3');
  9598. this._txtTrack = TSDemuxer.createTrack('text');
  9599. this._audioTrack.segmentCodec = 'aac';
  9600. // flush any partial content
  9601. this.aacOverFlow = null;
  9602. this.avcSample = null;
  9603. this.remainderData = null;
  9604. this.audioCodec = audioCodec;
  9605. this.videoCodec = videoCodec;
  9606. this._duration = trackDuration;
  9607. };
  9608. _proto.resetTimeStamp = function resetTimeStamp() {};
  9609. _proto.resetContiguity = function resetContiguity() {
  9610. var _audioTrack = this._audioTrack,
  9611. _avcTrack = this._avcTrack,
  9612. _id3Track = this._id3Track;
  9613. if (_audioTrack) {
  9614. _audioTrack.pesData = null;
  9615. }
  9616. if (_avcTrack) {
  9617. _avcTrack.pesData = null;
  9618. }
  9619. if (_id3Track) {
  9620. _id3Track.pesData = null;
  9621. }
  9622. this.aacOverFlow = null;
  9623. this.avcSample = null;
  9624. this.remainderData = null;
  9625. };
  9626. _proto.demux = function demux(data, timeOffset, isSampleAes, flush) {
  9627. if (isSampleAes === void 0) {
  9628. isSampleAes = false;
  9629. }
  9630. if (flush === void 0) {
  9631. flush = false;
  9632. }
  9633. if (!isSampleAes) {
  9634. this.sampleAes = null;
  9635. }
  9636. var pes;
  9637. var videoTrack = this._avcTrack;
  9638. var audioTrack = this._audioTrack;
  9639. var id3Track = this._id3Track;
  9640. var textTrack = this._txtTrack;
  9641. var avcId = videoTrack.pid;
  9642. var avcData = videoTrack.pesData;
  9643. var audioId = audioTrack.pid;
  9644. var id3Id = id3Track.pid;
  9645. var audioData = audioTrack.pesData;
  9646. var id3Data = id3Track.pesData;
  9647. var unknownPID = null;
  9648. var pmtParsed = this.pmtParsed;
  9649. var pmtId = this._pmtId;
  9650. var len = data.length;
  9651. if (this.remainderData) {
  9652. data = (0,_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_5__.appendUint8Array)(this.remainderData, data);
  9653. len = data.length;
  9654. this.remainderData = null;
  9655. }
  9656. if (len < PACKET_LENGTH && !flush) {
  9657. this.remainderData = data;
  9658. return {
  9659. audioTrack: audioTrack,
  9660. videoTrack: videoTrack,
  9661. id3Track: id3Track,
  9662. textTrack: textTrack
  9663. };
  9664. }
  9665. var syncOffset = Math.max(0, TSDemuxer.syncOffset(data));
  9666. len -= (len - syncOffset) % PACKET_LENGTH;
  9667. if (len < data.byteLength && !flush) {
  9668. this.remainderData = new Uint8Array(data.buffer, len, data.buffer.byteLength - len);
  9669. }
  9670. // loop through TS packets
  9671. var tsPacketErrors = 0;
  9672. for (var start = syncOffset; start < len; start += PACKET_LENGTH) {
  9673. if (data[start] === 0x47) {
  9674. var stt = !!(data[start + 1] & 0x40);
  9675. // pid is a 13-bit field starting at the last bit of TS[1]
  9676. var pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];
  9677. var atf = (data[start + 3] & 0x30) >> 4;
  9678. // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.
  9679. var offset = void 0;
  9680. if (atf > 1) {
  9681. offset = start + 5 + data[start + 4];
  9682. // continue if there is only adaptation field
  9683. if (offset === start + PACKET_LENGTH) {
  9684. continue;
  9685. }
  9686. } else {
  9687. offset = start + 4;
  9688. }
  9689. switch (pid) {
  9690. case avcId:
  9691. if (stt) {
  9692. if (avcData && (pes = parsePES(avcData))) {
  9693. this.parseAVCPES(videoTrack, textTrack, pes, false);
  9694. }
  9695. avcData = {
  9696. data: [],
  9697. size: 0
  9698. };
  9699. }
  9700. if (avcData) {
  9701. avcData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  9702. avcData.size += start + PACKET_LENGTH - offset;
  9703. }
  9704. break;
  9705. case audioId:
  9706. if (stt) {
  9707. if (audioData && (pes = parsePES(audioData))) {
  9708. switch (audioTrack.segmentCodec) {
  9709. case 'aac':
  9710. this.parseAACPES(audioTrack, pes);
  9711. break;
  9712. case 'mp3':
  9713. this.parseMPEGPES(audioTrack, pes);
  9714. break;
  9715. }
  9716. }
  9717. audioData = {
  9718. data: [],
  9719. size: 0
  9720. };
  9721. }
  9722. if (audioData) {
  9723. audioData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  9724. audioData.size += start + PACKET_LENGTH - offset;
  9725. }
  9726. break;
  9727. case id3Id:
  9728. if (stt) {
  9729. if (id3Data && (pes = parsePES(id3Data))) {
  9730. this.parseID3PES(id3Track, pes);
  9731. }
  9732. id3Data = {
  9733. data: [],
  9734. size: 0
  9735. };
  9736. }
  9737. if (id3Data) {
  9738. id3Data.data.push(data.subarray(offset, start + PACKET_LENGTH));
  9739. id3Data.size += start + PACKET_LENGTH - offset;
  9740. }
  9741. break;
  9742. case 0:
  9743. if (stt) {
  9744. offset += data[offset] + 1;
  9745. }
  9746. pmtId = this._pmtId = parsePAT(data, offset);
  9747. break;
  9748. case pmtId:
  9749. {
  9750. if (stt) {
  9751. offset += data[offset] + 1;
  9752. }
  9753. var parsedPIDs = parsePMT(data, offset, this.typeSupported, isSampleAes);
  9754. // only update track id if track PID found while parsing PMT
  9755. // this is to avoid resetting the PID to -1 in case
  9756. // track PID transiently disappears from the stream
  9757. // this could happen in case of transient missing audio samples for example
  9758. // NOTE this is only the PID of the track as found in TS,
  9759. // but we are not using this for MP4 track IDs.
  9760. avcId = parsedPIDs.avc;
  9761. if (avcId > 0) {
  9762. videoTrack.pid = avcId;
  9763. }
  9764. audioId = parsedPIDs.audio;
  9765. if (audioId > 0) {
  9766. audioTrack.pid = audioId;
  9767. audioTrack.segmentCodec = parsedPIDs.segmentCodec;
  9768. }
  9769. id3Id = parsedPIDs.id3;
  9770. if (id3Id > 0) {
  9771. id3Track.pid = id3Id;
  9772. }
  9773. if (unknownPID !== null && !pmtParsed) {
  9774. _utils_logger__WEBPACK_IMPORTED_MODULE_6__.logger.log("unknown PID '" + unknownPID + "' in TS found");
  9775. unknownPID = null;
  9776. // we set it to -188, the += 188 in the for loop will reset start to 0
  9777. start = syncOffset - 188;
  9778. }
  9779. pmtParsed = this.pmtParsed = true;
  9780. break;
  9781. }
  9782. case 17:
  9783. case 0x1fff:
  9784. break;
  9785. default:
  9786. unknownPID = pid;
  9787. break;
  9788. }
  9789. } else {
  9790. tsPacketErrors++;
  9791. }
  9792. }
  9793. if (tsPacketErrors > 0) {
  9794. this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_4__.Events.ERROR, _events__WEBPACK_IMPORTED_MODULE_4__.Events.ERROR, {
  9795. type: _errors__WEBPACK_IMPORTED_MODULE_7__.ErrorTypes.MEDIA_ERROR,
  9796. details: _errors__WEBPACK_IMPORTED_MODULE_7__.ErrorDetails.FRAG_PARSING_ERROR,
  9797. fatal: false,
  9798. reason: "Found " + tsPacketErrors + " TS packet/s that do not start with 0x47"
  9799. });
  9800. }
  9801. videoTrack.pesData = avcData;
  9802. audioTrack.pesData = audioData;
  9803. id3Track.pesData = id3Data;
  9804. var demuxResult = {
  9805. audioTrack: audioTrack,
  9806. videoTrack: videoTrack,
  9807. id3Track: id3Track,
  9808. textTrack: textTrack
  9809. };
  9810. if (flush) {
  9811. this.extractRemainingSamples(demuxResult);
  9812. }
  9813. return demuxResult;
  9814. };
  9815. _proto.flush = function flush() {
  9816. var remainderData = this.remainderData;
  9817. this.remainderData = null;
  9818. var result;
  9819. if (remainderData) {
  9820. result = this.demux(remainderData, -1, false, true);
  9821. } else {
  9822. result = {
  9823. videoTrack: this._avcTrack,
  9824. audioTrack: this._audioTrack,
  9825. id3Track: this._id3Track,
  9826. textTrack: this._txtTrack
  9827. };
  9828. }
  9829. this.extractRemainingSamples(result);
  9830. if (this.sampleAes) {
  9831. return this.decrypt(result, this.sampleAes);
  9832. }
  9833. return result;
  9834. };
  9835. _proto.extractRemainingSamples = function extractRemainingSamples(demuxResult) {
  9836. var audioTrack = demuxResult.audioTrack,
  9837. videoTrack = demuxResult.videoTrack,
  9838. id3Track = demuxResult.id3Track,
  9839. textTrack = demuxResult.textTrack;
  9840. var avcData = videoTrack.pesData;
  9841. var audioData = audioTrack.pesData;
  9842. var id3Data = id3Track.pesData;
  9843. // try to parse last PES packets
  9844. var pes;
  9845. if (avcData && (pes = parsePES(avcData))) {
  9846. this.parseAVCPES(videoTrack, textTrack, pes, true);
  9847. videoTrack.pesData = null;
  9848. } else {
  9849. // either avcData null or PES truncated, keep it for next frag parsing
  9850. videoTrack.pesData = avcData;
  9851. }
  9852. if (audioData && (pes = parsePES(audioData))) {
  9853. switch (audioTrack.segmentCodec) {
  9854. case 'aac':
  9855. this.parseAACPES(audioTrack, pes);
  9856. break;
  9857. case 'mp3':
  9858. this.parseMPEGPES(audioTrack, pes);
  9859. break;
  9860. }
  9861. audioTrack.pesData = null;
  9862. } else {
  9863. if (audioData !== null && audioData !== void 0 && audioData.size) {
  9864. _utils_logger__WEBPACK_IMPORTED_MODULE_6__.logger.log('last AAC PES packet truncated,might overlap between fragments');
  9865. }
  9866. // either audioData null or PES truncated, keep it for next frag parsing
  9867. audioTrack.pesData = audioData;
  9868. }
  9869. if (id3Data && (pes = parsePES(id3Data))) {
  9870. this.parseID3PES(id3Track, pes);
  9871. id3Track.pesData = null;
  9872. } else {
  9873. // either id3Data null or PES truncated, keep it for next frag parsing
  9874. id3Track.pesData = id3Data;
  9875. }
  9876. };
  9877. _proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
  9878. var demuxResult = this.demux(data, timeOffset, true, !this.config.progressive);
  9879. var sampleAes = this.sampleAes = new _sample_aes__WEBPACK_IMPORTED_MODULE_3__["default"](this.observer, this.config, keyData);
  9880. return this.decrypt(demuxResult, sampleAes);
  9881. };
  9882. _proto.decrypt = function decrypt(demuxResult, sampleAes) {
  9883. return new Promise(function (resolve) {
  9884. var audioTrack = demuxResult.audioTrack,
  9885. videoTrack = demuxResult.videoTrack;
  9886. if (audioTrack.samples && audioTrack.segmentCodec === 'aac') {
  9887. sampleAes.decryptAacSamples(audioTrack.samples, 0, function () {
  9888. if (videoTrack.samples) {
  9889. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, function () {
  9890. resolve(demuxResult);
  9891. });
  9892. } else {
  9893. resolve(demuxResult);
  9894. }
  9895. });
  9896. } else if (videoTrack.samples) {
  9897. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, function () {
  9898. resolve(demuxResult);
  9899. });
  9900. }
  9901. });
  9902. };
  9903. _proto.destroy = function destroy() {
  9904. this._duration = 0;
  9905. };
  9906. _proto.parseAVCPES = function parseAVCPES(track, textTrack, pes, last) {
  9907. var _this = this;
  9908. var units = this.parseAVCNALu(track, pes.data);
  9909. var debug = false;
  9910. var avcSample = this.avcSample;
  9911. var push;
  9912. var spsfound = false;
  9913. // free pes.data to save up some memory
  9914. pes.data = null;
  9915. // if new NAL units found and last sample still there, let's push ...
  9916. // this helps parsing streams with missing AUD (only do this if AUD never found)
  9917. if (avcSample && units.length && !track.audFound) {
  9918. pushAccessUnit(avcSample, track);
  9919. avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, '');
  9920. }
  9921. units.forEach(function (unit) {
  9922. switch (unit.type) {
  9923. // NDR
  9924. case 1:
  9925. {
  9926. push = true;
  9927. if (!avcSample) {
  9928. avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
  9929. }
  9930. if (debug) {
  9931. avcSample.debug += 'NDR ';
  9932. }
  9933. avcSample.frame = true;
  9934. var data = unit.data;
  9935. // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)
  9936. if (spsfound && data.length > 4) {
  9937. // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR
  9938. var sliceType = new _exp_golomb__WEBPACK_IMPORTED_MODULE_2__["default"](data).readSliceType();
  9939. // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice
  9940. // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.
  9941. // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.
  9942. // I slice: A slice that is not an SI slice that is decoded using intra prediction only.
  9943. // if (sliceType === 2 || sliceType === 7) {
  9944. if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
  9945. avcSample.key = true;
  9946. }
  9947. }
  9948. break;
  9949. // IDR
  9950. }
  9951. case 5:
  9952. push = true;
  9953. // handle PES not starting with AUD
  9954. if (!avcSample) {
  9955. avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
  9956. }
  9957. if (debug) {
  9958. avcSample.debug += 'IDR ';
  9959. }
  9960. avcSample.key = true;
  9961. avcSample.frame = true;
  9962. break;
  9963. // SEI
  9964. case 6:
  9965. {
  9966. push = true;
  9967. if (debug && avcSample) {
  9968. avcSample.debug += 'SEI ';
  9969. }
  9970. (0,_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_5__.parseSEIMessageFromNALu)(unit.data, 1, pes.pts, textTrack.samples);
  9971. break;
  9972. // SPS
  9973. }
  9974. case 7:
  9975. push = true;
  9976. spsfound = true;
  9977. if (debug && avcSample) {
  9978. avcSample.debug += 'SPS ';
  9979. }
  9980. if (!track.sps) {
  9981. var expGolombDecoder = new _exp_golomb__WEBPACK_IMPORTED_MODULE_2__["default"](unit.data);
  9982. var config = expGolombDecoder.readSPS();
  9983. track.width = config.width;
  9984. track.height = config.height;
  9985. track.pixelRatio = config.pixelRatio;
  9986. // TODO: `track.sps` is defined as a `number[]`, but we're setting it to a `Uint8Array[]`.
  9987. track.sps = [unit.data];
  9988. track.duration = _this._duration;
  9989. var codecarray = unit.data.subarray(1, 4);
  9990. var codecstring = 'avc1.';
  9991. for (var i = 0; i < 3; i++) {
  9992. var h = codecarray[i].toString(16);
  9993. if (h.length < 2) {
  9994. h = '0' + h;
  9995. }
  9996. codecstring += h;
  9997. }
  9998. track.codec = codecstring;
  9999. }
  10000. break;
  10001. // PPS
  10002. case 8:
  10003. push = true;
  10004. if (debug && avcSample) {
  10005. avcSample.debug += 'PPS ';
  10006. }
  10007. if (!track.pps) {
  10008. // TODO: `track.pss` is defined as a `number[]`, but we're setting it to a `Uint8Array[]`.
  10009. track.pps = [unit.data];
  10010. }
  10011. break;
  10012. // AUD
  10013. case 9:
  10014. push = false;
  10015. track.audFound = true;
  10016. if (avcSample) {
  10017. pushAccessUnit(avcSample, track);
  10018. }
  10019. avcSample = _this.avcSample = createAVCSample(false, pes.pts, pes.dts, debug ? 'AUD ' : '');
  10020. break;
  10021. // Filler Data
  10022. case 12:
  10023. push = true;
  10024. break;
  10025. default:
  10026. push = false;
  10027. if (avcSample) {
  10028. avcSample.debug += 'unknown NAL ' + unit.type + ' ';
  10029. }
  10030. break;
  10031. }
  10032. if (avcSample && push) {
  10033. var _units = avcSample.units;
  10034. _units.push(unit);
  10035. }
  10036. });
  10037. // if last PES packet, push samples
  10038. if (last && avcSample) {
  10039. pushAccessUnit(avcSample, track);
  10040. this.avcSample = null;
  10041. }
  10042. };
  10043. _proto.getLastNalUnit = function getLastNalUnit(samples) {
  10044. var _avcSample;
  10045. var avcSample = this.avcSample;
  10046. var lastUnit;
  10047. // try to fallback to previous sample if current one is empty
  10048. if (!avcSample || avcSample.units.length === 0) {
  10049. avcSample = samples[samples.length - 1];
  10050. }
  10051. if ((_avcSample = avcSample) !== null && _avcSample !== void 0 && _avcSample.units) {
  10052. var units = avcSample.units;
  10053. lastUnit = units[units.length - 1];
  10054. }
  10055. return lastUnit;
  10056. };
  10057. _proto.parseAVCNALu = function parseAVCNALu(track, array) {
  10058. var len = array.byteLength;
  10059. var state = track.naluState || 0;
  10060. var lastState = state;
  10061. var units = [];
  10062. var i = 0;
  10063. var value;
  10064. var overflow;
  10065. var unitType;
  10066. var lastUnitStart = -1;
  10067. var lastUnitType = 0;
  10068. // logger.log('PES:' + Hex.hexDump(array));
  10069. if (state === -1) {
  10070. // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet
  10071. lastUnitStart = 0;
  10072. // NALu type is value read from offset 0
  10073. lastUnitType = array[0] & 0x1f;
  10074. state = 0;
  10075. i = 1;
  10076. }
  10077. while (i < len) {
  10078. value = array[i++];
  10079. // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case
  10080. if (!state) {
  10081. state = value ? 0 : 1;
  10082. continue;
  10083. }
  10084. if (state === 1) {
  10085. state = value ? 0 : 2;
  10086. continue;
  10087. }
  10088. // here we have state either equal to 2 or 3
  10089. if (!value) {
  10090. state = 3;
  10091. } else if (value === 1) {
  10092. if (lastUnitStart >= 0) {
  10093. var unit = {
  10094. data: array.subarray(lastUnitStart, i - state - 1),
  10095. type: lastUnitType
  10096. };
  10097. // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
  10098. units.push(unit);
  10099. } else {
  10100. // lastUnitStart is undefined => this is the first start code found in this PES packet
  10101. // first check if start code delimiter is overlapping between 2 PES packets,
  10102. // ie it started in last packet (lastState not zero)
  10103. // and ended at the beginning of this PES packet (i <= 4 - lastState)
  10104. var lastUnit = this.getLastNalUnit(track.samples);
  10105. if (lastUnit) {
  10106. if (lastState && i <= 4 - lastState) {
  10107. // start delimiter overlapping between PES packets
  10108. // strip start delimiter bytes from the end of last NAL unit
  10109. // check if lastUnit had a state different from zero
  10110. if (lastUnit.state) {
  10111. // strip last bytes
  10112. lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
  10113. }
  10114. }
  10115. // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.
  10116. overflow = i - state - 1;
  10117. if (overflow > 0) {
  10118. // logger.log('first NALU found with overflow:' + overflow);
  10119. var tmp = new Uint8Array(lastUnit.data.byteLength + overflow);
  10120. tmp.set(lastUnit.data, 0);
  10121. tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);
  10122. lastUnit.data = tmp;
  10123. lastUnit.state = 0;
  10124. }
  10125. }
  10126. }
  10127. // check if we can read unit type
  10128. if (i < len) {
  10129. unitType = array[i] & 0x1f;
  10130. // logger.log('find NALU @ offset:' + i + ',type:' + unitType);
  10131. lastUnitStart = i;
  10132. lastUnitType = unitType;
  10133. state = 0;
  10134. } else {
  10135. // not enough byte to read unit type. let's read it on next PES parsing
  10136. state = -1;
  10137. }
  10138. } else {
  10139. state = 0;
  10140. }
  10141. }
  10142. if (lastUnitStart >= 0 && state >= 0) {
  10143. var _unit = {
  10144. data: array.subarray(lastUnitStart, len),
  10145. type: lastUnitType,
  10146. state: state
  10147. };
  10148. units.push(_unit);
  10149. // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);
  10150. }
  10151. // no NALu found
  10152. if (units.length === 0) {
  10153. // append pes.data to previous NAL unit
  10154. var _lastUnit = this.getLastNalUnit(track.samples);
  10155. if (_lastUnit) {
  10156. var _tmp = new Uint8Array(_lastUnit.data.byteLength + array.byteLength);
  10157. _tmp.set(_lastUnit.data, 0);
  10158. _tmp.set(array, _lastUnit.data.byteLength);
  10159. _lastUnit.data = _tmp;
  10160. }
  10161. }
  10162. track.naluState = state;
  10163. return units;
  10164. };
  10165. _proto.parseAACPES = function parseAACPES(track, pes) {
  10166. var startOffset = 0;
  10167. var aacOverFlow = this.aacOverFlow;
  10168. var data = pes.data;
  10169. if (aacOverFlow) {
  10170. this.aacOverFlow = null;
  10171. var frameMissingBytes = aacOverFlow.missing;
  10172. var sampleLength = aacOverFlow.sample.unit.byteLength;
  10173. // logger.log(`AAC: append overflowing ${sampleLength} bytes to beginning of new PES`);
  10174. if (frameMissingBytes === -1) {
  10175. var tmp = new Uint8Array(sampleLength + data.byteLength);
  10176. tmp.set(aacOverFlow.sample.unit, 0);
  10177. tmp.set(data, sampleLength);
  10178. data = tmp;
  10179. } else {
  10180. var frameOverflowBytes = sampleLength - frameMissingBytes;
  10181. aacOverFlow.sample.unit.set(data.subarray(0, frameMissingBytes), frameOverflowBytes);
  10182. track.samples.push(aacOverFlow.sample);
  10183. startOffset = aacOverFlow.missing;
  10184. }
  10185. }
  10186. // look for ADTS header (0xFFFx)
  10187. var offset;
  10188. var len;
  10189. for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
  10190. if (_adts__WEBPACK_IMPORTED_MODULE_0__.isHeader(data, offset)) {
  10191. break;
  10192. }
  10193. }
  10194. // if ADTS header does not start straight from the beginning of the PES payload, raise an error
  10195. if (offset !== startOffset) {
  10196. var reason;
  10197. var fatal;
  10198. if (offset < len - 1) {
  10199. reason = "AAC PES did not start with ADTS header,offset:" + offset;
  10200. fatal = false;
  10201. } else {
  10202. reason = 'no ADTS header found in AAC PES';
  10203. fatal = true;
  10204. }
  10205. _utils_logger__WEBPACK_IMPORTED_MODULE_6__.logger.warn("parsing error:" + reason);
  10206. this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_4__.Events.ERROR, _events__WEBPACK_IMPORTED_MODULE_4__.Events.ERROR, {
  10207. type: _errors__WEBPACK_IMPORTED_MODULE_7__.ErrorTypes.MEDIA_ERROR,
  10208. details: _errors__WEBPACK_IMPORTED_MODULE_7__.ErrorDetails.FRAG_PARSING_ERROR,
  10209. fatal: fatal,
  10210. reason: reason
  10211. });
  10212. if (fatal) {
  10213. return;
  10214. }
  10215. }
  10216. _adts__WEBPACK_IMPORTED_MODULE_0__.initTrackConfig(track, this.observer, data, offset, this.audioCodec);
  10217. var pts;
  10218. if (pes.pts !== undefined) {
  10219. pts = pes.pts;
  10220. } else if (aacOverFlow) {
  10221. // if last AAC frame is overflowing, we should ensure timestamps are contiguous:
  10222. // first sample PTS should be equal to last sample PTS + frameDuration
  10223. var frameDuration = _adts__WEBPACK_IMPORTED_MODULE_0__.getFrameDuration(track.samplerate);
  10224. pts = aacOverFlow.sample.pts + frameDuration;
  10225. } else {
  10226. _utils_logger__WEBPACK_IMPORTED_MODULE_6__.logger.warn('[tsdemuxer]: AAC PES unknown PTS');
  10227. return;
  10228. }
  10229. // scan for aac samples
  10230. var frameIndex = 0;
  10231. var frame;
  10232. while (offset < len) {
  10233. frame = _adts__WEBPACK_IMPORTED_MODULE_0__.appendFrame(track, data, offset, pts, frameIndex);
  10234. offset += frame.length;
  10235. if (!frame.missing) {
  10236. frameIndex++;
  10237. for (; offset < len - 1; offset++) {
  10238. if (_adts__WEBPACK_IMPORTED_MODULE_0__.isHeader(data, offset)) {
  10239. break;
  10240. }
  10241. }
  10242. } else {
  10243. this.aacOverFlow = frame;
  10244. break;
  10245. }
  10246. }
  10247. };
  10248. _proto.parseMPEGPES = function parseMPEGPES(track, pes) {
  10249. var data = pes.data;
  10250. var length = data.length;
  10251. var frameIndex = 0;
  10252. var offset = 0;
  10253. var pts = pes.pts;
  10254. if (pts === undefined) {
  10255. _utils_logger__WEBPACK_IMPORTED_MODULE_6__.logger.warn('[tsdemuxer]: MPEG PES unknown PTS');
  10256. return;
  10257. }
  10258. while (offset < length) {
  10259. if (_mpegaudio__WEBPACK_IMPORTED_MODULE_1__.isHeader(data, offset)) {
  10260. var frame = _mpegaudio__WEBPACK_IMPORTED_MODULE_1__.appendFrame(track, data, offset, pts, frameIndex);
  10261. if (frame) {
  10262. offset += frame.length;
  10263. frameIndex++;
  10264. } else {
  10265. // logger.log('Unable to parse Mpeg audio frame');
  10266. break;
  10267. }
  10268. } else {
  10269. // nothing found, keep looking
  10270. offset++;
  10271. }
  10272. }
  10273. };
  10274. _proto.parseID3PES = function parseID3PES(id3Track, pes) {
  10275. if (pes.pts === undefined) {
  10276. _utils_logger__WEBPACK_IMPORTED_MODULE_6__.logger.warn('[tsdemuxer]: ID3 PES unknown PTS');
  10277. return;
  10278. }
  10279. var id3Sample = _extends({}, pes, {
  10280. type: this._avcTrack ? _types_demuxer__WEBPACK_IMPORTED_MODULE_8__.MetadataSchema.emsg : _types_demuxer__WEBPACK_IMPORTED_MODULE_8__.MetadataSchema.audioId3,
  10281. duration: Number.POSITIVE_INFINITY
  10282. });
  10283. id3Track.samples.push(id3Sample);
  10284. };
  10285. return TSDemuxer;
  10286. }();
  10287. function createAVCSample(key, pts, dts, debug) {
  10288. return {
  10289. key: key,
  10290. frame: false,
  10291. pts: pts,
  10292. dts: dts,
  10293. units: [],
  10294. debug: debug,
  10295. length: 0
  10296. };
  10297. }
  10298. function parsePAT(data, offset) {
  10299. // skip the PSI header and parse the first PMT entry
  10300. return (data[offset + 10] & 0x1f) << 8 | data[offset + 11];
  10301. // logger.log('PMT PID:' + this._pmtId);
  10302. }
  10303. function parsePMT(data, offset, typeSupported, isSampleAes) {
  10304. var result = {
  10305. audio: -1,
  10306. avc: -1,
  10307. id3: -1,
  10308. segmentCodec: 'aac'
  10309. };
  10310. var sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
  10311. var tableEnd = offset + 3 + sectionLength - 4;
  10312. // to determine where the table is, we have to figure out how
  10313. // long the program info descriptors are
  10314. var programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11];
  10315. // advance the offset to the first entry in the mapping table
  10316. offset += 12 + programInfoLength;
  10317. while (offset < tableEnd) {
  10318. var pid = (data[offset + 1] & 0x1f) << 8 | data[offset + 2];
  10319. switch (data[offset]) {
  10320. case 0xcf:
  10321. // SAMPLE-AES AAC
  10322. if (!isSampleAes) {
  10323. _utils_logger__WEBPACK_IMPORTED_MODULE_6__.logger.log('ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream');
  10324. break;
  10325. }
  10326. /* falls through */
  10327. case 0x0f:
  10328. // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
  10329. // logger.log('AAC PID:' + pid);
  10330. if (result.audio === -1) {
  10331. result.audio = pid;
  10332. }
  10333. break;
  10334. // Packetized metadata (ID3)
  10335. case 0x15:
  10336. // logger.log('ID3 PID:' + pid);
  10337. if (result.id3 === -1) {
  10338. result.id3 = pid;
  10339. }
  10340. break;
  10341. case 0xdb:
  10342. // SAMPLE-AES AVC
  10343. if (!isSampleAes) {
  10344. _utils_logger__WEBPACK_IMPORTED_MODULE_6__.logger.log('H.264 with AES-128-CBC slice encryption found in unencrypted stream');
  10345. break;
  10346. }
  10347. /* falls through */
  10348. case 0x1b:
  10349. // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
  10350. // logger.log('AVC PID:' + pid);
  10351. if (result.avc === -1) {
  10352. result.avc = pid;
  10353. }
  10354. break;
  10355. // ISO/IEC 11172-3 (MPEG-1 audio)
  10356. // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)
  10357. case 0x03:
  10358. case 0x04:
  10359. // logger.log('MPEG PID:' + pid);
  10360. if (typeSupported.mpeg !== true && typeSupported.mp3 !== true) {
  10361. _utils_logger__WEBPACK_IMPORTED_MODULE_6__.logger.log('MPEG audio found, not supported in this browser');
  10362. } else if (result.audio === -1) {
  10363. result.audio = pid;
  10364. result.segmentCodec = 'mp3';
  10365. }
  10366. break;
  10367. case 0x24:
  10368. _utils_logger__WEBPACK_IMPORTED_MODULE_6__.logger.warn('Unsupported HEVC stream type found');
  10369. break;
  10370. default:
  10371. // logger.log('unknown stream type:' + data[offset]);
  10372. break;
  10373. }
  10374. // move to the next table entry
  10375. // skip past the elementary stream descriptors, if present
  10376. offset += ((data[offset + 3] & 0x0f) << 8 | data[offset + 4]) + 5;
  10377. }
  10378. return result;
  10379. }
  10380. function parsePES(stream) {
  10381. var i = 0;
  10382. var frag;
  10383. var pesLen;
  10384. var pesHdrLen;
  10385. var pesPts;
  10386. var pesDts;
  10387. var data = stream.data;
  10388. // safety check
  10389. if (!stream || stream.size === 0) {
  10390. return null;
  10391. }
  10392. // we might need up to 19 bytes to read PES header
  10393. // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes
  10394. // usually only one merge is needed (and this is rare ...)
  10395. while (data[0].length < 19 && data.length > 1) {
  10396. var newData = new Uint8Array(data[0].length + data[1].length);
  10397. newData.set(data[0]);
  10398. newData.set(data[1], data[0].length);
  10399. data[0] = newData;
  10400. data.splice(1, 1);
  10401. }
  10402. // retrieve PTS/DTS from first fragment
  10403. frag = data[0];
  10404. var pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
  10405. if (pesPrefix === 1) {
  10406. pesLen = (frag[4] << 8) + frag[5];
  10407. // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated
  10408. // minus 6 : PES header size
  10409. if (pesLen && pesLen > stream.size - 6) {
  10410. return null;
  10411. }
  10412. var pesFlags = frag[7];
  10413. if (pesFlags & 0xc0) {
  10414. /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  10415. as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
  10416. as Bitwise operators treat their operands as a sequence of 32 bits */
  10417. pesPts = (frag[9] & 0x0e) * 536870912 +
  10418. // 1 << 29
  10419. (frag[10] & 0xff) * 4194304 +
  10420. // 1 << 22
  10421. (frag[11] & 0xfe) * 16384 +
  10422. // 1 << 14
  10423. (frag[12] & 0xff) * 128 +
  10424. // 1 << 7
  10425. (frag[13] & 0xfe) / 2;
  10426. if (pesFlags & 0x40) {
  10427. pesDts = (frag[14] & 0x0e) * 536870912 +
  10428. // 1 << 29
  10429. (frag[15] & 0xff) * 4194304 +
  10430. // 1 << 22
  10431. (frag[16] & 0xfe) * 16384 +
  10432. // 1 << 14
  10433. (frag[17] & 0xff) * 128 +
  10434. // 1 << 7
  10435. (frag[18] & 0xfe) / 2;
  10436. if (pesPts - pesDts > 60 * 90000) {
  10437. _utils_logger__WEBPACK_IMPORTED_MODULE_6__.logger.warn(Math.round((pesPts - pesDts) / 90000) + "s delta between PTS and DTS, align them");
  10438. pesPts = pesDts;
  10439. }
  10440. } else {
  10441. pesDts = pesPts;
  10442. }
  10443. }
  10444. pesHdrLen = frag[8];
  10445. // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension
  10446. var payloadStartOffset = pesHdrLen + 9;
  10447. if (stream.size <= payloadStartOffset) {
  10448. return null;
  10449. }
  10450. stream.size -= payloadStartOffset;
  10451. // reassemble PES packet
  10452. var pesData = new Uint8Array(stream.size);
  10453. for (var j = 0, dataLen = data.length; j < dataLen; j++) {
  10454. frag = data[j];
  10455. var len = frag.byteLength;
  10456. if (payloadStartOffset) {
  10457. if (payloadStartOffset > len) {
  10458. // trim full frag if PES header bigger than frag
  10459. payloadStartOffset -= len;
  10460. continue;
  10461. } else {
  10462. // trim partial frag if PES header smaller than frag
  10463. frag = frag.subarray(payloadStartOffset);
  10464. len -= payloadStartOffset;
  10465. payloadStartOffset = 0;
  10466. }
  10467. }
  10468. pesData.set(frag, i);
  10469. i += len;
  10470. }
  10471. if (pesLen) {
  10472. // payload size : remove PES header + PES extension
  10473. pesLen -= pesHdrLen + 3;
  10474. }
  10475. return {
  10476. data: pesData,
  10477. pts: pesPts,
  10478. dts: pesDts,
  10479. len: pesLen
  10480. };
  10481. }
  10482. return null;
  10483. }
  10484. function pushAccessUnit(avcSample, avcTrack) {
  10485. if (avcSample.units.length && avcSample.frame) {
  10486. // if sample does not have PTS/DTS, patch with last sample PTS/DTS
  10487. if (avcSample.pts === undefined) {
  10488. var samples = avcTrack.samples;
  10489. var nbSamples = samples.length;
  10490. if (nbSamples) {
  10491. var lastSample = samples[nbSamples - 1];
  10492. avcSample.pts = lastSample.pts;
  10493. avcSample.dts = lastSample.dts;
  10494. } else {
  10495. // dropping samples, no timestamp found
  10496. avcTrack.dropped++;
  10497. return;
  10498. }
  10499. }
  10500. avcTrack.samples.push(avcSample);
  10501. }
  10502. if (avcSample.debug.length) {
  10503. _utils_logger__WEBPACK_IMPORTED_MODULE_6__.logger.log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug);
  10504. }
  10505. }
  10506. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (TSDemuxer);
  10507. /***/ }),
  10508. /***/ "./src/demux/webworkify-webpack.js":
  10509. /*!*****************************************!*\
  10510. !*** ./src/demux/webworkify-webpack.js ***!
  10511. \*****************************************/
  10512. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  10513. "use strict";
  10514. __webpack_require__.r(__webpack_exports__);
  10515. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  10516. /* harmony export */ "default": () => (/* export default binding */ __WEBPACK_DEFAULT_EXPORT__)
  10517. /* harmony export */ });
  10518. /*
  10519. * Fork of webworkify-webpack with support for Webpack 5
  10520. * https://github.com/wupeng-engineer/webworkify-webpack/blob/db0de7/index.js
  10521. */
  10522. var webpackBootstrapFunc = function webpackBootstrapFunc() {
  10523. // webpackBootstrap
  10524. /******/
  10525. var __webpack_modules__ = ENTRY_MODULE;
  10526. /************************************************************************/
  10527. /******/ // The module cache
  10528. /******/
  10529. var __webpack_module_cache__ = {};
  10530. /******/
  10531. /******/ // The require function
  10532. /******/
  10533. var __nested_webpack_require_497__ = function __webpack_require__(moduleId) {
  10534. /******/ // Check if module is in cache
  10535. /******/var cachedModule = __webpack_module_cache__[moduleId];
  10536. /******/
  10537. if (cachedModule !== undefined) {
  10538. /******/return cachedModule.exports;
  10539. /******/
  10540. }
  10541. /******/ // Create a new module (and put it into the cache)
  10542. /******/
  10543. var module = __webpack_module_cache__[moduleId] = {
  10544. /******/ // no module.id needed
  10545. /******/ // no module.loaded needed
  10546. /******/exports: {}
  10547. /******/
  10548. };
  10549. /******/
  10550. /******/ // Execute the module function
  10551. /******/
  10552. __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  10553. /******/
  10554. /******/ // Return the exports of the module
  10555. /******/
  10556. return module.exports;
  10557. /******/
  10558. };
  10559. /******/
  10560. /******/ // expose the modules object (__webpack_modules__)
  10561. /******/
  10562. __nested_webpack_require_497__.m = __webpack_modules__;
  10563. /******/
  10564. /************************************************************************/
  10565. /******/ /* webpack/runtime/compat get default export */
  10566. /******/
  10567. (function () {
  10568. /******/ // getDefaultExport function for compatibility with non-harmony modules
  10569. /******/__nested_webpack_require_497__.n = function (module) {
  10570. /******/var getter = module && module.__esModule ? /******/function () {
  10571. return module['default'];
  10572. } : /******/function () {
  10573. return module;
  10574. };
  10575. /******/
  10576. __nested_webpack_require_497__.d(getter, {
  10577. a: getter
  10578. });
  10579. /******/
  10580. return getter;
  10581. /******/
  10582. };
  10583. /******/
  10584. })();
  10585. /******/
  10586. /******/ /* webpack/runtime/define property getters */
  10587. /******/
  10588. (function () {
  10589. /******/ // define getter functions for harmony exports
  10590. /******/__nested_webpack_require_497__.d = function (exports, definition) {
  10591. /******/for (var key in definition) {
  10592. /******/if (__nested_webpack_require_497__.o(definition, key) && !__nested_webpack_require_497__.o(exports, key)) {
  10593. /******/Object.defineProperty(exports, key, {
  10594. enumerable: true,
  10595. get: definition[key]
  10596. });
  10597. /******/
  10598. }
  10599. /******/
  10600. }
  10601. /******/
  10602. };
  10603. /******/
  10604. })();
  10605. /******/
  10606. /******/ /* webpack/runtime/hasOwnProperty shorthand */
  10607. /******/
  10608. (function () {
  10609. /******/__nested_webpack_require_497__.o = function (obj, prop) {
  10610. return Object.prototype.hasOwnProperty.call(obj, prop);
  10611. };
  10612. /******/
  10613. })();
  10614. /******/
  10615. /******/ /* webpack/runtime/make namespace object */
  10616. /******/
  10617. (function () {
  10618. /******/ // define __esModule on exports
  10619. /******/__nested_webpack_require_497__.r = function (exports) {
  10620. /******/if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  10621. /******/Object.defineProperty(exports, Symbol.toStringTag, {
  10622. value: 'Module'
  10623. });
  10624. /******/
  10625. }
  10626. /******/
  10627. Object.defineProperty(exports, '__esModule', {
  10628. value: true
  10629. });
  10630. /******/
  10631. };
  10632. /******/
  10633. })();
  10634. /******/
  10635. /************************************************************************/
  10636. /******/
  10637. /******/ // module factories are used so entry inlining is disabled
  10638. /******/ // startup
  10639. /******/ // Load entry module and return exports
  10640. /******/
  10641. var result = __nested_webpack_require_497__(ENTRY_MODULE);
  10642. /******/
  10643. return result.default || result;
  10644. };
  10645. var webpackBootstrapFuncArr = webpackBootstrapFunc.toString().split('ENTRY_MODULE');
  10646. var moduleNameReqExp = '[\\.|\\-|\\+|\\w|\/|@]+';
  10647. var dependencyRegExp = '\\(\\s*(\/\\*.*?\\*\/)?\\s*.*?(' + moduleNameReqExp + ').*?\\)';
  10648. function quoteRegExp(str) {
  10649. return (str + '').replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&');
  10650. }
  10651. function isNumeric(n) {
  10652. return !isNaN(1 * n);
  10653. }
  10654. function getModuleDependencies(sources, module, queueName) {
  10655. var retval = {};
  10656. retval[queueName] = [];
  10657. var fnString = module.toString().replace(/^"[^"]+"/, 'function');
  10658. ;
  10659. var wrapperSignature = fnString.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/) || fnString.match(/^\(\w+,\s*\w+,\s*(\w+)\)\s?\=\s?\>/);
  10660. if (!wrapperSignature) return retval;
  10661. var webpackRequireName = wrapperSignature[1];
  10662. var re = new RegExp('(\\\\n|\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g');
  10663. var match;
  10664. while (match = re.exec(fnString)) {
  10665. if (match[3] === 'dll-reference') continue;
  10666. retval[queueName].push(match[3]);
  10667. }
  10668. re = new RegExp('\\(' + quoteRegExp(webpackRequireName) + '\\("(dll-reference\\s(' + moduleNameReqExp + '))"\\)\\)' + dependencyRegExp, 'g');
  10669. while (match = re.exec(fnString)) {
  10670. if (!sources[match[2]]) {
  10671. retval[queueName].push(match[1]);
  10672. sources[match[2]] = __webpack_require__(match[1]).m;
  10673. }
  10674. retval[match[2]] = retval[match[2]] || [];
  10675. retval[match[2]].push(match[4]);
  10676. }
  10677. var keys = Object.keys(retval);
  10678. for (var i = 0; i < keys.length; i++) {
  10679. for (var j = 0; j < retval[keys[i]].length; j++) {
  10680. if (isNumeric(retval[keys[i]][j])) {
  10681. retval[keys[i]][j] = 1 * retval[keys[i]][j];
  10682. }
  10683. }
  10684. }
  10685. return retval;
  10686. }
  10687. function hasValuesInQueues(queues) {
  10688. var keys = Object.keys(queues);
  10689. return keys.reduce(function (hasValues, key) {
  10690. return hasValues || queues[key].length > 0;
  10691. }, false);
  10692. }
  10693. function getRequiredModules(sources, moduleId) {
  10694. var modulesQueue = {
  10695. main: [moduleId]
  10696. };
  10697. var requiredModules = {
  10698. main: []
  10699. };
  10700. var seenModules = {
  10701. main: {}
  10702. };
  10703. while (hasValuesInQueues(modulesQueue)) {
  10704. var queues = Object.keys(modulesQueue);
  10705. for (var i = 0; i < queues.length; i++) {
  10706. var queueName = queues[i];
  10707. var queue = modulesQueue[queueName];
  10708. var moduleToCheck = queue.pop();
  10709. seenModules[queueName] = seenModules[queueName] || {};
  10710. if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue;
  10711. seenModules[queueName][moduleToCheck] = true;
  10712. requiredModules[queueName] = requiredModules[queueName] || [];
  10713. requiredModules[queueName].push(moduleToCheck);
  10714. var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName);
  10715. var newModulesKeys = Object.keys(newModules);
  10716. for (var j = 0; j < newModulesKeys.length; j++) {
  10717. modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || [];
  10718. modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]]);
  10719. }
  10720. }
  10721. }
  10722. return requiredModules;
  10723. }
  10724. function getWebpackString(requiredModules, sources, entryModule, key) {
  10725. var moduleString = requiredModules[key].map(function (id) {
  10726. return "\"" + id + "\": " + sources[key][id].toString().replace(/^"[^"]+"/, 'function');
  10727. }).join(",");
  10728. return webpackBootstrapFuncArr[0] + "{" + moduleString + "}" + webpackBootstrapFuncArr[1] + "\"" + entryModule + "\"" + webpackBootstrapFuncArr[2];
  10729. }
  10730. /* harmony default export */ function __WEBPACK_DEFAULT_EXPORT__(moduleId, options) {
  10731. options = options || {};
  10732. var sources = {
  10733. main: __webpack_require__.m
  10734. };
  10735. var requiredModules = options.all ? {
  10736. main: Object.keys(sources.main)
  10737. } : getRequiredModules(sources, moduleId);
  10738. var src = '';
  10739. Object.keys(requiredModules).filter(function (m) {
  10740. return m !== 'main';
  10741. }).forEach(function (module) {
  10742. var entryModule = 0;
  10743. while (requiredModules[module][entryModule]) {
  10744. entryModule++;
  10745. }
  10746. requiredModules[module].push(entryModule);
  10747. sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })';
  10748. src = src + ("var " + module + " = (" + getWebpackString(requiredModules, sources, entryModule, modules) + ")();\n");
  10749. });
  10750. src = src + ("new ((" + getWebpackString(requiredModules, sources, moduleId, 'main') + ")())(self);");
  10751. var blob = new window.Blob([src], {
  10752. type: 'text/javascript'
  10753. });
  10754. var URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  10755. var workerUrl = URL.createObjectURL(blob);
  10756. var worker = new window.Worker(workerUrl);
  10757. worker.objectURL = workerUrl;
  10758. return worker;
  10759. }
  10760. /***/ }),
  10761. /***/ "./src/empty.js":
  10762. /*!**********************!*\
  10763. !*** ./src/empty.js ***!
  10764. \**********************/
  10765. /***/ ((module) => {
  10766. // This file is inserted as a shim for modules which we do not want to include into the distro.
  10767. // This replacement is done in the "resolve" section of the webpack config.
  10768. module.exports = undefined;
  10769. /***/ }),
  10770. /***/ "./src/errors.ts":
  10771. /*!***********************!*\
  10772. !*** ./src/errors.ts ***!
  10773. \***********************/
  10774. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  10775. "use strict";
  10776. __webpack_require__.r(__webpack_exports__);
  10777. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  10778. /* harmony export */ "ErrorDetails": () => (/* binding */ ErrorDetails),
  10779. /* harmony export */ "ErrorTypes": () => (/* binding */ ErrorTypes)
  10780. /* harmony export */ });
  10781. var ErrorTypes;
  10782. /**
  10783. * @enum {ErrorDetails}
  10784. * @typedef {string} ErrorDetail
  10785. */
  10786. (function (ErrorTypes) {
  10787. ErrorTypes["NETWORK_ERROR"] = "networkError";
  10788. ErrorTypes["MEDIA_ERROR"] = "mediaError";
  10789. ErrorTypes["KEY_SYSTEM_ERROR"] = "keySystemError";
  10790. ErrorTypes["MUX_ERROR"] = "muxError";
  10791. ErrorTypes["OTHER_ERROR"] = "otherError";
  10792. })(ErrorTypes || (ErrorTypes = {}));
  10793. var ErrorDetails;
  10794. (function (ErrorDetails) {
  10795. ErrorDetails["KEY_SYSTEM_NO_KEYS"] = "keySystemNoKeys";
  10796. ErrorDetails["KEY_SYSTEM_NO_ACCESS"] = "keySystemNoAccess";
  10797. ErrorDetails["KEY_SYSTEM_NO_SESSION"] = "keySystemNoSession";
  10798. ErrorDetails["KEY_SYSTEM_LICENSE_REQUEST_FAILED"] = "keySystemLicenseRequestFailed";
  10799. ErrorDetails["KEY_SYSTEM_NO_INIT_DATA"] = "keySystemNoInitData";
  10800. ErrorDetails["MANIFEST_LOAD_ERROR"] = "manifestLoadError";
  10801. ErrorDetails["MANIFEST_LOAD_TIMEOUT"] = "manifestLoadTimeOut";
  10802. ErrorDetails["MANIFEST_PARSING_ERROR"] = "manifestParsingError";
  10803. ErrorDetails["MANIFEST_INCOMPATIBLE_CODECS_ERROR"] = "manifestIncompatibleCodecsError";
  10804. ErrorDetails["LEVEL_EMPTY_ERROR"] = "levelEmptyError";
  10805. ErrorDetails["LEVEL_LOAD_ERROR"] = "levelLoadError";
  10806. ErrorDetails["LEVEL_LOAD_TIMEOUT"] = "levelLoadTimeOut";
  10807. ErrorDetails["LEVEL_SWITCH_ERROR"] = "levelSwitchError";
  10808. ErrorDetails["AUDIO_TRACK_LOAD_ERROR"] = "audioTrackLoadError";
  10809. ErrorDetails["AUDIO_TRACK_LOAD_TIMEOUT"] = "audioTrackLoadTimeOut";
  10810. ErrorDetails["SUBTITLE_LOAD_ERROR"] = "subtitleTrackLoadError";
  10811. ErrorDetails["SUBTITLE_TRACK_LOAD_TIMEOUT"] = "subtitleTrackLoadTimeOut";
  10812. ErrorDetails["FRAG_LOAD_ERROR"] = "fragLoadError";
  10813. ErrorDetails["FRAG_LOAD_TIMEOUT"] = "fragLoadTimeOut";
  10814. ErrorDetails["FRAG_DECRYPT_ERROR"] = "fragDecryptError";
  10815. ErrorDetails["FRAG_PARSING_ERROR"] = "fragParsingError";
  10816. ErrorDetails["REMUX_ALLOC_ERROR"] = "remuxAllocError";
  10817. ErrorDetails["KEY_LOAD_ERROR"] = "keyLoadError";
  10818. ErrorDetails["KEY_LOAD_TIMEOUT"] = "keyLoadTimeOut";
  10819. ErrorDetails["BUFFER_ADD_CODEC_ERROR"] = "bufferAddCodecError";
  10820. ErrorDetails["BUFFER_INCOMPATIBLE_CODECS_ERROR"] = "bufferIncompatibleCodecsError";
  10821. ErrorDetails["BUFFER_APPEND_ERROR"] = "bufferAppendError";
  10822. ErrorDetails["BUFFER_APPENDING_ERROR"] = "bufferAppendingError";
  10823. ErrorDetails["BUFFER_STALLED_ERROR"] = "bufferStalledError";
  10824. ErrorDetails["BUFFER_FULL_ERROR"] = "bufferFullError";
  10825. ErrorDetails["BUFFER_SEEK_OVER_HOLE"] = "bufferSeekOverHole";
  10826. ErrorDetails["BUFFER_NUDGE_ON_STALL"] = "bufferNudgeOnStall";
  10827. ErrorDetails["INTERNAL_EXCEPTION"] = "internalException";
  10828. ErrorDetails["INTERNAL_ABORTED"] = "aborted";
  10829. ErrorDetails["UNKNOWN"] = "unknown";
  10830. })(ErrorDetails || (ErrorDetails = {}));
  10831. /***/ }),
  10832. /***/ "./src/events.ts":
  10833. /*!***********************!*\
  10834. !*** ./src/events.ts ***!
  10835. \***********************/
  10836. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  10837. "use strict";
  10838. __webpack_require__.r(__webpack_exports__);
  10839. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  10840. /* harmony export */ "Events": () => (/* binding */ Events)
  10841. /* harmony export */ });
  10842. /**
  10843. * @readonly
  10844. * @enum {string}
  10845. */
  10846. var Events;
  10847. (function (Events) {
  10848. Events["MEDIA_ATTACHING"] = "hlsMediaAttaching";
  10849. Events["MEDIA_ATTACHED"] = "hlsMediaAttached";
  10850. Events["MEDIA_DETACHING"] = "hlsMediaDetaching";
  10851. Events["MEDIA_DETACHED"] = "hlsMediaDetached";
  10852. Events["BUFFER_RESET"] = "hlsBufferReset";
  10853. Events["BUFFER_CODECS"] = "hlsBufferCodecs";
  10854. Events["BUFFER_CREATED"] = "hlsBufferCreated";
  10855. Events["BUFFER_APPENDING"] = "hlsBufferAppending";
  10856. Events["BUFFER_APPENDED"] = "hlsBufferAppended";
  10857. Events["BUFFER_EOS"] = "hlsBufferEos";
  10858. Events["BUFFER_FLUSHING"] = "hlsBufferFlushing";
  10859. Events["BUFFER_FLUSHED"] = "hlsBufferFlushed";
  10860. Events["MANIFEST_LOADING"] = "hlsManifestLoading";
  10861. Events["MANIFEST_LOADED"] = "hlsManifestLoaded";
  10862. Events["MANIFEST_PARSED"] = "hlsManifestParsed";
  10863. Events["LEVEL_SWITCHING"] = "hlsLevelSwitching";
  10864. Events["LEVEL_SWITCHED"] = "hlsLevelSwitched";
  10865. Events["LEVEL_LOADING"] = "hlsLevelLoading";
  10866. Events["LEVEL_LOADED"] = "hlsLevelLoaded";
  10867. Events["LEVEL_UPDATED"] = "hlsLevelUpdated";
  10868. Events["LEVEL_PTS_UPDATED"] = "hlsLevelPtsUpdated";
  10869. Events["LEVELS_UPDATED"] = "hlsLevelsUpdated";
  10870. Events["AUDIO_TRACKS_UPDATED"] = "hlsAudioTracksUpdated";
  10871. Events["AUDIO_TRACK_SWITCHING"] = "hlsAudioTrackSwitching";
  10872. Events["AUDIO_TRACK_SWITCHED"] = "hlsAudioTrackSwitched";
  10873. Events["AUDIO_TRACK_LOADING"] = "hlsAudioTrackLoading";
  10874. Events["AUDIO_TRACK_LOADED"] = "hlsAudioTrackLoaded";
  10875. Events["SUBTITLE_TRACKS_UPDATED"] = "hlsSubtitleTracksUpdated";
  10876. Events["SUBTITLE_TRACKS_CLEARED"] = "hlsSubtitleTracksCleared";
  10877. Events["SUBTITLE_TRACK_SWITCH"] = "hlsSubtitleTrackSwitch";
  10878. Events["SUBTITLE_TRACK_LOADING"] = "hlsSubtitleTrackLoading";
  10879. Events["SUBTITLE_TRACK_LOADED"] = "hlsSubtitleTrackLoaded";
  10880. Events["SUBTITLE_FRAG_PROCESSED"] = "hlsSubtitleFragProcessed";
  10881. Events["CUES_PARSED"] = "hlsCuesParsed";
  10882. Events["NON_NATIVE_TEXT_TRACKS_FOUND"] = "hlsNonNativeTextTracksFound";
  10883. Events["INIT_PTS_FOUND"] = "hlsInitPtsFound";
  10884. Events["FRAG_LOADING"] = "hlsFragLoading";
  10885. Events["FRAG_LOAD_EMERGENCY_ABORTED"] = "hlsFragLoadEmergencyAborted";
  10886. Events["FRAG_LOADED"] = "hlsFragLoaded";
  10887. Events["FRAG_DECRYPTED"] = "hlsFragDecrypted";
  10888. Events["FRAG_PARSING_INIT_SEGMENT"] = "hlsFragParsingInitSegment";
  10889. Events["FRAG_PARSING_USERDATA"] = "hlsFragParsingUserdata";
  10890. Events["FRAG_PARSING_METADATA"] = "hlsFragParsingMetadata";
  10891. Events["FRAG_PARSED"] = "hlsFragParsed";
  10892. Events["FRAG_BUFFERED"] = "hlsFragBuffered";
  10893. Events["FRAG_CHANGED"] = "hlsFragChanged";
  10894. Events["FPS_DROP"] = "hlsFpsDrop";
  10895. Events["FPS_DROP_LEVEL_CAPPING"] = "hlsFpsDropLevelCapping";
  10896. Events["ERROR"] = "hlsError";
  10897. Events["DESTROYING"] = "hlsDestroying";
  10898. Events["KEY_LOADING"] = "hlsKeyLoading";
  10899. Events["KEY_LOADED"] = "hlsKeyLoaded";
  10900. Events["LIVE_BACK_BUFFER_REACHED"] = "hlsLiveBackBufferReached";
  10901. Events["BACK_BUFFER_REACHED"] = "hlsBackBufferReached";
  10902. })(Events || (Events = {}));
  10903. /***/ }),
  10904. /***/ "./src/hls.ts":
  10905. /*!********************!*\
  10906. !*** ./src/hls.ts ***!
  10907. \********************/
  10908. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  10909. "use strict";
  10910. __webpack_require__.r(__webpack_exports__);
  10911. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  10912. /* harmony export */ "default": () => (/* binding */ Hls)
  10913. /* harmony export */ });
  10914. /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! url-toolkit */ "./node_modules/.pnpm/url-toolkit@2.2.5/node_modules/url-toolkit/src/url-toolkit.js");
  10915. /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_0__);
  10916. /* harmony import */ var _loader_playlist_loader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./loader/playlist-loader */ "./src/loader/playlist-loader.ts");
  10917. /* harmony import */ var _controller_id3_track_controller__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./controller/id3-track-controller */ "./src/controller/id3-track-controller.ts");
  10918. /* harmony import */ var _controller_latency_controller__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./controller/latency-controller */ "./src/controller/latency-controller.ts");
  10919. /* harmony import */ var _controller_level_controller__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./controller/level-controller */ "./src/controller/level-controller.ts");
  10920. /* harmony import */ var _controller_fragment_tracker__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./controller/fragment-tracker */ "./src/controller/fragment-tracker.ts");
  10921. /* harmony import */ var _controller_stream_controller__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./controller/stream-controller */ "./src/controller/stream-controller.ts");
  10922. /* harmony import */ var _is_supported__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./is-supported */ "./src/is-supported.ts");
  10923. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./utils/logger */ "./src/utils/logger.ts");
  10924. /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./config */ "./src/config.ts");
  10925. /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js");
  10926. /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_10__);
  10927. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./events */ "./src/events.ts");
  10928. /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./errors */ "./src/errors.ts");
  10929. 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, _toPropertyKey(descriptor.key), descriptor); } }
  10930. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  10931. function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
  10932. function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
  10933. /**
  10934. * @module Hls
  10935. * @class
  10936. * @constructor
  10937. */
  10938. var Hls = /*#__PURE__*/function () {
  10939. Hls.isSupported = function isSupported() {
  10940. return (0,_is_supported__WEBPACK_IMPORTED_MODULE_7__.isSupported)();
  10941. };
  10942. /**
  10943. * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
  10944. *
  10945. * @constructs Hls
  10946. * @param {HlsConfig} config
  10947. */
  10948. function Hls(userConfig) {
  10949. if (userConfig === void 0) {
  10950. userConfig = {};
  10951. }
  10952. this.config = void 0;
  10953. this.userConfig = void 0;
  10954. this.coreComponents = void 0;
  10955. this.networkControllers = void 0;
  10956. this._emitter = new eventemitter3__WEBPACK_IMPORTED_MODULE_10__.EventEmitter();
  10957. this._autoLevelCapping = void 0;
  10958. this.abrController = void 0;
  10959. this.bufferController = void 0;
  10960. this.capLevelController = void 0;
  10961. this.latencyController = void 0;
  10962. this.levelController = void 0;
  10963. this.streamController = void 0;
  10964. this.audioTrackController = void 0;
  10965. this.subtitleTrackController = void 0;
  10966. this.emeController = void 0;
  10967. this.cmcdController = void 0;
  10968. this._media = null;
  10969. this.url = null;
  10970. var config = this.config = (0,_config__WEBPACK_IMPORTED_MODULE_9__.mergeConfig)(Hls.DefaultConfig, userConfig);
  10971. this.userConfig = userConfig;
  10972. (0,_utils_logger__WEBPACK_IMPORTED_MODULE_8__.enableLogs)(config.debug, 'Hls instance');
  10973. this._autoLevelCapping = -1;
  10974. if (config.progressive) {
  10975. (0,_config__WEBPACK_IMPORTED_MODULE_9__.enableStreamingMode)(config);
  10976. }
  10977. // core controllers and network loaders
  10978. var ConfigAbrController = config.abrController,
  10979. ConfigBufferController = config.bufferController,
  10980. ConfigCapLevelController = config.capLevelController,
  10981. ConfigFpsController = config.fpsController;
  10982. var abrController = this.abrController = new ConfigAbrController(this);
  10983. var bufferController = this.bufferController = new ConfigBufferController(this);
  10984. var capLevelController = this.capLevelController = new ConfigCapLevelController(this);
  10985. var fpsController = new ConfigFpsController(this);
  10986. var playListLoader = new _loader_playlist_loader__WEBPACK_IMPORTED_MODULE_1__["default"](this);
  10987. var id3TrackController = new _controller_id3_track_controller__WEBPACK_IMPORTED_MODULE_2__["default"](this);
  10988. // network controllers
  10989. var levelController = this.levelController = new _controller_level_controller__WEBPACK_IMPORTED_MODULE_4__["default"](this);
  10990. // FragmentTracker must be defined before StreamController because the order of event handling is important
  10991. var fragmentTracker = new _controller_fragment_tracker__WEBPACK_IMPORTED_MODULE_5__.FragmentTracker(this);
  10992. var streamController = this.streamController = new _controller_stream_controller__WEBPACK_IMPORTED_MODULE_6__["default"](this, fragmentTracker);
  10993. // Cap level controller uses streamController to flush the buffer
  10994. capLevelController.setStreamController(streamController);
  10995. // fpsController uses streamController to switch when frames are being dropped
  10996. fpsController.setStreamController(streamController);
  10997. var networkControllers = [playListLoader, levelController, streamController];
  10998. this.networkControllers = networkControllers;
  10999. var coreComponents = [abrController, bufferController, capLevelController, fpsController, id3TrackController, fragmentTracker];
  11000. this.audioTrackController = this.createController(config.audioTrackController, null, networkControllers);
  11001. this.createController(config.audioStreamController, fragmentTracker, networkControllers);
  11002. // subtitleTrackController must be defined before because the order of event handling is important
  11003. this.subtitleTrackController = this.createController(config.subtitleTrackController, null, networkControllers);
  11004. this.createController(config.subtitleStreamController, fragmentTracker, networkControllers);
  11005. this.createController(config.timelineController, null, coreComponents);
  11006. this.emeController = this.createController(config.emeController, null, coreComponents);
  11007. this.cmcdController = this.createController(config.cmcdController, null, coreComponents);
  11008. this.latencyController = this.createController(_controller_latency_controller__WEBPACK_IMPORTED_MODULE_3__["default"], null, coreComponents);
  11009. this.coreComponents = coreComponents;
  11010. }
  11011. var _proto = Hls.prototype;
  11012. _proto.createController = function createController(ControllerClass, fragmentTracker, components) {
  11013. if (ControllerClass) {
  11014. var controllerInstance = fragmentTracker ? new ControllerClass(this, fragmentTracker) : new ControllerClass(this);
  11015. if (components) {
  11016. components.push(controllerInstance);
  11017. }
  11018. return controllerInstance;
  11019. }
  11020. return null;
  11021. }
  11022. // Delegate the EventEmitter through the public API of Hls.js
  11023. ;
  11024. _proto.on = function on(event, listener, context) {
  11025. if (context === void 0) {
  11026. context = this;
  11027. }
  11028. this._emitter.on(event, listener, context);
  11029. };
  11030. _proto.once = function once(event, listener, context) {
  11031. if (context === void 0) {
  11032. context = this;
  11033. }
  11034. this._emitter.once(event, listener, context);
  11035. };
  11036. _proto.removeAllListeners = function removeAllListeners(event) {
  11037. this._emitter.removeAllListeners(event);
  11038. };
  11039. _proto.off = function off(event, listener, context, once) {
  11040. if (context === void 0) {
  11041. context = this;
  11042. }
  11043. this._emitter.off(event, listener, context, once);
  11044. };
  11045. _proto.listeners = function listeners(event) {
  11046. return this._emitter.listeners(event);
  11047. };
  11048. _proto.emit = function emit(event, name, eventObject) {
  11049. return this._emitter.emit(event, name, eventObject);
  11050. };
  11051. _proto.trigger = function trigger(event, eventObject) {
  11052. if (this.config.debug) {
  11053. return this.emit(event, event, eventObject);
  11054. } else {
  11055. try {
  11056. return this.emit(event, event, eventObject);
  11057. } catch (e) {
  11058. _utils_logger__WEBPACK_IMPORTED_MODULE_8__.logger.error('An internal error happened while handling event ' + event + '. Error message: "' + e.message + '". Here is a stacktrace:', e);
  11059. this.trigger(_events__WEBPACK_IMPORTED_MODULE_11__.Events.ERROR, {
  11060. type: _errors__WEBPACK_IMPORTED_MODULE_12__.ErrorTypes.OTHER_ERROR,
  11061. details: _errors__WEBPACK_IMPORTED_MODULE_12__.ErrorDetails.INTERNAL_EXCEPTION,
  11062. fatal: false,
  11063. event: event,
  11064. error: e
  11065. });
  11066. }
  11067. }
  11068. return false;
  11069. };
  11070. _proto.listenerCount = function listenerCount(event) {
  11071. return this._emitter.listenerCount(event);
  11072. }
  11073. /**
  11074. * Dispose of the instance
  11075. */;
  11076. _proto.destroy = function destroy() {
  11077. _utils_logger__WEBPACK_IMPORTED_MODULE_8__.logger.log('destroy');
  11078. this.trigger(_events__WEBPACK_IMPORTED_MODULE_11__.Events.DESTROYING, undefined);
  11079. this.detachMedia();
  11080. this.removeAllListeners();
  11081. this._autoLevelCapping = -1;
  11082. this.url = null;
  11083. this.networkControllers.forEach(function (component) {
  11084. return component.destroy();
  11085. });
  11086. this.networkControllers.length = 0;
  11087. this.coreComponents.forEach(function (component) {
  11088. return component.destroy();
  11089. });
  11090. this.coreComponents.length = 0;
  11091. }
  11092. /**
  11093. * Attaches Hls.js to a media element
  11094. * @param {HTMLMediaElement} media
  11095. */;
  11096. _proto.attachMedia = function attachMedia(media) {
  11097. _utils_logger__WEBPACK_IMPORTED_MODULE_8__.logger.log('attachMedia');
  11098. this._media = media;
  11099. this.trigger(_events__WEBPACK_IMPORTED_MODULE_11__.Events.MEDIA_ATTACHING, {
  11100. media: media
  11101. });
  11102. }
  11103. /**
  11104. * Detach Hls.js from the media
  11105. */;
  11106. _proto.detachMedia = function detachMedia() {
  11107. _utils_logger__WEBPACK_IMPORTED_MODULE_8__.logger.log('detachMedia');
  11108. this.trigger(_events__WEBPACK_IMPORTED_MODULE_11__.Events.MEDIA_DETACHING, undefined);
  11109. this._media = null;
  11110. }
  11111. /**
  11112. * Set the source URL. Can be relative or absolute.
  11113. * @param {string} url
  11114. */;
  11115. _proto.loadSource = function loadSource(url) {
  11116. this.stopLoad();
  11117. var media = this.media;
  11118. var loadedSource = this.url;
  11119. var loadingSource = this.url = url_toolkit__WEBPACK_IMPORTED_MODULE_0__.buildAbsoluteURL(self.location.href, url, {
  11120. alwaysNormalize: true
  11121. });
  11122. _utils_logger__WEBPACK_IMPORTED_MODULE_8__.logger.log("loadSource:" + loadingSource);
  11123. if (media && loadedSource && loadedSource !== loadingSource && this.bufferController.hasSourceTypes()) {
  11124. this.detachMedia();
  11125. this.attachMedia(media);
  11126. }
  11127. // when attaching to a source URL, trigger a playlist load
  11128. this.trigger(_events__WEBPACK_IMPORTED_MODULE_11__.Events.MANIFEST_LOADING, {
  11129. url: url
  11130. });
  11131. }
  11132. /**
  11133. * Start loading data from the stream source.
  11134. * Depending on default config, client starts loading automatically when a source is set.
  11135. *
  11136. * @param {number} startPosition Set the start position to stream from
  11137. * @default -1 None (from earliest point)
  11138. */;
  11139. _proto.startLoad = function startLoad(startPosition) {
  11140. if (startPosition === void 0) {
  11141. startPosition = -1;
  11142. }
  11143. _utils_logger__WEBPACK_IMPORTED_MODULE_8__.logger.log("startLoad(" + startPosition + ")");
  11144. this.networkControllers.forEach(function (controller) {
  11145. controller.startLoad(startPosition);
  11146. });
  11147. }
  11148. /**
  11149. * Stop loading of any stream data.
  11150. */;
  11151. _proto.stopLoad = function stopLoad() {
  11152. _utils_logger__WEBPACK_IMPORTED_MODULE_8__.logger.log('stopLoad');
  11153. this.networkControllers.forEach(function (controller) {
  11154. controller.stopLoad();
  11155. });
  11156. }
  11157. /**
  11158. * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
  11159. */;
  11160. _proto.swapAudioCodec = function swapAudioCodec() {
  11161. _utils_logger__WEBPACK_IMPORTED_MODULE_8__.logger.log('swapAudioCodec');
  11162. this.streamController.swapAudioCodec();
  11163. }
  11164. /**
  11165. * When the media-element fails, this allows to detach and then re-attach it
  11166. * as one call (convenience method).
  11167. *
  11168. * Automatic recovery of media-errors by this process is configurable.
  11169. */;
  11170. _proto.recoverMediaError = function recoverMediaError() {
  11171. _utils_logger__WEBPACK_IMPORTED_MODULE_8__.logger.log('recoverMediaError');
  11172. var media = this._media;
  11173. this.detachMedia();
  11174. if (media) {
  11175. this.attachMedia(media);
  11176. }
  11177. };
  11178. _proto.removeLevel = function removeLevel(levelIndex, urlId) {
  11179. if (urlId === void 0) {
  11180. urlId = 0;
  11181. }
  11182. this.levelController.removeLevel(levelIndex, urlId);
  11183. }
  11184. /**
  11185. * @type {Level[]}
  11186. */;
  11187. _createClass(Hls, [{
  11188. key: "levels",
  11189. get: function get() {
  11190. var levels = this.levelController.levels;
  11191. return levels ? levels : [];
  11192. }
  11193. /**
  11194. * Index of quality level currently played
  11195. * @type {number}
  11196. */
  11197. }, {
  11198. key: "currentLevel",
  11199. get: function get() {
  11200. return this.streamController.currentLevel;
  11201. }
  11202. /**
  11203. * Set quality level index immediately .
  11204. * This will flush the current buffer to replace the quality asap.
  11205. * That means playback will interrupt at least shortly to re-buffer and re-sync eventually.
  11206. * @type {number} -1 for automatic level selection
  11207. */,
  11208. set: function set(newLevel) {
  11209. _utils_logger__WEBPACK_IMPORTED_MODULE_8__.logger.log("set currentLevel:" + newLevel);
  11210. this.loadLevel = newLevel;
  11211. this.abrController.clearTimer();
  11212. this.streamController.immediateLevelSwitch();
  11213. }
  11214. /**
  11215. * Index of next quality level loaded as scheduled by stream controller.
  11216. * @type {number}
  11217. */
  11218. }, {
  11219. key: "nextLevel",
  11220. get: function get() {
  11221. return this.streamController.nextLevel;
  11222. }
  11223. /**
  11224. * Set quality level index for next loaded data.
  11225. * This will switch the video quality asap, without interrupting playback.
  11226. * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
  11227. * @type {number} -1 for automatic level selection
  11228. */,
  11229. set: function set(newLevel) {
  11230. _utils_logger__WEBPACK_IMPORTED_MODULE_8__.logger.log("set nextLevel:" + newLevel);
  11231. this.levelController.manualLevel = newLevel;
  11232. this.streamController.nextLevelSwitch();
  11233. }
  11234. /**
  11235. * Return the quality level of the currently or last (of none is loaded currently) segment
  11236. * @type {number}
  11237. */
  11238. }, {
  11239. key: "loadLevel",
  11240. get: function get() {
  11241. return this.levelController.level;
  11242. }
  11243. /**
  11244. * Set quality level index for next loaded data in a conservative way.
  11245. * This will switch the quality without flushing, but interrupt current loading.
  11246. * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
  11247. * @type {number} newLevel -1 for automatic level selection
  11248. */,
  11249. set: function set(newLevel) {
  11250. _utils_logger__WEBPACK_IMPORTED_MODULE_8__.logger.log("set loadLevel:" + newLevel);
  11251. this.levelController.manualLevel = newLevel;
  11252. }
  11253. /**
  11254. * get next quality level loaded
  11255. * @type {number}
  11256. */
  11257. }, {
  11258. key: "nextLoadLevel",
  11259. get: function get() {
  11260. return this.levelController.nextLoadLevel;
  11261. }
  11262. /**
  11263. * Set quality level of next loaded segment in a fully "non-destructive" way.
  11264. * Same as `loadLevel` but will wait for next switch (until current loading is done).
  11265. * @type {number} level
  11266. */,
  11267. set: function set(level) {
  11268. this.levelController.nextLoadLevel = level;
  11269. }
  11270. /**
  11271. * Return "first level": like a default level, if not set,
  11272. * falls back to index of first level referenced in manifest
  11273. * @type {number}
  11274. */
  11275. }, {
  11276. key: "firstLevel",
  11277. get: function get() {
  11278. return Math.max(this.levelController.firstLevel, this.minAutoLevel);
  11279. }
  11280. /**
  11281. * Sets "first-level", see getter.
  11282. * @type {number}
  11283. */,
  11284. set: function set(newLevel) {
  11285. _utils_logger__WEBPACK_IMPORTED_MODULE_8__.logger.log("set firstLevel:" + newLevel);
  11286. this.levelController.firstLevel = newLevel;
  11287. }
  11288. /**
  11289. * Return start level (level of first fragment that will be played back)
  11290. * if not overrided by user, first level appearing in manifest will be used as start level
  11291. * if -1 : automatic start level selection, playback will start from level matching download bandwidth
  11292. * (determined from download of first segment)
  11293. * @type {number}
  11294. */
  11295. }, {
  11296. key: "startLevel",
  11297. get: function get() {
  11298. return this.levelController.startLevel;
  11299. }
  11300. /**
  11301. * set start level (level of first fragment that will be played back)
  11302. * if not overrided by user, first level appearing in manifest will be used as start level
  11303. * if -1 : automatic start level selection, playback will start from level matching download bandwidth
  11304. * (determined from download of first segment)
  11305. * @type {number} newLevel
  11306. */,
  11307. set: function set(newLevel) {
  11308. _utils_logger__WEBPACK_IMPORTED_MODULE_8__.logger.log("set startLevel:" + newLevel);
  11309. // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel
  11310. if (newLevel !== -1) {
  11311. newLevel = Math.max(newLevel, this.minAutoLevel);
  11312. }
  11313. this.levelController.startLevel = newLevel;
  11314. }
  11315. /**
  11316. * Get the current setting for capLevelToPlayerSize
  11317. *
  11318. * @type {boolean}
  11319. */
  11320. }, {
  11321. key: "capLevelToPlayerSize",
  11322. get: function get() {
  11323. return this.config.capLevelToPlayerSize;
  11324. }
  11325. /**
  11326. * set dynamically set capLevelToPlayerSize against (`CapLevelController`)
  11327. *
  11328. * @type {boolean}
  11329. */,
  11330. set: function set(shouldStartCapping) {
  11331. var newCapLevelToPlayerSize = !!shouldStartCapping;
  11332. if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {
  11333. if (newCapLevelToPlayerSize) {
  11334. this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size.
  11335. } else {
  11336. this.capLevelController.stopCapping();
  11337. this.autoLevelCapping = -1;
  11338. this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap.
  11339. }
  11340. this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;
  11341. }
  11342. }
  11343. /**
  11344. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  11345. * @type {number}
  11346. */
  11347. }, {
  11348. key: "autoLevelCapping",
  11349. get: function get() {
  11350. return this._autoLevelCapping;
  11351. }
  11352. /**
  11353. * get bandwidth estimate
  11354. * @type {number}
  11355. */,
  11356. set:
  11357. /**
  11358. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  11359. * @type {number}
  11360. */
  11361. function set(newLevel) {
  11362. if (this._autoLevelCapping !== newLevel) {
  11363. _utils_logger__WEBPACK_IMPORTED_MODULE_8__.logger.log("set autoLevelCapping:" + newLevel);
  11364. this._autoLevelCapping = newLevel;
  11365. }
  11366. }
  11367. /**
  11368. * True when automatic level selection enabled
  11369. * @type {boolean}
  11370. */
  11371. }, {
  11372. key: "bandwidthEstimate",
  11373. get: function get() {
  11374. var bwEstimator = this.abrController.bwEstimator;
  11375. if (!bwEstimator) {
  11376. return NaN;
  11377. }
  11378. return bwEstimator.getEstimate();
  11379. }
  11380. }, {
  11381. key: "autoLevelEnabled",
  11382. get: function get() {
  11383. return this.levelController.manualLevel === -1;
  11384. }
  11385. /**
  11386. * Level set manually (if any)
  11387. * @type {number}
  11388. */
  11389. }, {
  11390. key: "manualLevel",
  11391. get: function get() {
  11392. return this.levelController.manualLevel;
  11393. }
  11394. /**
  11395. * min level selectable in auto mode according to config.minAutoBitrate
  11396. * @type {number}
  11397. */
  11398. }, {
  11399. key: "minAutoLevel",
  11400. get: function get() {
  11401. var levels = this.levels,
  11402. minAutoBitrate = this.config.minAutoBitrate;
  11403. if (!levels) return 0;
  11404. var len = levels.length;
  11405. for (var i = 0; i < len; i++) {
  11406. if (levels[i].maxBitrate >= minAutoBitrate) {
  11407. return i;
  11408. }
  11409. }
  11410. return 0;
  11411. }
  11412. /**
  11413. * max level selectable in auto mode according to autoLevelCapping
  11414. * @type {number}
  11415. */
  11416. }, {
  11417. key: "maxAutoLevel",
  11418. get: function get() {
  11419. var levels = this.levels,
  11420. autoLevelCapping = this.autoLevelCapping;
  11421. var maxAutoLevel;
  11422. if (autoLevelCapping === -1 && levels && levels.length) {
  11423. maxAutoLevel = levels.length - 1;
  11424. } else {
  11425. maxAutoLevel = autoLevelCapping;
  11426. }
  11427. return maxAutoLevel;
  11428. }
  11429. /**
  11430. * next automatically selected quality level
  11431. * @type {number}
  11432. */
  11433. }, {
  11434. key: "nextAutoLevel",
  11435. get: function get() {
  11436. // ensure next auto level is between min and max auto level
  11437. return Math.min(Math.max(this.abrController.nextAutoLevel, this.minAutoLevel), this.maxAutoLevel);
  11438. }
  11439. /**
  11440. * this setter is used to force next auto level.
  11441. * this is useful to force a switch down in auto mode:
  11442. * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
  11443. * forced value is valid for one fragment. upon successful frag loading at forced level,
  11444. * this value will be resetted to -1 by ABR controller.
  11445. * @type {number}
  11446. */,
  11447. set: function set(nextLevel) {
  11448. this.abrController.nextAutoLevel = Math.max(this.minAutoLevel, nextLevel);
  11449. }
  11450. /**
  11451. * get the datetime value relative to media.currentTime for the active level Program Date Time if present
  11452. * @type {Date}
  11453. */
  11454. }, {
  11455. key: "playingDate",
  11456. get: function get() {
  11457. return this.streamController.currentProgramDateTime;
  11458. }
  11459. }, {
  11460. key: "mainForwardBufferInfo",
  11461. get: function get() {
  11462. return this.streamController.getMainFwdBufferInfo();
  11463. }
  11464. /**
  11465. * @type {AudioTrack[]}
  11466. */
  11467. }, {
  11468. key: "audioTracks",
  11469. get: function get() {
  11470. var audioTrackController = this.audioTrackController;
  11471. return audioTrackController ? audioTrackController.audioTracks : [];
  11472. }
  11473. /**
  11474. * index of the selected audio track (index in audio track lists)
  11475. * @type {number}
  11476. */
  11477. }, {
  11478. key: "audioTrack",
  11479. get: function get() {
  11480. var audioTrackController = this.audioTrackController;
  11481. return audioTrackController ? audioTrackController.audioTrack : -1;
  11482. }
  11483. /**
  11484. * selects an audio track, based on its index in audio track lists
  11485. * @type {number}
  11486. */,
  11487. set: function set(audioTrackId) {
  11488. var audioTrackController = this.audioTrackController;
  11489. if (audioTrackController) {
  11490. audioTrackController.audioTrack = audioTrackId;
  11491. }
  11492. }
  11493. /**
  11494. * get alternate subtitle tracks list from playlist
  11495. * @type {MediaPlaylist[]}
  11496. */
  11497. }, {
  11498. key: "subtitleTracks",
  11499. get: function get() {
  11500. var subtitleTrackController = this.subtitleTrackController;
  11501. return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
  11502. }
  11503. /**
  11504. * index of the selected subtitle track (index in subtitle track lists)
  11505. * @type {number}
  11506. */
  11507. }, {
  11508. key: "subtitleTrack",
  11509. get: function get() {
  11510. var subtitleTrackController = this.subtitleTrackController;
  11511. return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
  11512. },
  11513. set:
  11514. /**
  11515. * select an subtitle track, based on its index in subtitle track lists
  11516. * @type {number}
  11517. */
  11518. function set(subtitleTrackId) {
  11519. var subtitleTrackController = this.subtitleTrackController;
  11520. if (subtitleTrackController) {
  11521. subtitleTrackController.subtitleTrack = subtitleTrackId;
  11522. }
  11523. }
  11524. /**
  11525. * @type {boolean}
  11526. */
  11527. }, {
  11528. key: "media",
  11529. get: function get() {
  11530. return this._media;
  11531. }
  11532. }, {
  11533. key: "subtitleDisplay",
  11534. get: function get() {
  11535. var subtitleTrackController = this.subtitleTrackController;
  11536. return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
  11537. }
  11538. /**
  11539. * Enable/disable subtitle display rendering
  11540. * @type {boolean}
  11541. */,
  11542. set: function set(value) {
  11543. var subtitleTrackController = this.subtitleTrackController;
  11544. if (subtitleTrackController) {
  11545. subtitleTrackController.subtitleDisplay = value;
  11546. }
  11547. }
  11548. /**
  11549. * get mode for Low-Latency HLS loading
  11550. * @type {boolean}
  11551. */
  11552. }, {
  11553. key: "lowLatencyMode",
  11554. get: function get() {
  11555. return this.config.lowLatencyMode;
  11556. }
  11557. /**
  11558. * Enable/disable Low-Latency HLS part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK.
  11559. * @type {boolean}
  11560. */,
  11561. set: function set(mode) {
  11562. this.config.lowLatencyMode = mode;
  11563. }
  11564. /**
  11565. * position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```hls.config.liveSyncDuration```)
  11566. * @type {number}
  11567. */
  11568. }, {
  11569. key: "liveSyncPosition",
  11570. get: function get() {
  11571. return this.latencyController.liveSyncPosition;
  11572. }
  11573. /**
  11574. * estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced)
  11575. * returns 0 before first playlist is loaded
  11576. * @type {number}
  11577. */
  11578. }, {
  11579. key: "latency",
  11580. get: function get() {
  11581. return this.latencyController.latency;
  11582. }
  11583. /**
  11584. * maximum distance from the edge before the player seeks forward to ```hls.liveSyncPosition```
  11585. * configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration```
  11586. * returns 0 before first playlist is loaded
  11587. * @type {number}
  11588. */
  11589. }, {
  11590. key: "maxLatency",
  11591. get: function get() {
  11592. return this.latencyController.maxLatency;
  11593. }
  11594. /**
  11595. * target distance from the edge as calculated by the latency controller
  11596. * @type {number}
  11597. */
  11598. }, {
  11599. key: "targetLatency",
  11600. get: function get() {
  11601. return this.latencyController.targetLatency;
  11602. }
  11603. /**
  11604. * the rate at which the edge of the current live playlist is advancing or 1 if there is none
  11605. * @type {number}
  11606. */
  11607. }, {
  11608. key: "drift",
  11609. get: function get() {
  11610. return this.latencyController.drift;
  11611. }
  11612. /**
  11613. * set to true when startLoad is called before MANIFEST_PARSED event
  11614. * @type {boolean}
  11615. */
  11616. }, {
  11617. key: "forceStartLoad",
  11618. get: function get() {
  11619. return this.streamController.forceStartLoad;
  11620. }
  11621. }], [{
  11622. key: "version",
  11623. get: function get() {
  11624. return undefined;
  11625. }
  11626. }, {
  11627. key: "Events",
  11628. get: function get() {
  11629. return _events__WEBPACK_IMPORTED_MODULE_11__.Events;
  11630. }
  11631. }, {
  11632. key: "ErrorTypes",
  11633. get: function get() {
  11634. return _errors__WEBPACK_IMPORTED_MODULE_12__.ErrorTypes;
  11635. }
  11636. }, {
  11637. key: "ErrorDetails",
  11638. get: function get() {
  11639. return _errors__WEBPACK_IMPORTED_MODULE_12__.ErrorDetails;
  11640. }
  11641. }, {
  11642. key: "DefaultConfig",
  11643. get: function get() {
  11644. if (!Hls.defaultConfig) {
  11645. return _config__WEBPACK_IMPORTED_MODULE_9__.hlsDefaultConfig;
  11646. }
  11647. return Hls.defaultConfig;
  11648. }
  11649. /**
  11650. * @type {HlsConfig}
  11651. */,
  11652. set: function set(defaultConfig) {
  11653. Hls.defaultConfig = defaultConfig;
  11654. }
  11655. }]);
  11656. return Hls;
  11657. }();
  11658. Hls.defaultConfig = void 0;
  11659. /***/ }),
  11660. /***/ "./src/is-supported.ts":
  11661. /*!*****************************!*\
  11662. !*** ./src/is-supported.ts ***!
  11663. \*****************************/
  11664. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  11665. "use strict";
  11666. __webpack_require__.r(__webpack_exports__);
  11667. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  11668. /* harmony export */ "changeTypeSupported": () => (/* binding */ changeTypeSupported),
  11669. /* harmony export */ "isSupported": () => (/* binding */ isSupported)
  11670. /* harmony export */ });
  11671. /* harmony import */ var _utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/mediasource-helper */ "./src/utils/mediasource-helper.ts");
  11672. function getSourceBuffer() {
  11673. return self.SourceBuffer || self.WebKitSourceBuffer;
  11674. }
  11675. function isSupported() {
  11676. var mediaSource = (0,_utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_0__.getMediaSource)();
  11677. if (!mediaSource) {
  11678. return false;
  11679. }
  11680. var sourceBuffer = getSourceBuffer();
  11681. var isTypeSupported = mediaSource && typeof mediaSource.isTypeSupported === 'function' && mediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"');
  11682. // if SourceBuffer is exposed ensure its API is valid
  11683. // safari and old version of Chrome doe not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible
  11684. var sourceBufferValidAPI = !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function';
  11685. return !!isTypeSupported && !!sourceBufferValidAPI;
  11686. }
  11687. function changeTypeSupported() {
  11688. var _sourceBuffer$prototy;
  11689. var sourceBuffer = getSourceBuffer();
  11690. return typeof (sourceBuffer === null || sourceBuffer === void 0 ? void 0 : (_sourceBuffer$prototy = sourceBuffer.prototype) === null || _sourceBuffer$prototy === void 0 ? void 0 : _sourceBuffer$prototy.changeType) === 'function';
  11691. }
  11692. /***/ }),
  11693. /***/ "./src/loader/date-range.ts":
  11694. /*!**********************************!*\
  11695. !*** ./src/loader/date-range.ts ***!
  11696. \**********************************/
  11697. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  11698. "use strict";
  11699. __webpack_require__.r(__webpack_exports__);
  11700. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  11701. /* harmony export */ "DateRange": () => (/* binding */ DateRange),
  11702. /* harmony export */ "DateRangeAttribute": () => (/* binding */ DateRangeAttribute)
  11703. /* harmony export */ });
  11704. /* harmony import */ var _Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
  11705. /* harmony import */ var _utils_attr_list__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/attr-list */ "./src/utils/attr-list.ts");
  11706. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
  11707. function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
  11708. 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, _toPropertyKey(descriptor.key), descriptor); } }
  11709. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  11710. function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
  11711. function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
  11712. var DateRangeAttribute;
  11713. (function (DateRangeAttribute) {
  11714. DateRangeAttribute["ID"] = "ID";
  11715. DateRangeAttribute["CLASS"] = "CLASS";
  11716. DateRangeAttribute["START_DATE"] = "START-DATE";
  11717. DateRangeAttribute["DURATION"] = "DURATION";
  11718. DateRangeAttribute["END_DATE"] = "END-DATE";
  11719. DateRangeAttribute["END_ON_NEXT"] = "END-ON-NEXT";
  11720. DateRangeAttribute["PLANNED_DURATION"] = "PLANNED-DURATION";
  11721. DateRangeAttribute["SCTE35_OUT"] = "SCTE35-OUT";
  11722. DateRangeAttribute["SCTE35_IN"] = "SCTE35-IN";
  11723. })(DateRangeAttribute || (DateRangeAttribute = {}));
  11724. var DateRange = /*#__PURE__*/function () {
  11725. function DateRange(dateRangeAttr, dateRangeWithSameId) {
  11726. this.attr = void 0;
  11727. this._startDate = void 0;
  11728. this._endDate = void 0;
  11729. this._badValueForSameId = void 0;
  11730. if (dateRangeWithSameId) {
  11731. var previousAttr = dateRangeWithSameId.attr;
  11732. for (var key in previousAttr) {
  11733. if (Object.prototype.hasOwnProperty.call(dateRangeAttr, key) && dateRangeAttr[key] !== previousAttr[key]) {
  11734. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.warn("DATERANGE tag attribute: \"" + key + "\" does not match for tags with ID: \"" + dateRangeAttr.ID + "\"");
  11735. this._badValueForSameId = key;
  11736. break;
  11737. }
  11738. }
  11739. // Merge DateRange tags with the same ID
  11740. dateRangeAttr = _extends(new _utils_attr_list__WEBPACK_IMPORTED_MODULE_1__.AttrList({}), previousAttr, dateRangeAttr);
  11741. }
  11742. this.attr = dateRangeAttr;
  11743. this._startDate = new Date(dateRangeAttr[DateRangeAttribute.START_DATE]);
  11744. if (DateRangeAttribute.END_DATE in this.attr) {
  11745. var endDate = new Date(this.attr[DateRangeAttribute.END_DATE]);
  11746. if ((0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(endDate.getTime())) {
  11747. this._endDate = endDate;
  11748. }
  11749. }
  11750. }
  11751. _createClass(DateRange, [{
  11752. key: "id",
  11753. get: function get() {
  11754. return this.attr.ID;
  11755. }
  11756. }, {
  11757. key: "class",
  11758. get: function get() {
  11759. return this.attr.CLASS;
  11760. }
  11761. }, {
  11762. key: "startDate",
  11763. get: function get() {
  11764. return this._startDate;
  11765. }
  11766. }, {
  11767. key: "endDate",
  11768. get: function get() {
  11769. if (this._endDate) {
  11770. return this._endDate;
  11771. }
  11772. var duration = this.duration;
  11773. if (duration !== null) {
  11774. return new Date(this._startDate.getTime() + duration * 1000);
  11775. }
  11776. return null;
  11777. }
  11778. }, {
  11779. key: "duration",
  11780. get: function get() {
  11781. if (DateRangeAttribute.DURATION in this.attr) {
  11782. var duration = this.attr.decimalFloatingPoint(DateRangeAttribute.DURATION);
  11783. if ((0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(duration)) {
  11784. return duration;
  11785. }
  11786. } else if (this._endDate) {
  11787. return (this._endDate.getTime() - this._startDate.getTime()) / 1000;
  11788. }
  11789. return null;
  11790. }
  11791. }, {
  11792. key: "plannedDuration",
  11793. get: function get() {
  11794. if (DateRangeAttribute.PLANNED_DURATION in this.attr) {
  11795. return this.attr.decimalFloatingPoint(DateRangeAttribute.PLANNED_DURATION);
  11796. }
  11797. return null;
  11798. }
  11799. }, {
  11800. key: "endOnNext",
  11801. get: function get() {
  11802. return this.attr.bool(DateRangeAttribute.END_ON_NEXT);
  11803. }
  11804. }, {
  11805. key: "isValid",
  11806. get: function get() {
  11807. return !!this.id && !this._badValueForSameId && (0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(this.startDate.getTime()) && (this.duration === null || this.duration >= 0) && (!this.endOnNext || !!this.class);
  11808. }
  11809. }]);
  11810. return DateRange;
  11811. }();
  11812. /***/ }),
  11813. /***/ "./src/loader/fragment-loader.ts":
  11814. /*!***************************************!*\
  11815. !*** ./src/loader/fragment-loader.ts ***!
  11816. \***************************************/
  11817. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  11818. "use strict";
  11819. __webpack_require__.r(__webpack_exports__);
  11820. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  11821. /* harmony export */ "LoadError": () => (/* binding */ LoadError),
  11822. /* harmony export */ "default": () => (/* binding */ FragmentLoader)
  11823. /* harmony export */ });
  11824. /* harmony import */ var _Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
  11825. /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
  11826. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  11827. function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
  11828. function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct.bind(); } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
  11829. function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
  11830. function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
  11831. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  11832. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  11833. var MIN_CHUNK_SIZE = Math.pow(2, 17); // 128kb
  11834. var FragmentLoader = /*#__PURE__*/function () {
  11835. function FragmentLoader(config) {
  11836. this.config = void 0;
  11837. this.loader = null;
  11838. this.partLoadTimeout = -1;
  11839. this.config = config;
  11840. }
  11841. var _proto = FragmentLoader.prototype;
  11842. _proto.destroy = function destroy() {
  11843. if (this.loader) {
  11844. this.loader.destroy();
  11845. this.loader = null;
  11846. }
  11847. };
  11848. _proto.abort = function abort() {
  11849. if (this.loader) {
  11850. // Abort the loader for current fragment. Only one may load at any given time
  11851. this.loader.abort();
  11852. }
  11853. };
  11854. _proto.load = function load(frag, _onProgress) {
  11855. var _this = this;
  11856. var url = frag.url;
  11857. if (!url) {
  11858. return Promise.reject(new LoadError({
  11859. type: _errors__WEBPACK_IMPORTED_MODULE_1__.ErrorTypes.NETWORK_ERROR,
  11860. details: _errors__WEBPACK_IMPORTED_MODULE_1__.ErrorDetails.FRAG_LOAD_ERROR,
  11861. fatal: false,
  11862. frag: frag,
  11863. networkDetails: null
  11864. }, "Fragment does not have a " + (url ? 'part list' : 'url')));
  11865. }
  11866. this.abort();
  11867. var config = this.config;
  11868. var FragmentILoader = config.fLoader;
  11869. var DefaultILoader = config.loader;
  11870. return new Promise(function (resolve, reject) {
  11871. if (_this.loader) {
  11872. _this.loader.destroy();
  11873. }
  11874. var loader = _this.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  11875. var loaderContext = createLoaderContext(frag);
  11876. var loaderConfig = {
  11877. timeout: config.fragLoadingTimeOut,
  11878. maxRetry: 0,
  11879. retryDelay: 0,
  11880. maxRetryDelay: config.fragLoadingMaxRetryTimeout,
  11881. highWaterMark: frag.sn === 'initSegment' ? Infinity : MIN_CHUNK_SIZE
  11882. };
  11883. // Assign frag stats to the loader's stats reference
  11884. frag.stats = loader.stats;
  11885. loader.load(loaderContext, loaderConfig, {
  11886. onSuccess: function onSuccess(response, stats, context, networkDetails) {
  11887. _this.resetLoader(frag, loader);
  11888. var payload = response.data;
  11889. if (context.resetIV && frag.decryptdata) {
  11890. frag.decryptdata.iv = new Uint8Array(payload.slice(0, 16));
  11891. payload = payload.slice(16);
  11892. }
  11893. resolve({
  11894. frag: frag,
  11895. part: null,
  11896. payload: payload,
  11897. networkDetails: networkDetails
  11898. });
  11899. },
  11900. onError: function onError(response, context, networkDetails) {
  11901. _this.resetLoader(frag, loader);
  11902. reject(new LoadError({
  11903. type: _errors__WEBPACK_IMPORTED_MODULE_1__.ErrorTypes.NETWORK_ERROR,
  11904. details: _errors__WEBPACK_IMPORTED_MODULE_1__.ErrorDetails.FRAG_LOAD_ERROR,
  11905. fatal: false,
  11906. frag: frag,
  11907. response: response,
  11908. networkDetails: networkDetails
  11909. }));
  11910. },
  11911. onAbort: function onAbort(stats, context, networkDetails) {
  11912. _this.resetLoader(frag, loader);
  11913. reject(new LoadError({
  11914. type: _errors__WEBPACK_IMPORTED_MODULE_1__.ErrorTypes.NETWORK_ERROR,
  11915. details: _errors__WEBPACK_IMPORTED_MODULE_1__.ErrorDetails.INTERNAL_ABORTED,
  11916. fatal: false,
  11917. frag: frag,
  11918. networkDetails: networkDetails
  11919. }));
  11920. },
  11921. onTimeout: function onTimeout(response, context, networkDetails) {
  11922. _this.resetLoader(frag, loader);
  11923. reject(new LoadError({
  11924. type: _errors__WEBPACK_IMPORTED_MODULE_1__.ErrorTypes.NETWORK_ERROR,
  11925. details: _errors__WEBPACK_IMPORTED_MODULE_1__.ErrorDetails.FRAG_LOAD_TIMEOUT,
  11926. fatal: false,
  11927. frag: frag,
  11928. networkDetails: networkDetails
  11929. }));
  11930. },
  11931. onProgress: function onProgress(stats, context, data, networkDetails) {
  11932. if (_onProgress) {
  11933. _onProgress({
  11934. frag: frag,
  11935. part: null,
  11936. payload: data,
  11937. networkDetails: networkDetails
  11938. });
  11939. }
  11940. }
  11941. });
  11942. });
  11943. };
  11944. _proto.loadPart = function loadPart(frag, part, onProgress) {
  11945. var _this2 = this;
  11946. this.abort();
  11947. var config = this.config;
  11948. var FragmentILoader = config.fLoader;
  11949. var DefaultILoader = config.loader;
  11950. return new Promise(function (resolve, reject) {
  11951. if (_this2.loader) {
  11952. _this2.loader.destroy();
  11953. }
  11954. var loader = _this2.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  11955. var loaderContext = createLoaderContext(frag, part);
  11956. var loaderConfig = {
  11957. timeout: config.fragLoadingTimeOut,
  11958. maxRetry: 0,
  11959. retryDelay: 0,
  11960. maxRetryDelay: config.fragLoadingMaxRetryTimeout,
  11961. highWaterMark: MIN_CHUNK_SIZE
  11962. };
  11963. // Assign part stats to the loader's stats reference
  11964. part.stats = loader.stats;
  11965. loader.load(loaderContext, loaderConfig, {
  11966. onSuccess: function onSuccess(response, stats, context, networkDetails) {
  11967. _this2.resetLoader(frag, loader);
  11968. _this2.updateStatsFromPart(frag, part);
  11969. var partLoadedData = {
  11970. frag: frag,
  11971. part: part,
  11972. payload: response.data,
  11973. networkDetails: networkDetails
  11974. };
  11975. onProgress(partLoadedData);
  11976. resolve(partLoadedData);
  11977. },
  11978. onError: function onError(response, context, networkDetails) {
  11979. _this2.resetLoader(frag, loader);
  11980. reject(new LoadError({
  11981. type: _errors__WEBPACK_IMPORTED_MODULE_1__.ErrorTypes.NETWORK_ERROR,
  11982. details: _errors__WEBPACK_IMPORTED_MODULE_1__.ErrorDetails.FRAG_LOAD_ERROR,
  11983. fatal: false,
  11984. frag: frag,
  11985. part: part,
  11986. response: response,
  11987. networkDetails: networkDetails
  11988. }));
  11989. },
  11990. onAbort: function onAbort(stats, context, networkDetails) {
  11991. frag.stats.aborted = part.stats.aborted;
  11992. _this2.resetLoader(frag, loader);
  11993. reject(new LoadError({
  11994. type: _errors__WEBPACK_IMPORTED_MODULE_1__.ErrorTypes.NETWORK_ERROR,
  11995. details: _errors__WEBPACK_IMPORTED_MODULE_1__.ErrorDetails.INTERNAL_ABORTED,
  11996. fatal: false,
  11997. frag: frag,
  11998. part: part,
  11999. networkDetails: networkDetails
  12000. }));
  12001. },
  12002. onTimeout: function onTimeout(response, context, networkDetails) {
  12003. _this2.resetLoader(frag, loader);
  12004. reject(new LoadError({
  12005. type: _errors__WEBPACK_IMPORTED_MODULE_1__.ErrorTypes.NETWORK_ERROR,
  12006. details: _errors__WEBPACK_IMPORTED_MODULE_1__.ErrorDetails.FRAG_LOAD_TIMEOUT,
  12007. fatal: false,
  12008. frag: frag,
  12009. part: part,
  12010. networkDetails: networkDetails
  12011. }));
  12012. }
  12013. });
  12014. });
  12015. };
  12016. _proto.updateStatsFromPart = function updateStatsFromPart(frag, part) {
  12017. var fragStats = frag.stats;
  12018. var partStats = part.stats;
  12019. var partTotal = partStats.total;
  12020. fragStats.loaded += partStats.loaded;
  12021. if (partTotal) {
  12022. var estTotalParts = Math.round(frag.duration / part.duration);
  12023. var estLoadedParts = Math.min(Math.round(fragStats.loaded / partTotal), estTotalParts);
  12024. var estRemainingParts = estTotalParts - estLoadedParts;
  12025. var estRemainingBytes = estRemainingParts * Math.round(fragStats.loaded / estLoadedParts);
  12026. fragStats.total = fragStats.loaded + estRemainingBytes;
  12027. } else {
  12028. fragStats.total = Math.max(fragStats.loaded, fragStats.total);
  12029. }
  12030. var fragLoading = fragStats.loading;
  12031. var partLoading = partStats.loading;
  12032. if (fragLoading.start) {
  12033. // add to fragment loader latency
  12034. fragLoading.first += partLoading.first - partLoading.start;
  12035. } else {
  12036. fragLoading.start = partLoading.start;
  12037. fragLoading.first = partLoading.first;
  12038. }
  12039. fragLoading.end = partLoading.end;
  12040. };
  12041. _proto.resetLoader = function resetLoader(frag, loader) {
  12042. frag.loader = null;
  12043. if (this.loader === loader) {
  12044. self.clearTimeout(this.partLoadTimeout);
  12045. this.loader = null;
  12046. }
  12047. loader.destroy();
  12048. };
  12049. return FragmentLoader;
  12050. }();
  12051. function createLoaderContext(frag, part) {
  12052. if (part === void 0) {
  12053. part = null;
  12054. }
  12055. var segment = part || frag;
  12056. var loaderContext = {
  12057. frag: frag,
  12058. part: part,
  12059. responseType: 'arraybuffer',
  12060. url: segment.url,
  12061. headers: {},
  12062. rangeStart: 0,
  12063. rangeEnd: 0
  12064. };
  12065. var start = segment.byteRangeStartOffset;
  12066. var end = segment.byteRangeEndOffset;
  12067. if ((0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(start) && (0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(end)) {
  12068. var _frag$decryptdata;
  12069. var byteRangeStart = start;
  12070. var byteRangeEnd = end;
  12071. if (frag.sn === 'initSegment' && ((_frag$decryptdata = frag.decryptdata) === null || _frag$decryptdata === void 0 ? void 0 : _frag$decryptdata.method) === 'AES-128') {
  12072. // MAP segment encrypted with method 'AES-128', when served with HTTP Range,
  12073. // has the unencrypted size specified in the range.
  12074. // Ref: https://tools.ietf.org/html/draft-pantos-hls-rfc8216bis-08#section-6.3.6
  12075. var fragmentLen = end - start;
  12076. if (fragmentLen % 16) {
  12077. byteRangeEnd = end + (16 - fragmentLen % 16);
  12078. }
  12079. if (start !== 0) {
  12080. loaderContext.resetIV = true;
  12081. byteRangeStart = start - 16;
  12082. }
  12083. }
  12084. loaderContext.rangeStart = byteRangeStart;
  12085. loaderContext.rangeEnd = byteRangeEnd;
  12086. }
  12087. return loaderContext;
  12088. }
  12089. var LoadError = /*#__PURE__*/function (_Error) {
  12090. _inheritsLoose(LoadError, _Error);
  12091. function LoadError(data) {
  12092. var _this3;
  12093. for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  12094. params[_key - 1] = arguments[_key];
  12095. }
  12096. _this3 = _Error.call.apply(_Error, [this].concat(params)) || this;
  12097. _this3.data = void 0;
  12098. _this3.data = data;
  12099. return _this3;
  12100. }
  12101. return LoadError;
  12102. }( /*#__PURE__*/_wrapNativeSuper(Error));
  12103. /***/ }),
  12104. /***/ "./src/loader/fragment.ts":
  12105. /*!********************************!*\
  12106. !*** ./src/loader/fragment.ts ***!
  12107. \********************************/
  12108. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  12109. "use strict";
  12110. __webpack_require__.r(__webpack_exports__);
  12111. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  12112. /* harmony export */ "BaseSegment": () => (/* binding */ BaseSegment),
  12113. /* harmony export */ "ElementaryStreamTypes": () => (/* binding */ ElementaryStreamTypes),
  12114. /* harmony export */ "Fragment": () => (/* binding */ Fragment),
  12115. /* harmony export */ "Part": () => (/* binding */ Part)
  12116. /* harmony export */ });
  12117. /* harmony import */ var _Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
  12118. /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! url-toolkit */ "./node_modules/.pnpm/url-toolkit@2.2.5/node_modules/url-toolkit/src/url-toolkit.js");
  12119. /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_1__);
  12120. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
  12121. /* harmony import */ var _level_key__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./level-key */ "./src/loader/level-key.ts");
  12122. /* harmony import */ var _load_stats__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./load-stats */ "./src/loader/load-stats.ts");
  12123. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  12124. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  12125. 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, _toPropertyKey(descriptor.key), descriptor); } }
  12126. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  12127. function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
  12128. function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
  12129. var ElementaryStreamTypes;
  12130. (function (ElementaryStreamTypes) {
  12131. ElementaryStreamTypes["AUDIO"] = "audio";
  12132. ElementaryStreamTypes["VIDEO"] = "video";
  12133. ElementaryStreamTypes["AUDIOVIDEO"] = "audiovideo";
  12134. })(ElementaryStreamTypes || (ElementaryStreamTypes = {}));
  12135. var BaseSegment = /*#__PURE__*/function () {
  12136. // baseurl is the URL to the playlist
  12137. // relurl is the portion of the URL that comes from inside the playlist.
  12138. // Holds the types of data this fragment supports
  12139. function BaseSegment(baseurl) {
  12140. var _this$elementaryStrea;
  12141. this._byteRange = null;
  12142. this._url = null;
  12143. this.baseurl = void 0;
  12144. this.relurl = void 0;
  12145. this.elementaryStreams = (_this$elementaryStrea = {}, _this$elementaryStrea[ElementaryStreamTypes.AUDIO] = null, _this$elementaryStrea[ElementaryStreamTypes.VIDEO] = null, _this$elementaryStrea[ElementaryStreamTypes.AUDIOVIDEO] = null, _this$elementaryStrea);
  12146. this.baseurl = baseurl;
  12147. }
  12148. // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array
  12149. var _proto = BaseSegment.prototype;
  12150. _proto.setByteRange = function setByteRange(value, previous) {
  12151. var params = value.split('@', 2);
  12152. var byteRange = [];
  12153. if (params.length === 1) {
  12154. byteRange[0] = previous ? previous.byteRangeEndOffset : 0;
  12155. } else {
  12156. byteRange[0] = parseInt(params[1]);
  12157. }
  12158. byteRange[1] = parseInt(params[0]) + byteRange[0];
  12159. this._byteRange = byteRange;
  12160. };
  12161. _createClass(BaseSegment, [{
  12162. key: "byteRange",
  12163. get: function get() {
  12164. if (!this._byteRange) {
  12165. return [];
  12166. }
  12167. return this._byteRange;
  12168. }
  12169. }, {
  12170. key: "byteRangeStartOffset",
  12171. get: function get() {
  12172. return this.byteRange[0];
  12173. }
  12174. }, {
  12175. key: "byteRangeEndOffset",
  12176. get: function get() {
  12177. return this.byteRange[1];
  12178. }
  12179. }, {
  12180. key: "url",
  12181. get: function get() {
  12182. if (!this._url && this.baseurl && this.relurl) {
  12183. this._url = (0,url_toolkit__WEBPACK_IMPORTED_MODULE_1__.buildAbsoluteURL)(this.baseurl, this.relurl, {
  12184. alwaysNormalize: true
  12185. });
  12186. }
  12187. return this._url || '';
  12188. },
  12189. set: function set(value) {
  12190. this._url = value;
  12191. }
  12192. }]);
  12193. return BaseSegment;
  12194. }();
  12195. var Fragment = /*#__PURE__*/function (_BaseSegment) {
  12196. _inheritsLoose(Fragment, _BaseSegment);
  12197. // EXTINF has to be present for a m3u8 to be considered valid
  12198. // sn notates the sequence number for a segment, and if set to a string can be 'initSegment'
  12199. // levelkey is the EXT-X-KEY that applies to this segment for decryption
  12200. // core difference from the private field _decryptdata is the lack of the initialized IV
  12201. // _decryptdata will set the IV for this segment based on the segment number in the fragment
  12202. // A string representing the fragment type
  12203. // A reference to the loader. Set while the fragment is loading, and removed afterwards. Used to abort fragment loading
  12204. // A reference to the key loader. Set while the key is loading, and removed afterwards. Used to abort key loading
  12205. // The level/track index to which the fragment belongs
  12206. // The continuity counter of the fragment
  12207. // The starting Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.
  12208. // The ending Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.
  12209. // The latest Presentation Time Stamp (PTS) appended to the buffer.
  12210. // The starting Decode Time Stamp (DTS) of the fragment. Set after transmux complete.
  12211. // The ending Decode Time Stamp (DTS) of the fragment. Set after transmux complete.
  12212. // The start time of the fragment, as listed in the manifest. Updated after transmux complete.
  12213. // Set by `updateFragPTSDTS` in level-helper
  12214. // The maximum starting Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.
  12215. // The minimum ending Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.
  12216. // Load/parse timing information
  12217. // A flag indicating whether the segment was downloaded in order to test bitrate, and was not buffered
  12218. // #EXTINF segment title
  12219. // The Media Initialization Section for this segment
  12220. function Fragment(type, baseurl) {
  12221. var _this;
  12222. _this = _BaseSegment.call(this, baseurl) || this;
  12223. _this._decryptdata = null;
  12224. _this.rawProgramDateTime = null;
  12225. _this.programDateTime = null;
  12226. _this.tagList = [];
  12227. _this.duration = 0;
  12228. _this.sn = 0;
  12229. _this.levelkey = void 0;
  12230. _this.type = void 0;
  12231. _this.loader = null;
  12232. _this.keyLoader = null;
  12233. _this.level = -1;
  12234. _this.cc = 0;
  12235. _this.startPTS = void 0;
  12236. _this.endPTS = void 0;
  12237. _this.appendedPTS = void 0;
  12238. _this.startDTS = void 0;
  12239. _this.endDTS = void 0;
  12240. _this.start = 0;
  12241. _this.deltaPTS = void 0;
  12242. _this.maxStartPTS = void 0;
  12243. _this.minEndPTS = void 0;
  12244. _this.stats = new _load_stats__WEBPACK_IMPORTED_MODULE_4__.LoadStats();
  12245. _this.urlId = 0;
  12246. _this.data = void 0;
  12247. _this.bitrateTest = false;
  12248. _this.title = null;
  12249. _this.initSegment = null;
  12250. _this.type = type;
  12251. return _this;
  12252. }
  12253. var _proto2 = Fragment.prototype;
  12254. _proto2.abortRequests = function abortRequests() {
  12255. var _this$loader, _this$keyLoader;
  12256. (_this$loader = this.loader) === null || _this$loader === void 0 ? void 0 : _this$loader.abort();
  12257. (_this$keyLoader = this.keyLoader) === null || _this$keyLoader === void 0 ? void 0 : _this$keyLoader.abort();
  12258. }
  12259. /**
  12260. * Utility method for parseLevelPlaylist to create an initialization vector for a given segment
  12261. * @param {number} segmentNumber - segment number to generate IV with
  12262. * @returns {Uint8Array}
  12263. */;
  12264. _proto2.createInitializationVector = function createInitializationVector(segmentNumber) {
  12265. var uint8View = new Uint8Array(16);
  12266. for (var i = 12; i < 16; i++) {
  12267. uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff;
  12268. }
  12269. return uint8View;
  12270. }
  12271. /**
  12272. * Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data
  12273. * @param levelkey - a playlist's encryption info
  12274. * @param segmentNumber - the fragment's segment number
  12275. * @returns {LevelKey} - an object to be applied as a fragment's decryptdata
  12276. */;
  12277. _proto2.setDecryptDataFromLevelKey = function setDecryptDataFromLevelKey(levelkey, segmentNumber) {
  12278. var decryptdata = levelkey;
  12279. if ((levelkey === null || levelkey === void 0 ? void 0 : levelkey.method) === 'AES-128' && levelkey.uri && !levelkey.iv) {
  12280. decryptdata = _level_key__WEBPACK_IMPORTED_MODULE_3__.LevelKey.fromURI(levelkey.uri);
  12281. decryptdata.method = levelkey.method;
  12282. decryptdata.iv = this.createInitializationVector(segmentNumber);
  12283. decryptdata.keyFormat = 'identity';
  12284. }
  12285. return decryptdata;
  12286. };
  12287. _proto2.setElementaryStreamInfo = function setElementaryStreamInfo(type, startPTS, endPTS, startDTS, endDTS, partial) {
  12288. if (partial === void 0) {
  12289. partial = false;
  12290. }
  12291. var elementaryStreams = this.elementaryStreams;
  12292. var info = elementaryStreams[type];
  12293. if (!info) {
  12294. elementaryStreams[type] = {
  12295. startPTS: startPTS,
  12296. endPTS: endPTS,
  12297. startDTS: startDTS,
  12298. endDTS: endDTS,
  12299. partial: partial
  12300. };
  12301. return;
  12302. }
  12303. info.startPTS = Math.min(info.startPTS, startPTS);
  12304. info.endPTS = Math.max(info.endPTS, endPTS);
  12305. info.startDTS = Math.min(info.startDTS, startDTS);
  12306. info.endDTS = Math.max(info.endDTS, endDTS);
  12307. };
  12308. _proto2.clearElementaryStreamInfo = function clearElementaryStreamInfo() {
  12309. var elementaryStreams = this.elementaryStreams;
  12310. elementaryStreams[ElementaryStreamTypes.AUDIO] = null;
  12311. elementaryStreams[ElementaryStreamTypes.VIDEO] = null;
  12312. elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO] = null;
  12313. };
  12314. _createClass(Fragment, [{
  12315. key: "decryptdata",
  12316. get: function get() {
  12317. if (!this.levelkey && !this._decryptdata) {
  12318. return null;
  12319. }
  12320. if (!this._decryptdata && this.levelkey) {
  12321. var sn = this.sn;
  12322. if (typeof sn !== 'number') {
  12323. // We are fetching decryption data for a initialization segment
  12324. // If the segment was encrypted with AES-128
  12325. // It must have an IV defined. We cannot substitute the Segment Number in.
  12326. if (this.levelkey && this.levelkey.method === 'AES-128' && !this.levelkey.iv) {
  12327. _utils_logger__WEBPACK_IMPORTED_MODULE_2__.logger.warn("missing IV for initialization segment with method=\"" + this.levelkey.method + "\" - compliance issue");
  12328. }
  12329. /*
  12330. Be converted to a Number.
  12331. 'initSegment' will become NaN.
  12332. NaN, which when converted through ToInt32() -> +0.
  12333. ---
  12334. Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation.
  12335. */
  12336. sn = 0;
  12337. }
  12338. this._decryptdata = this.setDecryptDataFromLevelKey(this.levelkey, sn);
  12339. }
  12340. return this._decryptdata;
  12341. }
  12342. }, {
  12343. key: "end",
  12344. get: function get() {
  12345. return this.start + this.duration;
  12346. }
  12347. }, {
  12348. key: "endProgramDateTime",
  12349. get: function get() {
  12350. if (this.programDateTime === null) {
  12351. return null;
  12352. }
  12353. if (!(0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(this.programDateTime)) {
  12354. return null;
  12355. }
  12356. var duration = !(0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(this.duration) ? 0 : this.duration;
  12357. return this.programDateTime + duration * 1000;
  12358. }
  12359. }, {
  12360. key: "encrypted",
  12361. get: function get() {
  12362. var _this$decryptdata;
  12363. // At the m3u8-parser level we need to add support for manifest signalled keyformats
  12364. // when we want the fragment to start reporting that it is encrypted.
  12365. // Currently, keyFormat will only be set for identity keys
  12366. if ((_this$decryptdata = this.decryptdata) !== null && _this$decryptdata !== void 0 && _this$decryptdata.keyFormat && this.decryptdata.uri) {
  12367. return true;
  12368. }
  12369. return false;
  12370. }
  12371. }]);
  12372. return Fragment;
  12373. }(BaseSegment);
  12374. var Part = /*#__PURE__*/function (_BaseSegment2) {
  12375. _inheritsLoose(Part, _BaseSegment2);
  12376. function Part(partAttrs, frag, baseurl, index, previous) {
  12377. var _this2;
  12378. _this2 = _BaseSegment2.call(this, baseurl) || this;
  12379. _this2.fragOffset = 0;
  12380. _this2.duration = 0;
  12381. _this2.gap = false;
  12382. _this2.independent = false;
  12383. _this2.relurl = void 0;
  12384. _this2.fragment = void 0;
  12385. _this2.index = void 0;
  12386. _this2.stats = new _load_stats__WEBPACK_IMPORTED_MODULE_4__.LoadStats();
  12387. _this2.duration = partAttrs.decimalFloatingPoint('DURATION');
  12388. _this2.gap = partAttrs.bool('GAP');
  12389. _this2.independent = partAttrs.bool('INDEPENDENT');
  12390. _this2.relurl = partAttrs.enumeratedString('URI');
  12391. _this2.fragment = frag;
  12392. _this2.index = index;
  12393. var byteRange = partAttrs.enumeratedString('BYTERANGE');
  12394. if (byteRange) {
  12395. _this2.setByteRange(byteRange, previous);
  12396. }
  12397. if (previous) {
  12398. _this2.fragOffset = previous.fragOffset + previous.duration;
  12399. }
  12400. return _this2;
  12401. }
  12402. _createClass(Part, [{
  12403. key: "start",
  12404. get: function get() {
  12405. return this.fragment.start + this.fragOffset;
  12406. }
  12407. }, {
  12408. key: "end",
  12409. get: function get() {
  12410. return this.start + this.duration;
  12411. }
  12412. }, {
  12413. key: "loaded",
  12414. get: function get() {
  12415. var elementaryStreams = this.elementaryStreams;
  12416. return !!(elementaryStreams.audio || elementaryStreams.video || elementaryStreams.audiovideo);
  12417. }
  12418. }]);
  12419. return Part;
  12420. }(BaseSegment);
  12421. /***/ }),
  12422. /***/ "./src/loader/key-loader.ts":
  12423. /*!**********************************!*\
  12424. !*** ./src/loader/key-loader.ts ***!
  12425. \**********************************/
  12426. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  12427. "use strict";
  12428. __webpack_require__.r(__webpack_exports__);
  12429. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  12430. /* harmony export */ "default": () => (/* binding */ KeyLoader)
  12431. /* harmony export */ });
  12432. /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
  12433. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
  12434. /* harmony import */ var _fragment_loader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./fragment-loader */ "./src/loader/fragment-loader.ts");
  12435. /*
  12436. * Decrypt key Loader
  12437. */
  12438. var KeyLoader = /*#__PURE__*/function () {
  12439. function KeyLoader(config) {
  12440. this.config = void 0;
  12441. this.loader = null;
  12442. this.decryptkey = null;
  12443. this.decrypturl = null;
  12444. this.config = config;
  12445. }
  12446. var _proto = KeyLoader.prototype;
  12447. _proto.abort = function abort() {
  12448. var _this$loader;
  12449. (_this$loader = this.loader) === null || _this$loader === void 0 ? void 0 : _this$loader.abort();
  12450. };
  12451. _proto.destroy = function destroy() {
  12452. if (this.loader) {
  12453. this.loader.destroy();
  12454. this.loader = null;
  12455. }
  12456. };
  12457. _proto.load = function load(frag) {
  12458. var _this = this;
  12459. var type = frag.type;
  12460. var loader = this.loader;
  12461. if (!frag.decryptdata) {
  12462. throw new Error('Missing decryption data on fragment in onKeyLoading');
  12463. }
  12464. // Load the key if the uri is different from previous one, or if the decrypt key has not yet been retrieved
  12465. var uri = frag.decryptdata.uri;
  12466. if (uri !== this.decrypturl || this.decryptkey === null) {
  12467. var config = this.config;
  12468. if (loader) {
  12469. _utils_logger__WEBPACK_IMPORTED_MODULE_1__.logger.warn("abort previous key loader for type:" + type);
  12470. loader.abort();
  12471. }
  12472. if (!uri) {
  12473. throw new Error('key uri is falsy');
  12474. }
  12475. var _Loader = config.loader;
  12476. var keyLoader = frag.keyLoader = this.loader = new _Loader(config);
  12477. this.decrypturl = uri;
  12478. this.decryptkey = null;
  12479. return new Promise(function (resolve, reject) {
  12480. var loaderContext = {
  12481. url: uri,
  12482. frag: frag,
  12483. part: null,
  12484. responseType: 'arraybuffer'
  12485. };
  12486. // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,
  12487. // key-loader will trigger an error and rely on stream-controller to handle retry logic.
  12488. // this will also align retry logic with fragment-loader
  12489. var loaderConfig = {
  12490. timeout: config.fragLoadingTimeOut,
  12491. maxRetry: 0,
  12492. retryDelay: config.fragLoadingRetryDelay,
  12493. maxRetryDelay: config.fragLoadingMaxRetryTimeout,
  12494. highWaterMark: 0
  12495. };
  12496. var loaderCallbacks = {
  12497. onSuccess: function onSuccess(response, stats, context, networkDetails) {
  12498. var frag = context.frag;
  12499. if (!frag.decryptdata) {
  12500. _utils_logger__WEBPACK_IMPORTED_MODULE_1__.logger.error('after key load, decryptdata unset');
  12501. return reject(new _fragment_loader__WEBPACK_IMPORTED_MODULE_2__.LoadError({
  12502. type: _errors__WEBPACK_IMPORTED_MODULE_0__.ErrorTypes.NETWORK_ERROR,
  12503. details: _errors__WEBPACK_IMPORTED_MODULE_0__.ErrorDetails.KEY_LOAD_ERROR,
  12504. fatal: false,
  12505. frag: frag,
  12506. networkDetails: networkDetails
  12507. }));
  12508. }
  12509. _this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data);
  12510. // detach fragment key loader on load success
  12511. frag.keyLoader = null;
  12512. _this.loader = null;
  12513. resolve({
  12514. frag: frag
  12515. });
  12516. },
  12517. onError: function onError(error, context, networkDetails) {
  12518. _this.resetLoader(context.frag, keyLoader);
  12519. reject(new _fragment_loader__WEBPACK_IMPORTED_MODULE_2__.LoadError({
  12520. type: _errors__WEBPACK_IMPORTED_MODULE_0__.ErrorTypes.NETWORK_ERROR,
  12521. details: _errors__WEBPACK_IMPORTED_MODULE_0__.ErrorDetails.KEY_LOAD_ERROR,
  12522. fatal: false,
  12523. frag: frag,
  12524. networkDetails: networkDetails
  12525. }));
  12526. },
  12527. onTimeout: function onTimeout(stats, context, networkDetails) {
  12528. _this.resetLoader(context.frag, keyLoader);
  12529. reject(new _fragment_loader__WEBPACK_IMPORTED_MODULE_2__.LoadError({
  12530. type: _errors__WEBPACK_IMPORTED_MODULE_0__.ErrorTypes.NETWORK_ERROR,
  12531. details: _errors__WEBPACK_IMPORTED_MODULE_0__.ErrorDetails.KEY_LOAD_TIMEOUT,
  12532. fatal: false,
  12533. frag: frag,
  12534. networkDetails: networkDetails
  12535. }));
  12536. },
  12537. onAbort: function onAbort(stats, context, networkDetails) {
  12538. _this.resetLoader(context.frag, keyLoader);
  12539. reject(new _fragment_loader__WEBPACK_IMPORTED_MODULE_2__.LoadError({
  12540. type: _errors__WEBPACK_IMPORTED_MODULE_0__.ErrorTypes.NETWORK_ERROR,
  12541. details: _errors__WEBPACK_IMPORTED_MODULE_0__.ErrorDetails.INTERNAL_ABORTED,
  12542. fatal: false,
  12543. frag: frag,
  12544. networkDetails: networkDetails
  12545. }));
  12546. }
  12547. };
  12548. keyLoader.load(loaderContext, loaderConfig, loaderCallbacks);
  12549. });
  12550. } else if (this.decryptkey) {
  12551. // Return the key if it's already been loaded
  12552. frag.decryptdata.key = this.decryptkey;
  12553. return Promise.resolve({
  12554. frag: frag
  12555. });
  12556. }
  12557. return Promise.resolve();
  12558. };
  12559. _proto.resetLoader = function resetLoader(frag, loader) {
  12560. if (this.loader === loader) {
  12561. this.loader = null;
  12562. }
  12563. loader.destroy();
  12564. };
  12565. return KeyLoader;
  12566. }();
  12567. /***/ }),
  12568. /***/ "./src/loader/level-details.ts":
  12569. /*!*************************************!*\
  12570. !*** ./src/loader/level-details.ts ***!
  12571. \*************************************/
  12572. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  12573. "use strict";
  12574. __webpack_require__.r(__webpack_exports__);
  12575. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  12576. /* harmony export */ "LevelDetails": () => (/* binding */ LevelDetails)
  12577. /* harmony export */ });
  12578. /* harmony import */ var _Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
  12579. 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, _toPropertyKey(descriptor.key), descriptor); } }
  12580. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  12581. function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
  12582. function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
  12583. var DEFAULT_TARGET_DURATION = 10;
  12584. var LevelDetails = /*#__PURE__*/function () {
  12585. // Manifest reload synchronization
  12586. function LevelDetails(baseUrl) {
  12587. this.PTSKnown = false;
  12588. this.alignedSliding = false;
  12589. this.averagetargetduration = void 0;
  12590. this.endCC = 0;
  12591. this.endSN = 0;
  12592. this.fragments = void 0;
  12593. this.fragmentHint = void 0;
  12594. this.partList = null;
  12595. this.dateRanges = void 0;
  12596. this.live = true;
  12597. this.ageHeader = 0;
  12598. this.advancedDateTime = void 0;
  12599. this.updated = true;
  12600. this.advanced = true;
  12601. this.availabilityDelay = void 0;
  12602. this.misses = 0;
  12603. this.needSidxRanges = false;
  12604. this.startCC = 0;
  12605. this.startSN = 0;
  12606. this.startTimeOffset = null;
  12607. this.targetduration = 0;
  12608. this.totalduration = 0;
  12609. this.type = null;
  12610. this.url = void 0;
  12611. this.m3u8 = '';
  12612. this.version = null;
  12613. this.canBlockReload = false;
  12614. this.canSkipUntil = 0;
  12615. this.canSkipDateRanges = false;
  12616. this.skippedSegments = 0;
  12617. this.recentlyRemovedDateranges = void 0;
  12618. this.partHoldBack = 0;
  12619. this.holdBack = 0;
  12620. this.partTarget = 0;
  12621. this.preloadHint = void 0;
  12622. this.renditionReports = void 0;
  12623. this.tuneInGoal = 0;
  12624. this.deltaUpdateFailed = void 0;
  12625. this.driftStartTime = 0;
  12626. this.driftEndTime = 0;
  12627. this.driftStart = 0;
  12628. this.driftEnd = 0;
  12629. this.fragments = [];
  12630. this.dateRanges = {};
  12631. this.url = baseUrl;
  12632. }
  12633. var _proto = LevelDetails.prototype;
  12634. _proto.reloaded = function reloaded(previous) {
  12635. if (!previous) {
  12636. this.advanced = true;
  12637. this.updated = true;
  12638. return;
  12639. }
  12640. var partSnDiff = this.lastPartSn - previous.lastPartSn;
  12641. var partIndexDiff = this.lastPartIndex - previous.lastPartIndex;
  12642. this.updated = this.endSN !== previous.endSN || !!partIndexDiff || !!partSnDiff;
  12643. this.advanced = this.endSN > previous.endSN || partSnDiff > 0 || partSnDiff === 0 && partIndexDiff > 0;
  12644. if (this.updated || this.advanced) {
  12645. this.misses = Math.floor(previous.misses * 0.6);
  12646. } else {
  12647. this.misses = previous.misses + 1;
  12648. }
  12649. this.availabilityDelay = previous.availabilityDelay;
  12650. };
  12651. _createClass(LevelDetails, [{
  12652. key: "hasProgramDateTime",
  12653. get: function get() {
  12654. if (this.fragments.length) {
  12655. return (0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(this.fragments[this.fragments.length - 1].programDateTime);
  12656. }
  12657. return false;
  12658. }
  12659. }, {
  12660. key: "levelTargetDuration",
  12661. get: function get() {
  12662. return this.averagetargetduration || this.targetduration || DEFAULT_TARGET_DURATION;
  12663. }
  12664. }, {
  12665. key: "drift",
  12666. get: function get() {
  12667. var runTime = this.driftEndTime - this.driftStartTime;
  12668. if (runTime > 0) {
  12669. var runDuration = this.driftEnd - this.driftStart;
  12670. return runDuration * 1000 / runTime;
  12671. }
  12672. return 1;
  12673. }
  12674. }, {
  12675. key: "edge",
  12676. get: function get() {
  12677. return this.partEnd || this.fragmentEnd;
  12678. }
  12679. }, {
  12680. key: "partEnd",
  12681. get: function get() {
  12682. var _this$partList;
  12683. if ((_this$partList = this.partList) !== null && _this$partList !== void 0 && _this$partList.length) {
  12684. return this.partList[this.partList.length - 1].end;
  12685. }
  12686. return this.fragmentEnd;
  12687. }
  12688. }, {
  12689. key: "fragmentEnd",
  12690. get: function get() {
  12691. var _this$fragments;
  12692. if ((_this$fragments = this.fragments) !== null && _this$fragments !== void 0 && _this$fragments.length) {
  12693. return this.fragments[this.fragments.length - 1].end;
  12694. }
  12695. return 0;
  12696. }
  12697. }, {
  12698. key: "age",
  12699. get: function get() {
  12700. if (this.advancedDateTime) {
  12701. return Math.max(Date.now() - this.advancedDateTime, 0) / 1000;
  12702. }
  12703. return 0;
  12704. }
  12705. }, {
  12706. key: "lastPartIndex",
  12707. get: function get() {
  12708. var _this$partList2;
  12709. if ((_this$partList2 = this.partList) !== null && _this$partList2 !== void 0 && _this$partList2.length) {
  12710. return this.partList[this.partList.length - 1].index;
  12711. }
  12712. return -1;
  12713. }
  12714. }, {
  12715. key: "lastPartSn",
  12716. get: function get() {
  12717. var _this$partList3;
  12718. if ((_this$partList3 = this.partList) !== null && _this$partList3 !== void 0 && _this$partList3.length) {
  12719. return this.partList[this.partList.length - 1].fragment.sn;
  12720. }
  12721. return this.endSN;
  12722. }
  12723. }]);
  12724. return LevelDetails;
  12725. }();
  12726. /***/ }),
  12727. /***/ "./src/loader/level-key.ts":
  12728. /*!*********************************!*\
  12729. !*** ./src/loader/level-key.ts ***!
  12730. \*********************************/
  12731. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  12732. "use strict";
  12733. __webpack_require__.r(__webpack_exports__);
  12734. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  12735. /* harmony export */ "LevelKey": () => (/* binding */ LevelKey)
  12736. /* harmony export */ });
  12737. /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! url-toolkit */ "./node_modules/.pnpm/url-toolkit@2.2.5/node_modules/url-toolkit/src/url-toolkit.js");
  12738. /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_0__);
  12739. 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, _toPropertyKey(descriptor.key), descriptor); } }
  12740. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  12741. function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
  12742. function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
  12743. var LevelKey = /*#__PURE__*/function () {
  12744. LevelKey.fromURL = function fromURL(baseUrl, relativeUrl) {
  12745. return new LevelKey(baseUrl, relativeUrl);
  12746. };
  12747. LevelKey.fromURI = function fromURI(uri) {
  12748. return new LevelKey(uri);
  12749. };
  12750. function LevelKey(absoluteOrBaseURI, relativeURL) {
  12751. this._uri = null;
  12752. this.method = null;
  12753. this.keyFormat = null;
  12754. this.keyFormatVersions = null;
  12755. this.keyID = null;
  12756. this.key = null;
  12757. this.iv = null;
  12758. if (relativeURL) {
  12759. this._uri = (0,url_toolkit__WEBPACK_IMPORTED_MODULE_0__.buildAbsoluteURL)(absoluteOrBaseURI, relativeURL, {
  12760. alwaysNormalize: true
  12761. });
  12762. } else {
  12763. this._uri = absoluteOrBaseURI;
  12764. }
  12765. }
  12766. _createClass(LevelKey, [{
  12767. key: "uri",
  12768. get: function get() {
  12769. return this._uri;
  12770. }
  12771. }]);
  12772. return LevelKey;
  12773. }();
  12774. /***/ }),
  12775. /***/ "./src/loader/load-stats.ts":
  12776. /*!**********************************!*\
  12777. !*** ./src/loader/load-stats.ts ***!
  12778. \**********************************/
  12779. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  12780. "use strict";
  12781. __webpack_require__.r(__webpack_exports__);
  12782. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  12783. /* harmony export */ "LoadStats": () => (/* binding */ LoadStats)
  12784. /* harmony export */ });
  12785. var LoadStats = function LoadStats() {
  12786. this.aborted = false;
  12787. this.loaded = 0;
  12788. this.retry = 0;
  12789. this.total = 0;
  12790. this.chunkCount = 0;
  12791. this.bwEstimate = 0;
  12792. this.loading = {
  12793. start: 0,
  12794. first: 0,
  12795. end: 0
  12796. };
  12797. this.parsing = {
  12798. start: 0,
  12799. end: 0
  12800. };
  12801. this.buffering = {
  12802. start: 0,
  12803. first: 0,
  12804. end: 0
  12805. };
  12806. };
  12807. /***/ }),
  12808. /***/ "./src/loader/m3u8-parser.ts":
  12809. /*!***********************************!*\
  12810. !*** ./src/loader/m3u8-parser.ts ***!
  12811. \***********************************/
  12812. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  12813. "use strict";
  12814. __webpack_require__.r(__webpack_exports__);
  12815. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  12816. /* harmony export */ "default": () => (/* binding */ M3U8Parser)
  12817. /* harmony export */ });
  12818. /* harmony import */ var _Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
  12819. /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! url-toolkit */ "./node_modules/.pnpm/url-toolkit@2.2.5/node_modules/url-toolkit/src/url-toolkit.js");
  12820. /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_1__);
  12821. /* harmony import */ var _date_range__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./date-range */ "./src/loader/date-range.ts");
  12822. /* harmony import */ var _fragment__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./fragment */ "./src/loader/fragment.ts");
  12823. /* harmony import */ var _level_details__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./level-details */ "./src/loader/level-details.ts");
  12824. /* harmony import */ var _level_key__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./level-key */ "./src/loader/level-key.ts");
  12825. /* harmony import */ var _utils_attr_list__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/attr-list */ "./src/utils/attr-list.ts");
  12826. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
  12827. /* harmony import */ var _utils_codecs__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/codecs */ "./src/utils/codecs.ts");
  12828. // https://regex101.com is your friend
  12829. var MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-SESSION-DATA:([^\r\n]*)[\r\n]+/g;
  12830. var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
  12831. var LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,
  12832. // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
  12833. /(?!#) *(\S[\S ]*)/.source,
  12834. // segment URI, group 3 => the URI (note newline is not eaten)
  12835. /#EXT-X-BYTERANGE:*(.+)/.source,
  12836. // next segment's byterange, group 4 => range spec (x@y)
  12837. /#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,
  12838. // next segment's program date/time group 5 => the datetime spec
  12839. /#.*/.source // All other non-segment oriented tags will match with all groups empty
  12840. ].join('|'), 'g');
  12841. var LEVEL_PLAYLIST_REGEX_SLOW = new RegExp([/#(EXTM3U)/.source, /#EXT-X-(DATERANGE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source, /#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source, /#EXT-X-(DISCONTINUITY|ENDLIST|GAP)/.source, /(#)([^:]*):(.*)/.source, /(#)(.*)(?:.*)\r?\n?/.source].join('|'));
  12842. var MP4_REGEX_SUFFIX = /\.(mp4|m4s|m4v|m4a)$/i;
  12843. function isMP4Url(url) {
  12844. var _URLToolkit$parseURL$, _URLToolkit$parseURL;
  12845. return MP4_REGEX_SUFFIX.test((_URLToolkit$parseURL$ = (_URLToolkit$parseURL = url_toolkit__WEBPACK_IMPORTED_MODULE_1__.parseURL(url)) === null || _URLToolkit$parseURL === void 0 ? void 0 : _URLToolkit$parseURL.path) != null ? _URLToolkit$parseURL$ : '');
  12846. }
  12847. var M3U8Parser = /*#__PURE__*/function () {
  12848. function M3U8Parser() {}
  12849. M3U8Parser.findGroup = function findGroup(groups, mediaGroupId) {
  12850. for (var i = 0; i < groups.length; i++) {
  12851. var group = groups[i];
  12852. if (group.id === mediaGroupId) {
  12853. return group;
  12854. }
  12855. }
  12856. };
  12857. M3U8Parser.convertAVC1ToAVCOTI = function convertAVC1ToAVCOTI(codec) {
  12858. // Convert avc1 codec string from RFC-4281 to RFC-6381 for MediaSource.isTypeSupported
  12859. var avcdata = codec.split('.');
  12860. if (avcdata.length > 2) {
  12861. var result = avcdata.shift() + '.';
  12862. result += parseInt(avcdata.shift()).toString(16);
  12863. result += ('000' + parseInt(avcdata.shift()).toString(16)).slice(-4);
  12864. return result;
  12865. }
  12866. return codec;
  12867. };
  12868. M3U8Parser.resolve = function resolve(url, baseUrl) {
  12869. return url_toolkit__WEBPACK_IMPORTED_MODULE_1__.buildAbsoluteURL(baseUrl, url, {
  12870. alwaysNormalize: true
  12871. });
  12872. };
  12873. M3U8Parser.parseMasterPlaylist = function parseMasterPlaylist(string, baseurl) {
  12874. var levels = [];
  12875. var levelsWithKnownCodecs = [];
  12876. var sessionData = {};
  12877. var hasSessionData = false;
  12878. MASTER_PLAYLIST_REGEX.lastIndex = 0;
  12879. var result;
  12880. while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
  12881. if (result[1]) {
  12882. var _level$unknownCodecs;
  12883. // '#EXT-X-STREAM-INF' is found, parse level tag in group 1
  12884. var attrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_6__.AttrList(result[1]);
  12885. var level = {
  12886. attrs: attrs,
  12887. bitrate: attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH'),
  12888. name: attrs.NAME,
  12889. url: M3U8Parser.resolve(result[2], baseurl)
  12890. };
  12891. var resolution = attrs.decimalResolution('RESOLUTION');
  12892. if (resolution) {
  12893. level.width = resolution.width;
  12894. level.height = resolution.height;
  12895. }
  12896. setCodecs((attrs.CODECS || '').split(/[ ,]+/).filter(function (c) {
  12897. return c;
  12898. }), level);
  12899. if (level.videoCodec && level.videoCodec.indexOf('avc1') !== -1) {
  12900. level.videoCodec = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);
  12901. }
  12902. if (!((_level$unknownCodecs = level.unknownCodecs) !== null && _level$unknownCodecs !== void 0 && _level$unknownCodecs.length)) {
  12903. levelsWithKnownCodecs.push(level);
  12904. }
  12905. levels.push(level);
  12906. } else if (result[3]) {
  12907. // '#EXT-X-SESSION-DATA' is found, parse session data in group 3
  12908. var sessionAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_6__.AttrList(result[3]);
  12909. if (sessionAttrs['DATA-ID']) {
  12910. hasSessionData = true;
  12911. sessionData[sessionAttrs['DATA-ID']] = sessionAttrs;
  12912. }
  12913. }
  12914. }
  12915. // Filter out levels with unknown codecs if it does not remove all levels
  12916. var stripUnknownCodecLevels = levelsWithKnownCodecs.length > 0 && levelsWithKnownCodecs.length < levels.length;
  12917. return {
  12918. levels: stripUnknownCodecLevels ? levelsWithKnownCodecs : levels,
  12919. sessionData: hasSessionData ? sessionData : null
  12920. };
  12921. };
  12922. M3U8Parser.parseMasterPlaylistMedia = function parseMasterPlaylistMedia(string, baseurl, type, groups) {
  12923. if (groups === void 0) {
  12924. groups = [];
  12925. }
  12926. var result;
  12927. var medias = [];
  12928. var id = 0;
  12929. MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
  12930. while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
  12931. var attrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_6__.AttrList(result[1]);
  12932. if (attrs.TYPE === type) {
  12933. var media = {
  12934. attrs: attrs,
  12935. bitrate: 0,
  12936. id: id++,
  12937. groupId: attrs['GROUP-ID'],
  12938. instreamId: attrs['INSTREAM-ID'],
  12939. name: attrs.NAME || attrs.LANGUAGE || '',
  12940. type: type,
  12941. default: attrs.bool('DEFAULT'),
  12942. autoselect: attrs.bool('AUTOSELECT'),
  12943. forced: attrs.bool('FORCED'),
  12944. lang: attrs.LANGUAGE,
  12945. url: attrs.URI ? M3U8Parser.resolve(attrs.URI, baseurl) : ''
  12946. };
  12947. if (groups.length) {
  12948. // If there are audio or text groups signalled in the manifest, let's look for a matching codec string for this track
  12949. // If we don't find the track signalled, lets use the first audio groups codec we have
  12950. // Acting as a best guess
  12951. var groupCodec = M3U8Parser.findGroup(groups, media.groupId) || groups[0];
  12952. assignCodec(media, groupCodec, 'audioCodec');
  12953. assignCodec(media, groupCodec, 'textCodec');
  12954. }
  12955. medias.push(media);
  12956. }
  12957. }
  12958. return medias;
  12959. };
  12960. M3U8Parser.parseLevelPlaylist = function parseLevelPlaylist(string, baseurl, id, type, levelUrlId) {
  12961. var level = new _level_details__WEBPACK_IMPORTED_MODULE_4__.LevelDetails(baseurl);
  12962. var fragments = level.fragments;
  12963. // The most recent init segment seen (applies to all subsequent segments)
  12964. var currentInitSegment = null;
  12965. var currentSN = 0;
  12966. var currentPart = 0;
  12967. var totalduration = 0;
  12968. var discontinuityCounter = 0;
  12969. var prevFrag = null;
  12970. var frag = new _fragment__WEBPACK_IMPORTED_MODULE_3__.Fragment(type, baseurl);
  12971. var result;
  12972. var i;
  12973. var levelkey;
  12974. var firstPdtIndex = -1;
  12975. var createNextFrag = false;
  12976. LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
  12977. level.m3u8 = string;
  12978. while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
  12979. if (createNextFrag) {
  12980. createNextFrag = false;
  12981. frag = new _fragment__WEBPACK_IMPORTED_MODULE_3__.Fragment(type, baseurl);
  12982. // setup the next fragment for part loading
  12983. frag.start = totalduration;
  12984. frag.sn = currentSN;
  12985. frag.cc = discontinuityCounter;
  12986. frag.level = id;
  12987. if (currentInitSegment) {
  12988. frag.initSegment = currentInitSegment;
  12989. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  12990. currentInitSegment.rawProgramDateTime = null;
  12991. }
  12992. }
  12993. var duration = result[1];
  12994. if (duration) {
  12995. // INF
  12996. frag.duration = parseFloat(duration);
  12997. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  12998. var title = (' ' + result[2]).slice(1);
  12999. frag.title = title || null;
  13000. frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);
  13001. } else if (result[3]) {
  13002. // url
  13003. if ((0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(frag.duration)) {
  13004. frag.start = totalduration;
  13005. if (levelkey) {
  13006. frag.levelkey = levelkey;
  13007. }
  13008. frag.sn = currentSN;
  13009. frag.level = id;
  13010. frag.cc = discontinuityCounter;
  13011. frag.urlId = levelUrlId;
  13012. fragments.push(frag);
  13013. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  13014. frag.relurl = (' ' + result[3]).slice(1);
  13015. assignProgramDateTime(frag, prevFrag);
  13016. prevFrag = frag;
  13017. totalduration += frag.duration;
  13018. currentSN++;
  13019. currentPart = 0;
  13020. createNextFrag = true;
  13021. }
  13022. } else if (result[4]) {
  13023. // X-BYTERANGE
  13024. var data = (' ' + result[4]).slice(1);
  13025. if (prevFrag) {
  13026. frag.setByteRange(data, prevFrag);
  13027. } else {
  13028. frag.setByteRange(data);
  13029. }
  13030. } else if (result[5]) {
  13031. // PROGRAM-DATE-TIME
  13032. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  13033. frag.rawProgramDateTime = (' ' + result[5]).slice(1);
  13034. frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);
  13035. if (firstPdtIndex === -1) {
  13036. firstPdtIndex = fragments.length;
  13037. }
  13038. } else {
  13039. result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
  13040. if (!result) {
  13041. _utils_logger__WEBPACK_IMPORTED_MODULE_7__.logger.warn('No matches on slow regex match for level playlist!');
  13042. continue;
  13043. }
  13044. for (i = 1; i < result.length; i++) {
  13045. if (typeof result[i] !== 'undefined') {
  13046. break;
  13047. }
  13048. }
  13049. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  13050. var tag = (' ' + result[i]).slice(1);
  13051. var value1 = (' ' + result[i + 1]).slice(1);
  13052. var value2 = result[i + 2] ? (' ' + result[i + 2]).slice(1) : '';
  13053. switch (tag) {
  13054. case 'PLAYLIST-TYPE':
  13055. level.type = value1.toUpperCase();
  13056. break;
  13057. case 'MEDIA-SEQUENCE':
  13058. currentSN = level.startSN = parseInt(value1);
  13059. break;
  13060. case 'SKIP':
  13061. {
  13062. var skipAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_6__.AttrList(value1);
  13063. var skippedSegments = skipAttrs.decimalInteger('SKIPPED-SEGMENTS');
  13064. if ((0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(skippedSegments)) {
  13065. level.skippedSegments = skippedSegments;
  13066. // This will result in fragments[] containing undefined values, which we will fill in with `mergeDetails`
  13067. for (var _i = skippedSegments; _i--;) {
  13068. fragments.unshift(null);
  13069. }
  13070. currentSN += skippedSegments;
  13071. }
  13072. var recentlyRemovedDateranges = skipAttrs.enumeratedString('RECENTLY-REMOVED-DATERANGES');
  13073. if (recentlyRemovedDateranges) {
  13074. level.recentlyRemovedDateranges = recentlyRemovedDateranges.split('\t');
  13075. }
  13076. break;
  13077. }
  13078. case 'TARGETDURATION':
  13079. level.targetduration = parseFloat(value1);
  13080. break;
  13081. case 'VERSION':
  13082. level.version = parseInt(value1);
  13083. break;
  13084. case 'EXTM3U':
  13085. break;
  13086. case 'ENDLIST':
  13087. level.live = false;
  13088. break;
  13089. case '#':
  13090. if (value1 || value2) {
  13091. frag.tagList.push(value2 ? [value1, value2] : [value1]);
  13092. }
  13093. break;
  13094. case 'DISCONTINUITY':
  13095. discontinuityCounter++;
  13096. frag.tagList.push(['DIS']);
  13097. break;
  13098. case 'GAP':
  13099. frag.tagList.push([tag]);
  13100. break;
  13101. case 'BITRATE':
  13102. frag.tagList.push([tag, value1]);
  13103. break;
  13104. case 'DATERANGE':
  13105. {
  13106. var dateRangeAttr = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_6__.AttrList(value1);
  13107. var dateRange = new _date_range__WEBPACK_IMPORTED_MODULE_2__.DateRange(dateRangeAttr, level.dateRanges[dateRangeAttr.ID]);
  13108. if (dateRange.isValid || level.skippedSegments) {
  13109. level.dateRanges[dateRange.id] = dateRange;
  13110. } else {
  13111. _utils_logger__WEBPACK_IMPORTED_MODULE_7__.logger.warn("Ignoring invalid DATERANGE tag: \"" + value1 + "\"");
  13112. }
  13113. // Add to fragment tag list for backwards compatibility (< v1.2.0)
  13114. frag.tagList.push(['EXT-X-DATERANGE', value1]);
  13115. break;
  13116. }
  13117. case 'DISCONTINUITY-SEQUENCE':
  13118. discontinuityCounter = parseInt(value1);
  13119. break;
  13120. case 'KEY':
  13121. {
  13122. var _keyAttrs$enumeratedS;
  13123. // https://tools.ietf.org/html/rfc8216#section-4.3.2.4
  13124. var keyAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_6__.AttrList(value1);
  13125. var decryptmethod = keyAttrs.enumeratedString('METHOD');
  13126. var decrypturi = keyAttrs.URI;
  13127. var decryptiv = keyAttrs.hexadecimalInteger('IV');
  13128. var decryptkeyformatversions = keyAttrs.enumeratedString('KEYFORMATVERSIONS');
  13129. var decryptkeyid = keyAttrs.enumeratedString('KEYID');
  13130. // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of "identity".
  13131. var decryptkeyformat = (_keyAttrs$enumeratedS = keyAttrs.enumeratedString('KEYFORMAT')) != null ? _keyAttrs$enumeratedS : 'identity';
  13132. var unsupportedKnownKeyformatsInManifest = ['com.apple.streamingkeydelivery', 'com.microsoft.playready', 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed',
  13133. // widevine (v2)
  13134. 'com.widevine' // earlier widevine (v1)
  13135. ];
  13136. if (unsupportedKnownKeyformatsInManifest.indexOf(decryptkeyformat) > -1) {
  13137. _utils_logger__WEBPACK_IMPORTED_MODULE_7__.logger.warn("Keyformat " + decryptkeyformat + " is not supported from the manifest");
  13138. continue;
  13139. } else if (decryptkeyformat !== 'identity') {
  13140. // We are supposed to skip keys we don't understand.
  13141. // As we currently only officially support identity keys
  13142. // from the manifest we shouldn't save any other key.
  13143. continue;
  13144. }
  13145. // TODO: multiple keys can be defined on a fragment, and we need to support this
  13146. // for clients that support both playready and widevine
  13147. if (decryptmethod) {
  13148. // TODO: need to determine if the level key is actually a relative URL
  13149. // if it isn't, then we should instead construct the LevelKey using fromURI.
  13150. levelkey = _level_key__WEBPACK_IMPORTED_MODULE_5__.LevelKey.fromURL(baseurl, decrypturi);
  13151. if (decrypturi && ['AES-128', 'SAMPLE-AES', 'SAMPLE-AES-CENC'].indexOf(decryptmethod) >= 0) {
  13152. levelkey.method = decryptmethod;
  13153. levelkey.keyFormat = decryptkeyformat;
  13154. if (decryptkeyid) {
  13155. levelkey.keyID = decryptkeyid;
  13156. }
  13157. if (decryptkeyformatversions) {
  13158. levelkey.keyFormatVersions = decryptkeyformatversions;
  13159. }
  13160. // Initialization Vector (IV)
  13161. levelkey.iv = decryptiv;
  13162. }
  13163. }
  13164. break;
  13165. }
  13166. case 'START':
  13167. {
  13168. var startAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_6__.AttrList(value1);
  13169. var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');
  13170. // TIME-OFFSET can be 0
  13171. if ((0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(startTimeOffset)) {
  13172. level.startTimeOffset = startTimeOffset;
  13173. }
  13174. break;
  13175. }
  13176. case 'MAP':
  13177. {
  13178. var mapAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_6__.AttrList(value1);
  13179. if (frag.duration) {
  13180. // Initial segment tag is after segment duration tag.
  13181. // #EXTINF: 6.0
  13182. // #EXT-X-MAP:URI="init.mp4
  13183. var init = new _fragment__WEBPACK_IMPORTED_MODULE_3__.Fragment(type, baseurl);
  13184. setInitSegment(init, mapAttrs, id, levelkey);
  13185. currentInitSegment = init;
  13186. frag.initSegment = currentInitSegment;
  13187. if (currentInitSegment.rawProgramDateTime && !frag.rawProgramDateTime) {
  13188. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  13189. }
  13190. } else {
  13191. // Initial segment tag is before segment duration tag
  13192. setInitSegment(frag, mapAttrs, id, levelkey);
  13193. currentInitSegment = frag;
  13194. createNextFrag = true;
  13195. }
  13196. break;
  13197. }
  13198. case 'SERVER-CONTROL':
  13199. {
  13200. var serverControlAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_6__.AttrList(value1);
  13201. level.canBlockReload = serverControlAttrs.bool('CAN-BLOCK-RELOAD');
  13202. level.canSkipUntil = serverControlAttrs.optionalFloat('CAN-SKIP-UNTIL', 0);
  13203. level.canSkipDateRanges = level.canSkipUntil > 0 && serverControlAttrs.bool('CAN-SKIP-DATERANGES');
  13204. level.partHoldBack = serverControlAttrs.optionalFloat('PART-HOLD-BACK', 0);
  13205. level.holdBack = serverControlAttrs.optionalFloat('HOLD-BACK', 0);
  13206. break;
  13207. }
  13208. case 'PART-INF':
  13209. {
  13210. var partInfAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_6__.AttrList(value1);
  13211. level.partTarget = partInfAttrs.decimalFloatingPoint('PART-TARGET');
  13212. break;
  13213. }
  13214. case 'PART':
  13215. {
  13216. var partList = level.partList;
  13217. if (!partList) {
  13218. partList = level.partList = [];
  13219. }
  13220. var previousFragmentPart = currentPart > 0 ? partList[partList.length - 1] : undefined;
  13221. var index = currentPart++;
  13222. var part = new _fragment__WEBPACK_IMPORTED_MODULE_3__.Part(new _utils_attr_list__WEBPACK_IMPORTED_MODULE_6__.AttrList(value1), frag, baseurl, index, previousFragmentPart);
  13223. partList.push(part);
  13224. frag.duration += part.duration;
  13225. break;
  13226. }
  13227. case 'PRELOAD-HINT':
  13228. {
  13229. var preloadHintAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_6__.AttrList(value1);
  13230. level.preloadHint = preloadHintAttrs;
  13231. break;
  13232. }
  13233. case 'RENDITION-REPORT':
  13234. {
  13235. var renditionReportAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_6__.AttrList(value1);
  13236. level.renditionReports = level.renditionReports || [];
  13237. level.renditionReports.push(renditionReportAttrs);
  13238. break;
  13239. }
  13240. default:
  13241. _utils_logger__WEBPACK_IMPORTED_MODULE_7__.logger.warn("line parsed but not handled: " + result);
  13242. break;
  13243. }
  13244. }
  13245. }
  13246. if (prevFrag && !prevFrag.relurl) {
  13247. fragments.pop();
  13248. totalduration -= prevFrag.duration;
  13249. if (level.partList) {
  13250. level.fragmentHint = prevFrag;
  13251. }
  13252. } else if (level.partList) {
  13253. assignProgramDateTime(frag, prevFrag);
  13254. frag.cc = discontinuityCounter;
  13255. level.fragmentHint = frag;
  13256. }
  13257. var fragmentLength = fragments.length;
  13258. var firstFragment = fragments[0];
  13259. var lastFragment = fragments[fragmentLength - 1];
  13260. totalduration += level.skippedSegments * level.targetduration;
  13261. if (totalduration > 0 && fragmentLength && lastFragment) {
  13262. level.averagetargetduration = totalduration / fragmentLength;
  13263. var lastSn = lastFragment.sn;
  13264. level.endSN = lastSn !== 'initSegment' ? lastSn : 0;
  13265. if (firstFragment) {
  13266. level.startCC = firstFragment.cc;
  13267. if (!firstFragment.initSegment) {
  13268. // this is a bit lurky but HLS really has no other way to tell us
  13269. // if the fragments are TS or MP4, except if we download them :/
  13270. // but this is to be able to handle SIDX.
  13271. if (level.fragments.every(function (frag) {
  13272. return frag.relurl && isMP4Url(frag.relurl);
  13273. })) {
  13274. _utils_logger__WEBPACK_IMPORTED_MODULE_7__.logger.warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX');
  13275. frag = new _fragment__WEBPACK_IMPORTED_MODULE_3__.Fragment(type, baseurl);
  13276. frag.relurl = lastFragment.relurl;
  13277. frag.level = id;
  13278. frag.sn = 'initSegment';
  13279. firstFragment.initSegment = frag;
  13280. level.needSidxRanges = true;
  13281. }
  13282. }
  13283. }
  13284. } else {
  13285. level.endSN = 0;
  13286. level.startCC = 0;
  13287. }
  13288. if (level.fragmentHint) {
  13289. totalduration += level.fragmentHint.duration;
  13290. }
  13291. level.totalduration = totalduration;
  13292. level.endCC = discontinuityCounter;
  13293. /**
  13294. * Backfill any missing PDT values
  13295. * "If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after
  13296. * one or more Media Segment URIs, the client SHOULD extrapolate
  13297. * backward from that tag (using EXTINF durations and/or media
  13298. * timestamps) to associate dates with those segments."
  13299. * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs
  13300. * computed.
  13301. */
  13302. if (firstPdtIndex > 0) {
  13303. backfillProgramDateTimes(fragments, firstPdtIndex);
  13304. }
  13305. return level;
  13306. };
  13307. return M3U8Parser;
  13308. }();
  13309. function setCodecs(codecs, level) {
  13310. ['video', 'audio', 'text'].forEach(function (type) {
  13311. var filtered = codecs.filter(function (codec) {
  13312. return (0,_utils_codecs__WEBPACK_IMPORTED_MODULE_8__.isCodecType)(codec, type);
  13313. });
  13314. if (filtered.length) {
  13315. var preferred = filtered.filter(function (codec) {
  13316. return codec.lastIndexOf('avc1', 0) === 0 || codec.lastIndexOf('mp4a', 0) === 0;
  13317. });
  13318. level[type + "Codec"] = preferred.length > 0 ? preferred[0] : filtered[0];
  13319. // remove from list
  13320. codecs = codecs.filter(function (codec) {
  13321. return filtered.indexOf(codec) === -1;
  13322. });
  13323. }
  13324. });
  13325. level.unknownCodecs = codecs;
  13326. }
  13327. function assignCodec(media, groupItem, codecProperty) {
  13328. var codecValue = groupItem[codecProperty];
  13329. if (codecValue) {
  13330. media[codecProperty] = codecValue;
  13331. }
  13332. }
  13333. function backfillProgramDateTimes(fragments, firstPdtIndex) {
  13334. var fragPrev = fragments[firstPdtIndex];
  13335. for (var i = firstPdtIndex; i--;) {
  13336. var frag = fragments[i];
  13337. // Exit on delta-playlist skipped segments
  13338. if (!frag) {
  13339. return;
  13340. }
  13341. frag.programDateTime = fragPrev.programDateTime - frag.duration * 1000;
  13342. fragPrev = frag;
  13343. }
  13344. }
  13345. function assignProgramDateTime(frag, prevFrag) {
  13346. if (frag.rawProgramDateTime) {
  13347. frag.programDateTime = Date.parse(frag.rawProgramDateTime);
  13348. } else if (prevFrag !== null && prevFrag !== void 0 && prevFrag.programDateTime) {
  13349. frag.programDateTime = prevFrag.endProgramDateTime;
  13350. }
  13351. if (!(0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(frag.programDateTime)) {
  13352. frag.programDateTime = null;
  13353. frag.rawProgramDateTime = null;
  13354. }
  13355. }
  13356. function setInitSegment(frag, mapAttrs, id, levelkey) {
  13357. frag.relurl = mapAttrs.URI;
  13358. if (mapAttrs.BYTERANGE) {
  13359. frag.setByteRange(mapAttrs.BYTERANGE);
  13360. }
  13361. frag.level = id;
  13362. frag.sn = 'initSegment';
  13363. if (levelkey) {
  13364. frag.levelkey = levelkey;
  13365. }
  13366. frag.initSegment = null;
  13367. }
  13368. /***/ }),
  13369. /***/ "./src/loader/playlist-loader.ts":
  13370. /*!***************************************!*\
  13371. !*** ./src/loader/playlist-loader.ts ***!
  13372. \***************************************/
  13373. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  13374. "use strict";
  13375. __webpack_require__.r(__webpack_exports__);
  13376. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  13377. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  13378. /* harmony export */ });
  13379. /* harmony import */ var _Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
  13380. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
  13381. /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
  13382. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
  13383. /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
  13384. /* harmony import */ var _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./m3u8-parser */ "./src/loader/m3u8-parser.ts");
  13385. /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
  13386. /* harmony import */ var _utils_attr_list__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/attr-list */ "./src/utils/attr-list.ts");
  13387. /**
  13388. * PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models.
  13389. *
  13390. * Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks.
  13391. *
  13392. * Uses loader(s) set in config to do actual internal loading of resource tasks.
  13393. *
  13394. * @module
  13395. *
  13396. */
  13397. function mapContextToLevelType(context) {
  13398. var type = context.type;
  13399. switch (type) {
  13400. case _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistContextType.AUDIO_TRACK:
  13401. return _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistLevelType.AUDIO;
  13402. case _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistContextType.SUBTITLE_TRACK:
  13403. return _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistLevelType.SUBTITLE;
  13404. default:
  13405. return _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistLevelType.MAIN;
  13406. }
  13407. }
  13408. function getResponseUrl(response, context) {
  13409. var url = response.url;
  13410. // responseURL not supported on some browsers (it is used to detect URL redirection)
  13411. // data-uri mode also not supported (but no need to detect redirection)
  13412. if (url === undefined || url.indexOf('data:') === 0) {
  13413. // fallback to initial URL
  13414. url = context.url;
  13415. }
  13416. return url;
  13417. }
  13418. var PlaylistLoader = /*#__PURE__*/function () {
  13419. function PlaylistLoader(hls) {
  13420. this.hls = void 0;
  13421. this.loaders = Object.create(null);
  13422. this.hls = hls;
  13423. this.registerListeners();
  13424. }
  13425. var _proto = PlaylistLoader.prototype;
  13426. _proto.startLoad = function startLoad(startPosition) {};
  13427. _proto.stopLoad = function stopLoad() {
  13428. this.destroyInternalLoaders();
  13429. };
  13430. _proto.registerListeners = function registerListeners() {
  13431. var hls = this.hls;
  13432. hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.MANIFEST_LOADING, this.onManifestLoading, this);
  13433. hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.LEVEL_LOADING, this.onLevelLoading, this);
  13434. hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  13435. hls.on(_events__WEBPACK_IMPORTED_MODULE_1__.Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  13436. };
  13437. _proto.unregisterListeners = function unregisterListeners() {
  13438. var hls = this.hls;
  13439. hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.MANIFEST_LOADING, this.onManifestLoading, this);
  13440. hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.LEVEL_LOADING, this.onLevelLoading, this);
  13441. hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  13442. hls.off(_events__WEBPACK_IMPORTED_MODULE_1__.Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  13443. }
  13444. /**
  13445. * Returns defaults or configured loader-type overloads (pLoader and loader config params)
  13446. */;
  13447. _proto.createInternalLoader = function createInternalLoader(context) {
  13448. var config = this.hls.config;
  13449. var PLoader = config.pLoader;
  13450. var Loader = config.loader;
  13451. var InternalLoader = PLoader || Loader;
  13452. var loader = new InternalLoader(config);
  13453. context.loader = loader;
  13454. this.loaders[context.type] = loader;
  13455. return loader;
  13456. };
  13457. _proto.getInternalLoader = function getInternalLoader(context) {
  13458. return this.loaders[context.type];
  13459. };
  13460. _proto.resetInternalLoader = function resetInternalLoader(contextType) {
  13461. if (this.loaders[contextType]) {
  13462. delete this.loaders[contextType];
  13463. }
  13464. }
  13465. /**
  13466. * Call `destroy` on all internal loader instances mapped (one per context type)
  13467. */;
  13468. _proto.destroyInternalLoaders = function destroyInternalLoaders() {
  13469. for (var contextType in this.loaders) {
  13470. var loader = this.loaders[contextType];
  13471. if (loader) {
  13472. loader.destroy();
  13473. }
  13474. this.resetInternalLoader(contextType);
  13475. }
  13476. };
  13477. _proto.destroy = function destroy() {
  13478. this.unregisterListeners();
  13479. this.destroyInternalLoaders();
  13480. };
  13481. _proto.onManifestLoading = function onManifestLoading(event, data) {
  13482. var url = data.url;
  13483. this.load({
  13484. id: null,
  13485. groupId: null,
  13486. level: 0,
  13487. responseType: 'text',
  13488. type: _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistContextType.MANIFEST,
  13489. url: url,
  13490. deliveryDirectives: null
  13491. });
  13492. };
  13493. _proto.onLevelLoading = function onLevelLoading(event, data) {
  13494. var id = data.id,
  13495. level = data.level,
  13496. url = data.url,
  13497. deliveryDirectives = data.deliveryDirectives;
  13498. this.load({
  13499. id: id,
  13500. groupId: null,
  13501. level: level,
  13502. responseType: 'text',
  13503. type: _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistContextType.LEVEL,
  13504. url: url,
  13505. deliveryDirectives: deliveryDirectives
  13506. });
  13507. };
  13508. _proto.onAudioTrackLoading = function onAudioTrackLoading(event, data) {
  13509. var id = data.id,
  13510. groupId = data.groupId,
  13511. url = data.url,
  13512. deliveryDirectives = data.deliveryDirectives;
  13513. this.load({
  13514. id: id,
  13515. groupId: groupId,
  13516. level: null,
  13517. responseType: 'text',
  13518. type: _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistContextType.AUDIO_TRACK,
  13519. url: url,
  13520. deliveryDirectives: deliveryDirectives
  13521. });
  13522. };
  13523. _proto.onSubtitleTrackLoading = function onSubtitleTrackLoading(event, data) {
  13524. var id = data.id,
  13525. groupId = data.groupId,
  13526. url = data.url,
  13527. deliveryDirectives = data.deliveryDirectives;
  13528. this.load({
  13529. id: id,
  13530. groupId: groupId,
  13531. level: null,
  13532. responseType: 'text',
  13533. type: _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistContextType.SUBTITLE_TRACK,
  13534. url: url,
  13535. deliveryDirectives: deliveryDirectives
  13536. });
  13537. };
  13538. _proto.load = function load(context) {
  13539. var _context$deliveryDire;
  13540. var config = this.hls.config;
  13541. // logger.debug(`[playlist-loader]: Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);
  13542. // Check if a loader for this context already exists
  13543. var loader = this.getInternalLoader(context);
  13544. if (loader) {
  13545. var loaderContext = loader.context;
  13546. if (loaderContext && loaderContext.url === context.url) {
  13547. // same URL can't overlap
  13548. _utils_logger__WEBPACK_IMPORTED_MODULE_3__.logger.trace('[playlist-loader]: playlist request ongoing');
  13549. return;
  13550. }
  13551. _utils_logger__WEBPACK_IMPORTED_MODULE_3__.logger.log("[playlist-loader]: aborting previous loader for type: " + context.type);
  13552. loader.abort();
  13553. }
  13554. var maxRetry;
  13555. var timeout;
  13556. var retryDelay;
  13557. var maxRetryDelay;
  13558. // apply different configs for retries depending on
  13559. // context (manifest, level, audio/subs playlist)
  13560. switch (context.type) {
  13561. case _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistContextType.MANIFEST:
  13562. maxRetry = config.manifestLoadingMaxRetry;
  13563. timeout = config.manifestLoadingTimeOut;
  13564. retryDelay = config.manifestLoadingRetryDelay;
  13565. maxRetryDelay = config.manifestLoadingMaxRetryTimeout;
  13566. break;
  13567. case _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistContextType.LEVEL:
  13568. case _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistContextType.AUDIO_TRACK:
  13569. case _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistContextType.SUBTITLE_TRACK:
  13570. // Manage retries in Level/Track Controller
  13571. maxRetry = 0;
  13572. timeout = config.levelLoadingTimeOut;
  13573. break;
  13574. default:
  13575. maxRetry = config.levelLoadingMaxRetry;
  13576. timeout = config.levelLoadingTimeOut;
  13577. retryDelay = config.levelLoadingRetryDelay;
  13578. maxRetryDelay = config.levelLoadingMaxRetryTimeout;
  13579. break;
  13580. }
  13581. loader = this.createInternalLoader(context);
  13582. // Override level/track timeout for LL-HLS requests
  13583. // (the default of 10000ms is counter productive to blocking playlist reload requests)
  13584. if ((_context$deliveryDire = context.deliveryDirectives) !== null && _context$deliveryDire !== void 0 && _context$deliveryDire.part) {
  13585. var levelDetails;
  13586. if (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistContextType.LEVEL && context.level !== null) {
  13587. levelDetails = this.hls.levels[context.level].details;
  13588. } else if (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistContextType.AUDIO_TRACK && context.id !== null) {
  13589. levelDetails = this.hls.audioTracks[context.id].details;
  13590. } else if (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistContextType.SUBTITLE_TRACK && context.id !== null) {
  13591. levelDetails = this.hls.subtitleTracks[context.id].details;
  13592. }
  13593. if (levelDetails) {
  13594. var partTarget = levelDetails.partTarget;
  13595. var targetDuration = levelDetails.targetduration;
  13596. if (partTarget && targetDuration) {
  13597. timeout = Math.min(Math.max(partTarget * 3, targetDuration * 0.8) * 1000, timeout);
  13598. }
  13599. }
  13600. }
  13601. var loaderConfig = {
  13602. timeout: timeout,
  13603. maxRetry: maxRetry,
  13604. retryDelay: retryDelay,
  13605. maxRetryDelay: maxRetryDelay,
  13606. highWaterMark: 0
  13607. };
  13608. var loaderCallbacks = {
  13609. onSuccess: this.loadsuccess.bind(this),
  13610. onError: this.loaderror.bind(this),
  13611. onTimeout: this.loadtimeout.bind(this)
  13612. };
  13613. // logger.debug(`[playlist-loader]: Calling internal loader delegate for URL: ${context.url}`);
  13614. loader.load(context, loaderConfig, loaderCallbacks);
  13615. };
  13616. _proto.loadsuccess = function loadsuccess(response, stats, context, networkDetails) {
  13617. if (networkDetails === void 0) {
  13618. networkDetails = null;
  13619. }
  13620. if (context.isSidxRequest) {
  13621. this.handleSidxRequest(response, context);
  13622. this.handlePlaylistLoaded(response, stats, context, networkDetails);
  13623. return;
  13624. }
  13625. this.resetInternalLoader(context.type);
  13626. var string = response.data;
  13627. // Validate if it is an M3U8 at all
  13628. if (string.indexOf('#EXTM3U') !== 0) {
  13629. this.handleManifestParsingError(response, context, 'no EXTM3U delimiter', networkDetails);
  13630. return;
  13631. }
  13632. stats.parsing.start = performance.now();
  13633. // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present)
  13634. if (string.indexOf('#EXTINF:') > 0 || string.indexOf('#EXT-X-TARGETDURATION:') > 0) {
  13635. this.handleTrackOrLevelPlaylist(response, stats, context, networkDetails);
  13636. } else {
  13637. this.handleMasterPlaylist(response, stats, context, networkDetails);
  13638. }
  13639. };
  13640. _proto.loaderror = function loaderror(response, context, networkDetails) {
  13641. if (networkDetails === void 0) {
  13642. networkDetails = null;
  13643. }
  13644. this.handleNetworkError(context, networkDetails, false, response);
  13645. };
  13646. _proto.loadtimeout = function loadtimeout(stats, context, networkDetails) {
  13647. if (networkDetails === void 0) {
  13648. networkDetails = null;
  13649. }
  13650. this.handleNetworkError(context, networkDetails, true);
  13651. };
  13652. _proto.handleMasterPlaylist = function handleMasterPlaylist(response, stats, context, networkDetails) {
  13653. var hls = this.hls;
  13654. var string = response.data;
  13655. var url = getResponseUrl(response, context);
  13656. var _M3U8Parser$parseMast = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylist(string, url),
  13657. levels = _M3U8Parser$parseMast.levels,
  13658. sessionData = _M3U8Parser$parseMast.sessionData;
  13659. if (!levels.length) {
  13660. this.handleManifestParsingError(response, context, 'no level found in manifest', networkDetails);
  13661. return;
  13662. }
  13663. // multi level playlist, parse level info
  13664. var audioGroups = levels.map(function (level) {
  13665. return {
  13666. id: level.attrs.AUDIO,
  13667. audioCodec: level.audioCodec
  13668. };
  13669. });
  13670. var subtitleGroups = levels.map(function (level) {
  13671. return {
  13672. id: level.attrs.SUBTITLES,
  13673. textCodec: level.textCodec
  13674. };
  13675. });
  13676. var audioTracks = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups);
  13677. var subtitles = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylistMedia(string, url, 'SUBTITLES', subtitleGroups);
  13678. var captions = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylistMedia(string, url, 'CLOSED-CAPTIONS');
  13679. if (audioTracks.length) {
  13680. // check if we have found an audio track embedded in main playlist (audio track without URI attribute)
  13681. var embeddedAudioFound = audioTracks.some(function (audioTrack) {
  13682. return !audioTrack.url;
  13683. });
  13684. // if no embedded audio track defined, but audio codec signaled in quality level,
  13685. // we need to signal this main audio track this could happen with playlists with
  13686. // alt audio rendition in which quality levels (main)
  13687. // contains both audio+video. but with mixed audio track not signaled
  13688. if (!embeddedAudioFound && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
  13689. _utils_logger__WEBPACK_IMPORTED_MODULE_3__.logger.log('[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one');
  13690. audioTracks.unshift({
  13691. type: 'main',
  13692. name: 'main',
  13693. default: false,
  13694. autoselect: false,
  13695. forced: false,
  13696. id: -1,
  13697. attrs: new _utils_attr_list__WEBPACK_IMPORTED_MODULE_7__.AttrList({}),
  13698. bitrate: 0,
  13699. url: ''
  13700. });
  13701. }
  13702. }
  13703. hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.MANIFEST_LOADED, {
  13704. levels: levels,
  13705. audioTracks: audioTracks,
  13706. subtitles: subtitles,
  13707. captions: captions,
  13708. url: url,
  13709. stats: stats,
  13710. networkDetails: networkDetails,
  13711. sessionData: sessionData
  13712. });
  13713. };
  13714. _proto.handleTrackOrLevelPlaylist = function handleTrackOrLevelPlaylist(response, stats, context, networkDetails) {
  13715. var hls = this.hls;
  13716. var id = context.id,
  13717. level = context.level,
  13718. type = context.type;
  13719. var url = getResponseUrl(response, context);
  13720. var levelUrlId = (0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(id) ? id : 0;
  13721. var levelId = (0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(level) ? level : levelUrlId;
  13722. var levelType = mapContextToLevelType(context);
  13723. var levelDetails = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId);
  13724. if (!levelDetails.fragments.length) {
  13725. hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.ERROR, {
  13726. type: _errors__WEBPACK_IMPORTED_MODULE_2__.ErrorTypes.NETWORK_ERROR,
  13727. details: _errors__WEBPACK_IMPORTED_MODULE_2__.ErrorDetails.LEVEL_EMPTY_ERROR,
  13728. fatal: false,
  13729. url: url,
  13730. reason: 'no fragments found in level',
  13731. level: typeof context.level === 'number' ? context.level : undefined
  13732. });
  13733. return;
  13734. }
  13735. // We have done our first request (Manifest-type) and receive
  13736. // not a master playlist but a chunk-list (track/level)
  13737. // We fire the manifest-loaded event anyway with the parsed level-details
  13738. // by creating a single-level structure for it.
  13739. if (type === _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistContextType.MANIFEST) {
  13740. var singleLevel = {
  13741. attrs: new _utils_attr_list__WEBPACK_IMPORTED_MODULE_7__.AttrList({}),
  13742. bitrate: 0,
  13743. details: levelDetails,
  13744. name: '',
  13745. url: url
  13746. };
  13747. hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.MANIFEST_LOADED, {
  13748. levels: [singleLevel],
  13749. audioTracks: [],
  13750. url: url,
  13751. stats: stats,
  13752. networkDetails: networkDetails,
  13753. sessionData: null
  13754. });
  13755. }
  13756. // save parsing time
  13757. stats.parsing.end = performance.now();
  13758. // in case we need SIDX ranges
  13759. // return early after calling load for
  13760. // the SIDX box.
  13761. if (levelDetails.needSidxRanges) {
  13762. var _levelDetails$fragmen;
  13763. var sidxUrl = (_levelDetails$fragmen = levelDetails.fragments[0].initSegment) === null || _levelDetails$fragmen === void 0 ? void 0 : _levelDetails$fragmen.url;
  13764. this.load({
  13765. url: sidxUrl,
  13766. isSidxRequest: true,
  13767. type: type,
  13768. level: level,
  13769. levelDetails: levelDetails,
  13770. id: id,
  13771. groupId: null,
  13772. rangeStart: 0,
  13773. rangeEnd: 2048,
  13774. responseType: 'arraybuffer',
  13775. deliveryDirectives: null
  13776. });
  13777. return;
  13778. }
  13779. // extend the context with the new levelDetails property
  13780. context.levelDetails = levelDetails;
  13781. this.handlePlaylistLoaded(response, stats, context, networkDetails);
  13782. };
  13783. _proto.handleSidxRequest = function handleSidxRequest(response, context) {
  13784. var data = new Uint8Array(response.data);
  13785. var sidxBox = (0,_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__.findBox)(data, ['sidx'])[0];
  13786. // if provided fragment does not contain sidx, early return
  13787. if (!sidxBox) {
  13788. return;
  13789. }
  13790. var sidxInfo = (0,_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__.parseSegmentIndex)(sidxBox);
  13791. if (!sidxInfo) {
  13792. return;
  13793. }
  13794. var sidxReferences = sidxInfo.references;
  13795. var levelDetails = context.levelDetails;
  13796. sidxReferences.forEach(function (segmentRef, index) {
  13797. var segRefInfo = segmentRef.info;
  13798. var frag = levelDetails.fragments[index];
  13799. if (frag.byteRange.length === 0) {
  13800. frag.setByteRange(String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start));
  13801. }
  13802. if (frag.initSegment) {
  13803. var moovBox = (0,_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__.findBox)(data, ['moov'])[0];
  13804. var moovEndOffset = moovBox ? moovBox.length : null;
  13805. frag.initSegment.setByteRange(String(moovEndOffset) + '@0');
  13806. }
  13807. });
  13808. };
  13809. _proto.handleManifestParsingError = function handleManifestParsingError(response, context, reason, networkDetails) {
  13810. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.ERROR, {
  13811. type: _errors__WEBPACK_IMPORTED_MODULE_2__.ErrorTypes.NETWORK_ERROR,
  13812. details: _errors__WEBPACK_IMPORTED_MODULE_2__.ErrorDetails.MANIFEST_PARSING_ERROR,
  13813. fatal: context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistContextType.MANIFEST,
  13814. url: response.url,
  13815. reason: reason,
  13816. response: response,
  13817. context: context,
  13818. networkDetails: networkDetails
  13819. });
  13820. };
  13821. _proto.handleNetworkError = function handleNetworkError(context, networkDetails, timeout, response) {
  13822. if (timeout === void 0) {
  13823. timeout = false;
  13824. }
  13825. _utils_logger__WEBPACK_IMPORTED_MODULE_3__.logger.warn("[playlist-loader]: A network " + (timeout ? 'timeout' : 'error') + " occurred while loading " + context.type + " level: " + context.level + " id: " + context.id + " group-id: \"" + context.groupId + "\"");
  13826. var details = _errors__WEBPACK_IMPORTED_MODULE_2__.ErrorDetails.UNKNOWN;
  13827. var fatal = false;
  13828. var loader = this.getInternalLoader(context);
  13829. switch (context.type) {
  13830. case _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistContextType.MANIFEST:
  13831. details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__.ErrorDetails.MANIFEST_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__.ErrorDetails.MANIFEST_LOAD_ERROR;
  13832. fatal = true;
  13833. break;
  13834. case _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistContextType.LEVEL:
  13835. details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__.ErrorDetails.LEVEL_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__.ErrorDetails.LEVEL_LOAD_ERROR;
  13836. fatal = false;
  13837. break;
  13838. case _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistContextType.AUDIO_TRACK:
  13839. details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__.ErrorDetails.AUDIO_TRACK_LOAD_ERROR;
  13840. fatal = false;
  13841. break;
  13842. case _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistContextType.SUBTITLE_TRACK:
  13843. details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__.ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__.ErrorDetails.SUBTITLE_LOAD_ERROR;
  13844. fatal = false;
  13845. break;
  13846. }
  13847. if (loader) {
  13848. this.resetInternalLoader(context.type);
  13849. }
  13850. var errorData = {
  13851. type: _errors__WEBPACK_IMPORTED_MODULE_2__.ErrorTypes.NETWORK_ERROR,
  13852. details: details,
  13853. fatal: fatal,
  13854. url: context.url,
  13855. loader: loader,
  13856. context: context,
  13857. networkDetails: networkDetails
  13858. };
  13859. if (response) {
  13860. errorData.response = response;
  13861. }
  13862. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.ERROR, errorData);
  13863. };
  13864. _proto.handlePlaylistLoaded = function handlePlaylistLoaded(response, stats, context, networkDetails) {
  13865. var type = context.type,
  13866. level = context.level,
  13867. id = context.id,
  13868. groupId = context.groupId,
  13869. loader = context.loader,
  13870. levelDetails = context.levelDetails,
  13871. deliveryDirectives = context.deliveryDirectives;
  13872. if (!(levelDetails !== null && levelDetails !== void 0 && levelDetails.targetduration)) {
  13873. this.handleManifestParsingError(response, context, 'invalid target duration', networkDetails);
  13874. return;
  13875. }
  13876. if (!loader) {
  13877. return;
  13878. }
  13879. if (levelDetails.live) {
  13880. if (loader.getCacheAge) {
  13881. levelDetails.ageHeader = loader.getCacheAge() || 0;
  13882. }
  13883. if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) {
  13884. levelDetails.ageHeader = 0;
  13885. }
  13886. }
  13887. switch (type) {
  13888. case _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistContextType.MANIFEST:
  13889. case _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistContextType.LEVEL:
  13890. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.LEVEL_LOADED, {
  13891. details: levelDetails,
  13892. level: level || 0,
  13893. id: id || 0,
  13894. stats: stats,
  13895. networkDetails: networkDetails,
  13896. deliveryDirectives: deliveryDirectives
  13897. });
  13898. break;
  13899. case _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistContextType.AUDIO_TRACK:
  13900. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.AUDIO_TRACK_LOADED, {
  13901. details: levelDetails,
  13902. id: id || 0,
  13903. groupId: groupId || '',
  13904. stats: stats,
  13905. networkDetails: networkDetails,
  13906. deliveryDirectives: deliveryDirectives
  13907. });
  13908. break;
  13909. case _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistContextType.SUBTITLE_TRACK:
  13910. this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__.Events.SUBTITLE_TRACK_LOADED, {
  13911. details: levelDetails,
  13912. id: id || 0,
  13913. groupId: groupId || '',
  13914. stats: stats,
  13915. networkDetails: networkDetails,
  13916. deliveryDirectives: deliveryDirectives
  13917. });
  13918. break;
  13919. }
  13920. };
  13921. return PlaylistLoader;
  13922. }();
  13923. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (PlaylistLoader);
  13924. /***/ }),
  13925. /***/ "./src/polyfills/number.ts":
  13926. /*!*********************************!*\
  13927. !*** ./src/polyfills/number.ts ***!
  13928. \*********************************/
  13929. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  13930. "use strict";
  13931. __webpack_require__.r(__webpack_exports__);
  13932. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  13933. /* harmony export */ "MAX_SAFE_INTEGER": () => (/* binding */ MAX_SAFE_INTEGER),
  13934. /* harmony export */ "isFiniteNumber": () => (/* binding */ isFiniteNumber)
  13935. /* harmony export */ });
  13936. var isFiniteNumber = Number.isFinite || function (value) {
  13937. return typeof value === 'number' && isFinite(value);
  13938. };
  13939. var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  13940. /***/ }),
  13941. /***/ "./src/remux/aac-helper.ts":
  13942. /*!*********************************!*\
  13943. !*** ./src/remux/aac-helper.ts ***!
  13944. \*********************************/
  13945. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  13946. "use strict";
  13947. __webpack_require__.r(__webpack_exports__);
  13948. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  13949. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  13950. /* harmony export */ });
  13951. /**
  13952. * AAC helper
  13953. */
  13954. var AAC = /*#__PURE__*/function () {
  13955. function AAC() {}
  13956. AAC.getSilentFrame = function getSilentFrame(codec, channelCount) {
  13957. switch (codec) {
  13958. case 'mp4a.40.2':
  13959. if (channelCount === 1) {
  13960. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
  13961. } else if (channelCount === 2) {
  13962. return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
  13963. } else if (channelCount === 3) {
  13964. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
  13965. } else if (channelCount === 4) {
  13966. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
  13967. } else if (channelCount === 5) {
  13968. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
  13969. } else if (channelCount === 6) {
  13970. 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]);
  13971. }
  13972. break;
  13973. // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)
  13974. default:
  13975. if (channelCount === 1) {
  13976. // 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
  13977. 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]);
  13978. } else if (channelCount === 2) {
  13979. // 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
  13980. 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]);
  13981. } else if (channelCount === 3) {
  13982. // 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
  13983. 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]);
  13984. }
  13985. break;
  13986. }
  13987. return undefined;
  13988. };
  13989. return AAC;
  13990. }();
  13991. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (AAC);
  13992. /***/ }),
  13993. /***/ "./src/remux/mp4-generator.ts":
  13994. /*!************************************!*\
  13995. !*** ./src/remux/mp4-generator.ts ***!
  13996. \************************************/
  13997. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  13998. "use strict";
  13999. __webpack_require__.r(__webpack_exports__);
  14000. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  14001. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  14002. /* harmony export */ });
  14003. /**
  14004. * Generate MP4 Box
  14005. */
  14006. var UINT32_MAX = Math.pow(2, 32) - 1;
  14007. var MP4 = /*#__PURE__*/function () {
  14008. function MP4() {}
  14009. MP4.init = function init() {
  14010. MP4.types = {
  14011. avc1: [],
  14012. // codingname
  14013. avcC: [],
  14014. btrt: [],
  14015. dinf: [],
  14016. dref: [],
  14017. esds: [],
  14018. ftyp: [],
  14019. hdlr: [],
  14020. mdat: [],
  14021. mdhd: [],
  14022. mdia: [],
  14023. mfhd: [],
  14024. minf: [],
  14025. moof: [],
  14026. moov: [],
  14027. mp4a: [],
  14028. '.mp3': [],
  14029. mvex: [],
  14030. mvhd: [],
  14031. pasp: [],
  14032. sdtp: [],
  14033. stbl: [],
  14034. stco: [],
  14035. stsc: [],
  14036. stsd: [],
  14037. stsz: [],
  14038. stts: [],
  14039. tfdt: [],
  14040. tfhd: [],
  14041. traf: [],
  14042. trak: [],
  14043. trun: [],
  14044. trex: [],
  14045. tkhd: [],
  14046. vmhd: [],
  14047. smhd: []
  14048. };
  14049. var i;
  14050. for (i in MP4.types) {
  14051. if (MP4.types.hasOwnProperty(i)) {
  14052. MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  14053. }
  14054. }
  14055. var videoHdlr = new Uint8Array([0x00,
  14056. // version 0
  14057. 0x00, 0x00, 0x00,
  14058. // flags
  14059. 0x00, 0x00, 0x00, 0x00,
  14060. // pre_defined
  14061. 0x76, 0x69, 0x64, 0x65,
  14062. // handler_type: 'vide'
  14063. 0x00, 0x00, 0x00, 0x00,
  14064. // reserved
  14065. 0x00, 0x00, 0x00, 0x00,
  14066. // reserved
  14067. 0x00, 0x00, 0x00, 0x00,
  14068. // reserved
  14069. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  14070. ]);
  14071. var audioHdlr = new Uint8Array([0x00,
  14072. // version 0
  14073. 0x00, 0x00, 0x00,
  14074. // flags
  14075. 0x00, 0x00, 0x00, 0x00,
  14076. // pre_defined
  14077. 0x73, 0x6f, 0x75, 0x6e,
  14078. // handler_type: 'soun'
  14079. 0x00, 0x00, 0x00, 0x00,
  14080. // reserved
  14081. 0x00, 0x00, 0x00, 0x00,
  14082. // reserved
  14083. 0x00, 0x00, 0x00, 0x00,
  14084. // reserved
  14085. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  14086. ]);
  14087. MP4.HDLR_TYPES = {
  14088. video: videoHdlr,
  14089. audio: audioHdlr
  14090. };
  14091. var dref = new Uint8Array([0x00,
  14092. // version 0
  14093. 0x00, 0x00, 0x00,
  14094. // flags
  14095. 0x00, 0x00, 0x00, 0x01,
  14096. // entry_count
  14097. 0x00, 0x00, 0x00, 0x0c,
  14098. // entry_size
  14099. 0x75, 0x72, 0x6c, 0x20,
  14100. // 'url' type
  14101. 0x00,
  14102. // version 0
  14103. 0x00, 0x00, 0x01 // entry_flags
  14104. ]);
  14105. var stco = new Uint8Array([0x00,
  14106. // version
  14107. 0x00, 0x00, 0x00,
  14108. // flags
  14109. 0x00, 0x00, 0x00, 0x00 // entry_count
  14110. ]);
  14111. MP4.STTS = MP4.STSC = MP4.STCO = stco;
  14112. MP4.STSZ = new Uint8Array([0x00,
  14113. // version
  14114. 0x00, 0x00, 0x00,
  14115. // flags
  14116. 0x00, 0x00, 0x00, 0x00,
  14117. // sample_size
  14118. 0x00, 0x00, 0x00, 0x00 // sample_count
  14119. ]);
  14120. MP4.VMHD = new Uint8Array([0x00,
  14121. // version
  14122. 0x00, 0x00, 0x01,
  14123. // flags
  14124. 0x00, 0x00,
  14125. // graphicsmode
  14126. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  14127. ]);
  14128. MP4.SMHD = new Uint8Array([0x00,
  14129. // version
  14130. 0x00, 0x00, 0x00,
  14131. // flags
  14132. 0x00, 0x00,
  14133. // balance
  14134. 0x00, 0x00 // reserved
  14135. ]);
  14136. MP4.STSD = new Uint8Array([0x00,
  14137. // version 0
  14138. 0x00, 0x00, 0x00,
  14139. // flags
  14140. 0x00, 0x00, 0x00, 0x01]); // entry_count
  14141. var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom
  14142. var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1
  14143. var minorVersion = new Uint8Array([0, 0, 0, 1]);
  14144. MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
  14145. MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
  14146. };
  14147. MP4.box = function box(type) {
  14148. var size = 8;
  14149. for (var _len = arguments.length, payload = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  14150. payload[_key - 1] = arguments[_key];
  14151. }
  14152. var i = payload.length;
  14153. var len = i;
  14154. // calculate the total size we need to allocate
  14155. while (i--) {
  14156. size += payload[i].byteLength;
  14157. }
  14158. var result = new Uint8Array(size);
  14159. result[0] = size >> 24 & 0xff;
  14160. result[1] = size >> 16 & 0xff;
  14161. result[2] = size >> 8 & 0xff;
  14162. result[3] = size & 0xff;
  14163. result.set(type, 4);
  14164. // copy the payload into the result
  14165. for (i = 0, size = 8; i < len; i++) {
  14166. // copy payload[i] array @ offset size
  14167. result.set(payload[i], size);
  14168. size += payload[i].byteLength;
  14169. }
  14170. return result;
  14171. };
  14172. MP4.hdlr = function hdlr(type) {
  14173. return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
  14174. };
  14175. MP4.mdat = function mdat(data) {
  14176. return MP4.box(MP4.types.mdat, data);
  14177. };
  14178. MP4.mdhd = function mdhd(timescale, duration) {
  14179. duration *= timescale;
  14180. var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  14181. var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  14182. return MP4.box(MP4.types.mdhd, new Uint8Array([0x01,
  14183. // version 1
  14184. 0x00, 0x00, 0x00,
  14185. // flags
  14186. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  14187. // creation_time
  14188. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  14189. // modification_time
  14190. timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff,
  14191. // timescale
  14192. upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x55, 0xc4,
  14193. // 'und' language (undetermined)
  14194. 0x00, 0x00]));
  14195. };
  14196. MP4.mdia = function mdia(track) {
  14197. return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));
  14198. };
  14199. MP4.mfhd = function mfhd(sequenceNumber) {
  14200. return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00,
  14201. // flags
  14202. sequenceNumber >> 24, sequenceNumber >> 16 & 0xff, sequenceNumber >> 8 & 0xff, sequenceNumber & 0xff // sequence_number
  14203. ]));
  14204. };
  14205. MP4.minf = function minf(track) {
  14206. if (track.type === 'audio') {
  14207. return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
  14208. } else {
  14209. return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
  14210. }
  14211. };
  14212. MP4.moof = function moof(sn, baseMediaDecodeTime, track) {
  14213. return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
  14214. }
  14215. /**
  14216. * @param tracks... (optional) {array} the tracks associated with this movie
  14217. */;
  14218. MP4.moov = function moov(tracks) {
  14219. var i = tracks.length;
  14220. var boxes = [];
  14221. while (i--) {
  14222. boxes[i] = MP4.trak(tracks[i]);
  14223. }
  14224. return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));
  14225. };
  14226. MP4.mvex = function mvex(tracks) {
  14227. var i = tracks.length;
  14228. var boxes = [];
  14229. while (i--) {
  14230. boxes[i] = MP4.trex(tracks[i]);
  14231. }
  14232. return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));
  14233. };
  14234. MP4.mvhd = function mvhd(timescale, duration) {
  14235. duration *= timescale;
  14236. var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  14237. var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  14238. var bytes = new Uint8Array([0x01,
  14239. // version 1
  14240. 0x00, 0x00, 0x00,
  14241. // flags
  14242. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  14243. // creation_time
  14244. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  14245. // modification_time
  14246. timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff,
  14247. // timescale
  14248. upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x00, 0x01, 0x00, 0x00,
  14249. // 1.0 rate
  14250. 0x01, 0x00,
  14251. // 1.0 volume
  14252. 0x00, 0x00,
  14253. // reserved
  14254. 0x00, 0x00, 0x00, 0x00,
  14255. // reserved
  14256. 0x00, 0x00, 0x00, 0x00,
  14257. // reserved
  14258. 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,
  14259. // transformation: unity matrix
  14260. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  14261. // pre_defined
  14262. 0xff, 0xff, 0xff, 0xff // next_track_ID
  14263. ]);
  14264. return MP4.box(MP4.types.mvhd, bytes);
  14265. };
  14266. MP4.sdtp = function sdtp(track) {
  14267. var samples = track.samples || [];
  14268. var bytes = new Uint8Array(4 + samples.length);
  14269. var i;
  14270. var flags;
  14271. // leave the full box header (4 bytes) all zero
  14272. // write the sample table
  14273. for (i = 0; i < samples.length; i++) {
  14274. flags = samples[i].flags;
  14275. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  14276. }
  14277. return MP4.box(MP4.types.sdtp, bytes);
  14278. };
  14279. MP4.stbl = function stbl(track) {
  14280. 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));
  14281. };
  14282. MP4.avc1 = function avc1(track) {
  14283. var sps = [];
  14284. var pps = [];
  14285. var i;
  14286. var data;
  14287. var len;
  14288. // assemble the SPSs
  14289. for (i = 0; i < track.sps.length; i++) {
  14290. data = track.sps[i];
  14291. len = data.byteLength;
  14292. sps.push(len >>> 8 & 0xff);
  14293. sps.push(len & 0xff);
  14294. // SPS
  14295. sps = sps.concat(Array.prototype.slice.call(data));
  14296. }
  14297. // assemble the PPSs
  14298. for (i = 0; i < track.pps.length; i++) {
  14299. data = track.pps[i];
  14300. len = data.byteLength;
  14301. pps.push(len >>> 8 & 0xff);
  14302. pps.push(len & 0xff);
  14303. pps = pps.concat(Array.prototype.slice.call(data));
  14304. }
  14305. var avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01,
  14306. // version
  14307. sps[3],
  14308. // profile
  14309. sps[4],
  14310. // profile compat
  14311. sps[5],
  14312. // level
  14313. 0xfc | 3,
  14314. // lengthSizeMinusOne, hard-coded to 4 bytes
  14315. 0xe0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets
  14316. ].concat(sps).concat([track.pps.length // numOfPictureParameterSets
  14317. ]).concat(pps))); // "PPS"
  14318. var width = track.width;
  14319. var height = track.height;
  14320. var hSpacing = track.pixelRatio[0];
  14321. var vSpacing = track.pixelRatio[1];
  14322. return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00,
  14323. // reserved
  14324. 0x00, 0x00, 0x00,
  14325. // reserved
  14326. 0x00, 0x01,
  14327. // data_reference_index
  14328. 0x00, 0x00,
  14329. // pre_defined
  14330. 0x00, 0x00,
  14331. // reserved
  14332. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  14333. // pre_defined
  14334. width >> 8 & 0xff, width & 0xff,
  14335. // width
  14336. height >> 8 & 0xff, height & 0xff,
  14337. // height
  14338. 0x00, 0x48, 0x00, 0x00,
  14339. // horizresolution
  14340. 0x00, 0x48, 0x00, 0x00,
  14341. // vertresolution
  14342. 0x00, 0x00, 0x00, 0x00,
  14343. // reserved
  14344. 0x00, 0x01,
  14345. // frame_count
  14346. 0x12, 0x64, 0x61, 0x69, 0x6c,
  14347. // dailymotion/hls.js
  14348. 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,
  14349. // compressorname
  14350. 0x00, 0x18,
  14351. // depth = 24
  14352. 0x11, 0x11]),
  14353. // pre_defined = -1
  14354. avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80,
  14355. // bufferSizeDB
  14356. 0x00, 0x2d, 0xc6, 0xc0,
  14357. // maxBitrate
  14358. 0x00, 0x2d, 0xc6, 0xc0])),
  14359. // avgBitrate
  14360. MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24,
  14361. // hSpacing
  14362. hSpacing >> 16 & 0xff, hSpacing >> 8 & 0xff, hSpacing & 0xff, vSpacing >> 24,
  14363. // vSpacing
  14364. vSpacing >> 16 & 0xff, vSpacing >> 8 & 0xff, vSpacing & 0xff])));
  14365. };
  14366. MP4.esds = function esds(track) {
  14367. var configlen = track.config.length;
  14368. return new Uint8Array([0x00,
  14369. // version 0
  14370. 0x00, 0x00, 0x00,
  14371. // flags
  14372. 0x03,
  14373. // descriptor_type
  14374. 0x17 + configlen,
  14375. // length
  14376. 0x00, 0x01,
  14377. // es_id
  14378. 0x00,
  14379. // stream_priority
  14380. 0x04,
  14381. // descriptor_type
  14382. 0x0f + configlen,
  14383. // length
  14384. 0x40,
  14385. // codec : mpeg4_audio
  14386. 0x15,
  14387. // stream_type
  14388. 0x00, 0x00, 0x00,
  14389. // buffer_size
  14390. 0x00, 0x00, 0x00, 0x00,
  14391. // maxBitrate
  14392. 0x00, 0x00, 0x00, 0x00,
  14393. // avgBitrate
  14394. 0x05 // descriptor_type
  14395. ].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor
  14396. };
  14397. MP4.mp4a = function mp4a(track) {
  14398. var samplerate = track.samplerate;
  14399. return MP4.box(MP4.types.mp4a, new Uint8Array([0x00, 0x00, 0x00,
  14400. // reserved
  14401. 0x00, 0x00, 0x00,
  14402. // reserved
  14403. 0x00, 0x01,
  14404. // data_reference_index
  14405. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  14406. // reserved
  14407. 0x00, track.channelCount,
  14408. // channelcount
  14409. 0x00, 0x10,
  14410. // sampleSize:16bits
  14411. 0x00, 0x00, 0x00, 0x00,
  14412. // reserved2
  14413. samplerate >> 8 & 0xff, samplerate & 0xff,
  14414. //
  14415. 0x00, 0x00]), MP4.box(MP4.types.esds, MP4.esds(track)));
  14416. };
  14417. MP4.mp3 = function mp3(track) {
  14418. var samplerate = track.samplerate;
  14419. return MP4.box(MP4.types['.mp3'], new Uint8Array([0x00, 0x00, 0x00,
  14420. // reserved
  14421. 0x00, 0x00, 0x00,
  14422. // reserved
  14423. 0x00, 0x01,
  14424. // data_reference_index
  14425. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  14426. // reserved
  14427. 0x00, track.channelCount,
  14428. // channelcount
  14429. 0x00, 0x10,
  14430. // sampleSize:16bits
  14431. 0x00, 0x00, 0x00, 0x00,
  14432. // reserved2
  14433. samplerate >> 8 & 0xff, samplerate & 0xff,
  14434. //
  14435. 0x00, 0x00]));
  14436. };
  14437. MP4.stsd = function stsd(track) {
  14438. if (track.type === 'audio') {
  14439. if (track.segmentCodec === 'mp3' && track.codec === 'mp3') {
  14440. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));
  14441. }
  14442. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
  14443. } else {
  14444. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
  14445. }
  14446. };
  14447. MP4.tkhd = function tkhd(track) {
  14448. var id = track.id;
  14449. var duration = track.duration * track.timescale;
  14450. var width = track.width;
  14451. var height = track.height;
  14452. var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  14453. var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  14454. return MP4.box(MP4.types.tkhd, new Uint8Array([0x01,
  14455. // version 1
  14456. 0x00, 0x00, 0x07,
  14457. // flags
  14458. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  14459. // creation_time
  14460. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  14461. // modification_time
  14462. id >> 24 & 0xff, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff,
  14463. // track_ID
  14464. 0x00, 0x00, 0x00, 0x00,
  14465. // reserved
  14466. 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,
  14467. // reserved
  14468. 0x00, 0x00,
  14469. // layer
  14470. 0x00, 0x00,
  14471. // alternate_group
  14472. 0x00, 0x00,
  14473. // non-audio track volume
  14474. 0x00, 0x00,
  14475. // reserved
  14476. 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,
  14477. // transformation: unity matrix
  14478. width >> 8 & 0xff, width & 0xff, 0x00, 0x00,
  14479. // width
  14480. height >> 8 & 0xff, height & 0xff, 0x00, 0x00 // height
  14481. ]));
  14482. };
  14483. MP4.traf = function traf(track, baseMediaDecodeTime) {
  14484. var sampleDependencyTable = MP4.sdtp(track);
  14485. var id = track.id;
  14486. var upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
  14487. var lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
  14488. return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00,
  14489. // version 0
  14490. 0x00, 0x00, 0x00,
  14491. // flags
  14492. id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff // track_ID
  14493. ])), MP4.box(MP4.types.tfdt, new Uint8Array([0x01,
  14494. // version 1
  14495. 0x00, 0x00, 0x00,
  14496. // flags
  14497. 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 +
  14498. // tfhd
  14499. 20 +
  14500. // tfdt
  14501. 8 +
  14502. // traf header
  14503. 16 +
  14504. // mfhd
  14505. 8 +
  14506. // moof header
  14507. 8),
  14508. // mdat header
  14509. sampleDependencyTable);
  14510. }
  14511. /**
  14512. * Generate a track box.
  14513. * @param track {object} a track definition
  14514. * @return {Uint8Array} the track box
  14515. */;
  14516. MP4.trak = function trak(track) {
  14517. track.duration = track.duration || 0xffffffff;
  14518. return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
  14519. };
  14520. MP4.trex = function trex(track) {
  14521. var id = track.id;
  14522. return MP4.box(MP4.types.trex, new Uint8Array([0x00,
  14523. // version 0
  14524. 0x00, 0x00, 0x00,
  14525. // flags
  14526. id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff,
  14527. // track_ID
  14528. 0x00, 0x00, 0x00, 0x01,
  14529. // default_sample_description_index
  14530. 0x00, 0x00, 0x00, 0x00,
  14531. // default_sample_duration
  14532. 0x00, 0x00, 0x00, 0x00,
  14533. // default_sample_size
  14534. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  14535. ]));
  14536. };
  14537. MP4.trun = function trun(track, offset) {
  14538. var samples = track.samples || [];
  14539. var len = samples.length;
  14540. var arraylen = 12 + 16 * len;
  14541. var array = new Uint8Array(arraylen);
  14542. var i;
  14543. var sample;
  14544. var duration;
  14545. var size;
  14546. var flags;
  14547. var cts;
  14548. offset += 8 + arraylen;
  14549. array.set([track.type === 'video' ? 0x01 : 0x00,
  14550. // version 1 for video with signed-int sample_composition_time_offset
  14551. 0x00, 0x0f, 0x01,
  14552. // flags
  14553. len >>> 24 & 0xff, len >>> 16 & 0xff, len >>> 8 & 0xff, len & 0xff,
  14554. // sample_count
  14555. offset >>> 24 & 0xff, offset >>> 16 & 0xff, offset >>> 8 & 0xff, offset & 0xff // data_offset
  14556. ], 0);
  14557. for (i = 0; i < len; i++) {
  14558. sample = samples[i];
  14559. duration = sample.duration;
  14560. size = sample.size;
  14561. flags = sample.flags;
  14562. cts = sample.cts;
  14563. array.set([duration >>> 24 & 0xff, duration >>> 16 & 0xff, duration >>> 8 & 0xff, duration & 0xff,
  14564. // sample_duration
  14565. size >>> 24 & 0xff, size >>> 16 & 0xff, size >>> 8 & 0xff, size & 0xff,
  14566. // sample_size
  14567. flags.isLeading << 2 | flags.dependsOn, flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync, flags.degradPrio & 0xf0 << 8, flags.degradPrio & 0x0f,
  14568. // sample_flags
  14569. cts >>> 24 & 0xff, cts >>> 16 & 0xff, cts >>> 8 & 0xff, cts & 0xff // sample_composition_time_offset
  14570. ], 12 + 16 * i);
  14571. }
  14572. return MP4.box(MP4.types.trun, array);
  14573. };
  14574. MP4.initSegment = function initSegment(tracks) {
  14575. if (!MP4.types) {
  14576. MP4.init();
  14577. }
  14578. var movie = MP4.moov(tracks);
  14579. var result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);
  14580. result.set(MP4.FTYP);
  14581. result.set(movie, MP4.FTYP.byteLength);
  14582. return result;
  14583. };
  14584. return MP4;
  14585. }();
  14586. MP4.types = void 0;
  14587. MP4.HDLR_TYPES = void 0;
  14588. MP4.STTS = void 0;
  14589. MP4.STSC = void 0;
  14590. MP4.STCO = void 0;
  14591. MP4.STSZ = void 0;
  14592. MP4.VMHD = void 0;
  14593. MP4.SMHD = void 0;
  14594. MP4.STSD = void 0;
  14595. MP4.FTYP = void 0;
  14596. MP4.DINF = void 0;
  14597. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (MP4);
  14598. /***/ }),
  14599. /***/ "./src/remux/mp4-remuxer.ts":
  14600. /*!**********************************!*\
  14601. !*** ./src/remux/mp4-remuxer.ts ***!
  14602. \**********************************/
  14603. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  14604. "use strict";
  14605. __webpack_require__.r(__webpack_exports__);
  14606. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  14607. /* harmony export */ "default": () => (/* binding */ MP4Remuxer),
  14608. /* harmony export */ "flushTextTrackMetadataCueSamples": () => (/* binding */ flushTextTrackMetadataCueSamples),
  14609. /* harmony export */ "flushTextTrackUserdataCueSamples": () => (/* binding */ flushTextTrackUserdataCueSamples),
  14610. /* harmony export */ "normalizePts": () => (/* binding */ normalizePts)
  14611. /* harmony export */ });
  14612. /* harmony import */ var _Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
  14613. /* harmony import */ var _aac_helper__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./aac-helper */ "./src/remux/aac-helper.ts");
  14614. /* harmony import */ var _mp4_generator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./mp4-generator */ "./src/remux/mp4-generator.ts");
  14615. /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../events */ "./src/events.ts");
  14616. /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
  14617. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
  14618. /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
  14619. /* harmony import */ var _utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/timescale-conversion */ "./src/utils/timescale-conversion.ts");
  14620. function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
  14621. var MAX_SILENT_FRAME_DURATION = 10 * 1000; // 10 seconds
  14622. var AAC_SAMPLES_PER_FRAME = 1024;
  14623. var MPEG_AUDIO_SAMPLE_PER_FRAME = 1152;
  14624. var chromeVersion = null;
  14625. var safariWebkitVersion = null;
  14626. var MP4Remuxer = /*#__PURE__*/function () {
  14627. function MP4Remuxer(observer, config, typeSupported, vendor) {
  14628. if (vendor === void 0) {
  14629. vendor = '';
  14630. }
  14631. this.observer = void 0;
  14632. this.config = void 0;
  14633. this.typeSupported = void 0;
  14634. this.ISGenerated = false;
  14635. this._initPTS = void 0;
  14636. this._initDTS = void 0;
  14637. this.nextAvcDts = null;
  14638. this.nextAudioPts = null;
  14639. this.videoSampleDuration = null;
  14640. this.isAudioContiguous = false;
  14641. this.isVideoContiguous = false;
  14642. this.observer = observer;
  14643. this.config = config;
  14644. this.typeSupported = typeSupported;
  14645. this.ISGenerated = false;
  14646. if (chromeVersion === null) {
  14647. var userAgent = navigator.userAgent || '';
  14648. var result = userAgent.match(/Chrome\/(\d+)/i);
  14649. chromeVersion = result ? parseInt(result[1]) : 0;
  14650. }
  14651. if (safariWebkitVersion === null) {
  14652. var _result = navigator.userAgent.match(/Safari\/(\d+)/i);
  14653. safariWebkitVersion = _result ? parseInt(_result[1]) : 0;
  14654. }
  14655. }
  14656. var _proto = MP4Remuxer.prototype;
  14657. _proto.destroy = function destroy() {};
  14658. _proto.resetTimeStamp = function resetTimeStamp(defaultTimeStamp) {
  14659. _utils_logger__WEBPACK_IMPORTED_MODULE_5__.logger.log('[mp4-remuxer]: initPTS & initDTS reset');
  14660. this._initPTS = this._initDTS = defaultTimeStamp;
  14661. };
  14662. _proto.resetNextTimestamp = function resetNextTimestamp() {
  14663. _utils_logger__WEBPACK_IMPORTED_MODULE_5__.logger.log('[mp4-remuxer]: reset next timestamp');
  14664. this.isVideoContiguous = false;
  14665. this.isAudioContiguous = false;
  14666. };
  14667. _proto.resetInitSegment = function resetInitSegment() {
  14668. _utils_logger__WEBPACK_IMPORTED_MODULE_5__.logger.log('[mp4-remuxer]: ISGenerated flag reset');
  14669. this.ISGenerated = false;
  14670. };
  14671. _proto.getVideoStartPts = function getVideoStartPts(videoSamples) {
  14672. var rolloverDetected = false;
  14673. var startPTS = videoSamples.reduce(function (minPTS, sample) {
  14674. var delta = sample.pts - minPTS;
  14675. if (delta < -4294967296) {
  14676. // 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation
  14677. rolloverDetected = true;
  14678. return normalizePts(minPTS, sample.pts);
  14679. } else if (delta > 0) {
  14680. return minPTS;
  14681. } else {
  14682. return sample.pts;
  14683. }
  14684. }, videoSamples[0].pts);
  14685. if (rolloverDetected) {
  14686. _utils_logger__WEBPACK_IMPORTED_MODULE_5__.logger.debug('PTS rollover detected');
  14687. }
  14688. return startPTS;
  14689. };
  14690. _proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, flush, playlistType) {
  14691. var video;
  14692. var audio;
  14693. var initSegment;
  14694. var text;
  14695. var id3;
  14696. var independent;
  14697. var audioTimeOffset = timeOffset;
  14698. var videoTimeOffset = timeOffset;
  14699. // If we're remuxing audio and video progressively, wait until we've received enough samples for each track before proceeding.
  14700. // This is done to synchronize the audio and video streams. We know if the current segment will have samples if the "pid"
  14701. // parameter is greater than -1. The pid is set when the PMT is parsed, which contains the tracks list.
  14702. // However, if the initSegment has already been generated, or we've reached the end of a segment (flush),
  14703. // then we can remux one track without waiting for the other.
  14704. var hasAudio = audioTrack.pid > -1;
  14705. var hasVideo = videoTrack.pid > -1;
  14706. var length = videoTrack.samples.length;
  14707. var enoughAudioSamples = audioTrack.samples.length > 0;
  14708. var enoughVideoSamples = flush && length > 0 || length > 1;
  14709. var canRemuxAvc = (!hasAudio || enoughAudioSamples) && (!hasVideo || enoughVideoSamples) || this.ISGenerated || flush;
  14710. if (canRemuxAvc) {
  14711. if (!this.ISGenerated) {
  14712. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset);
  14713. }
  14714. var isVideoContiguous = this.isVideoContiguous;
  14715. var firstKeyFrameIndex = -1;
  14716. var firstKeyFramePTS;
  14717. if (enoughVideoSamples) {
  14718. firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples);
  14719. if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) {
  14720. independent = true;
  14721. if (firstKeyFrameIndex > 0) {
  14722. _utils_logger__WEBPACK_IMPORTED_MODULE_5__.logger.warn("[mp4-remuxer]: Dropped " + firstKeyFrameIndex + " out of " + length + " video samples due to a missing keyframe");
  14723. var startPTS = this.getVideoStartPts(videoTrack.samples);
  14724. videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex);
  14725. videoTrack.dropped += firstKeyFrameIndex;
  14726. videoTimeOffset += (videoTrack.samples[0].pts - startPTS) / videoTrack.inputTimeScale;
  14727. firstKeyFramePTS = videoTimeOffset;
  14728. } else if (firstKeyFrameIndex === -1) {
  14729. _utils_logger__WEBPACK_IMPORTED_MODULE_5__.logger.warn("[mp4-remuxer]: No keyframe found out of " + length + " video samples");
  14730. independent = false;
  14731. }
  14732. }
  14733. }
  14734. if (this.ISGenerated) {
  14735. if (enoughAudioSamples && enoughVideoSamples) {
  14736. // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)
  14737. // if first audio DTS is not aligned with first video DTS then we need to take that into account
  14738. // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small
  14739. // drift between audio and video streams
  14740. var _startPTS = this.getVideoStartPts(videoTrack.samples);
  14741. var tsDelta = normalizePts(audioTrack.samples[0].pts, _startPTS) - _startPTS;
  14742. var audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;
  14743. audioTimeOffset += Math.max(0, audiovideoTimestampDelta);
  14744. videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);
  14745. }
  14746. // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is calculated in remuxAudio.
  14747. if (enoughAudioSamples) {
  14748. // if initSegment was generated without audio samples, regenerate it again
  14749. if (!audioTrack.samplerate) {
  14750. _utils_logger__WEBPACK_IMPORTED_MODULE_5__.logger.warn('[mp4-remuxer]: regenerate InitSegment as audio detected');
  14751. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset);
  14752. }
  14753. audio = this.remuxAudio(audioTrack, audioTimeOffset, this.isAudioContiguous, accurateTimeOffset, hasVideo || enoughVideoSamples || playlistType === _types_loader__WEBPACK_IMPORTED_MODULE_6__.PlaylistLevelType.AUDIO ? videoTimeOffset : undefined);
  14754. if (enoughVideoSamples) {
  14755. var audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0;
  14756. // if initSegment was generated without video samples, regenerate it again
  14757. if (!videoTrack.inputTimeScale) {
  14758. _utils_logger__WEBPACK_IMPORTED_MODULE_5__.logger.warn('[mp4-remuxer]: regenerate InitSegment as video detected');
  14759. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset);
  14760. }
  14761. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, audioTrackLength);
  14762. }
  14763. } else if (enoughVideoSamples) {
  14764. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, 0);
  14765. }
  14766. if (video) {
  14767. video.firstKeyFrame = firstKeyFrameIndex;
  14768. video.independent = firstKeyFrameIndex !== -1;
  14769. video.firstKeyFramePTS = firstKeyFramePTS;
  14770. }
  14771. }
  14772. }
  14773. // Allow ID3 and text to remux, even if more audio/video samples are required
  14774. if (this.ISGenerated) {
  14775. if (id3Track.samples.length) {
  14776. id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, this._initPTS, this._initDTS);
  14777. }
  14778. if (textTrack.samples.length) {
  14779. text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, this._initPTS);
  14780. }
  14781. }
  14782. return {
  14783. audio: audio,
  14784. video: video,
  14785. initSegment: initSegment,
  14786. independent: independent,
  14787. text: text,
  14788. id3: id3
  14789. };
  14790. };
  14791. _proto.generateIS = function generateIS(audioTrack, videoTrack, timeOffset) {
  14792. var audioSamples = audioTrack.samples;
  14793. var videoSamples = videoTrack.samples;
  14794. var typeSupported = this.typeSupported;
  14795. var tracks = {};
  14796. var computePTSDTS = !(0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(this._initPTS);
  14797. var container = 'audio/mp4';
  14798. var initPTS;
  14799. var initDTS;
  14800. var timescale;
  14801. if (computePTSDTS) {
  14802. initPTS = initDTS = Infinity;
  14803. }
  14804. if (audioTrack.config && audioSamples.length) {
  14805. // let's use audio sampling rate as MP4 time scale.
  14806. // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)
  14807. // using audio sampling rate here helps having an integer MP4 frame duration
  14808. // this avoids potential rounding issue and AV sync issue
  14809. audioTrack.timescale = audioTrack.samplerate;
  14810. switch (audioTrack.segmentCodec) {
  14811. case 'mp3':
  14812. if (typeSupported.mpeg) {
  14813. // Chrome and Safari
  14814. container = 'audio/mpeg';
  14815. audioTrack.codec = '';
  14816. } else if (typeSupported.mp3) {
  14817. // Firefox
  14818. audioTrack.codec = 'mp3';
  14819. }
  14820. break;
  14821. }
  14822. tracks.audio = {
  14823. id: 'audio',
  14824. container: container,
  14825. codec: audioTrack.codec,
  14826. initSegment: audioTrack.segmentCodec === 'mp3' && typeSupported.mpeg ? new Uint8Array(0) : _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].initSegment([audioTrack]),
  14827. metadata: {
  14828. channelCount: audioTrack.channelCount
  14829. }
  14830. };
  14831. if (computePTSDTS) {
  14832. timescale = audioTrack.inputTimeScale;
  14833. // remember first PTS of this demuxing context. for audio, PTS = DTS
  14834. initPTS = initDTS = audioSamples[0].pts - Math.round(timescale * timeOffset);
  14835. }
  14836. }
  14837. if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
  14838. // let's use input time scale as MP4 video timescale
  14839. // we use input time scale straight away to avoid rounding issues on frame duration / cts computation
  14840. videoTrack.timescale = videoTrack.inputTimeScale;
  14841. tracks.video = {
  14842. id: 'main',
  14843. container: 'video/mp4',
  14844. codec: videoTrack.codec,
  14845. initSegment: _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].initSegment([videoTrack]),
  14846. metadata: {
  14847. width: videoTrack.width,
  14848. height: videoTrack.height
  14849. }
  14850. };
  14851. if (computePTSDTS) {
  14852. timescale = videoTrack.inputTimeScale;
  14853. var startPTS = this.getVideoStartPts(videoSamples);
  14854. var startOffset = Math.round(timescale * timeOffset);
  14855. initDTS = Math.min(initDTS, normalizePts(videoSamples[0].dts, startPTS) - startOffset);
  14856. initPTS = Math.min(initPTS, startPTS - startOffset);
  14857. }
  14858. }
  14859. if (Object.keys(tracks).length) {
  14860. this.ISGenerated = true;
  14861. if (computePTSDTS) {
  14862. this._initPTS = initPTS;
  14863. this._initDTS = initDTS;
  14864. }
  14865. return {
  14866. tracks: tracks,
  14867. initPTS: initPTS,
  14868. timescale: timescale
  14869. };
  14870. }
  14871. };
  14872. _proto.remuxVideo = function remuxVideo(track, timeOffset, contiguous, audioTrackLength) {
  14873. var timeScale = track.inputTimeScale;
  14874. var inputSamples = track.samples;
  14875. var outputSamples = [];
  14876. var nbSamples = inputSamples.length;
  14877. var initPTS = this._initPTS;
  14878. var nextAvcDts = this.nextAvcDts;
  14879. var offset = 8;
  14880. var mp4SampleDuration = this.videoSampleDuration;
  14881. var firstDTS;
  14882. var lastDTS;
  14883. var minPTS = Number.POSITIVE_INFINITY;
  14884. var maxPTS = Number.NEGATIVE_INFINITY;
  14885. var sortSamples = false;
  14886. // if parsed fragment is contiguous with last one, let's use last DTS value as reference
  14887. if (!contiguous || nextAvcDts === null) {
  14888. var pts = timeOffset * timeScale;
  14889. var cts = inputSamples[0].pts - normalizePts(inputSamples[0].dts, inputSamples[0].pts);
  14890. // if not contiguous, let's use target timeOffset
  14891. nextAvcDts = pts - cts;
  14892. }
  14893. // PTS is coded on 33bits, and can loop from -2^32 to 2^32
  14894. // PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value
  14895. for (var i = 0; i < nbSamples; i++) {
  14896. var sample = inputSamples[i];
  14897. sample.pts = normalizePts(sample.pts - initPTS, nextAvcDts);
  14898. sample.dts = normalizePts(sample.dts - initPTS, nextAvcDts);
  14899. if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {
  14900. sortSamples = true;
  14901. }
  14902. }
  14903. // sort video samples by DTS then PTS then demux id order
  14904. if (sortSamples) {
  14905. inputSamples.sort(function (a, b) {
  14906. var deltadts = a.dts - b.dts;
  14907. var deltapts = a.pts - b.pts;
  14908. return deltadts || deltapts;
  14909. });
  14910. }
  14911. // Get first/last DTS
  14912. firstDTS = inputSamples[0].dts;
  14913. lastDTS = inputSamples[inputSamples.length - 1].dts;
  14914. // Sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS
  14915. // set this constant duration as being the avg delta between consecutive DTS.
  14916. var inputDuration = lastDTS - firstDTS;
  14917. var averageSampleDuration = inputDuration ? Math.round(inputDuration / (nbSamples - 1)) : mp4SampleDuration || track.inputTimeScale / 30;
  14918. // if fragment are contiguous, detect hole/overlapping between fragments
  14919. if (contiguous) {
  14920. // check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)
  14921. var delta = firstDTS - nextAvcDts;
  14922. var foundHole = delta > averageSampleDuration;
  14923. var foundOverlap = delta < -1;
  14924. if (foundHole || foundOverlap) {
  14925. if (foundHole) {
  14926. _utils_logger__WEBPACK_IMPORTED_MODULE_5__.logger.warn("AVC: " + (0,_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__.toMsFromMpegTsClock)(delta, true) + " ms (" + delta + "dts) hole between fragments detected, filling it");
  14927. } else {
  14928. _utils_logger__WEBPACK_IMPORTED_MODULE_5__.logger.warn("AVC: " + (0,_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__.toMsFromMpegTsClock)(-delta, true) + " ms (" + delta + "dts) overlapping between fragments detected");
  14929. }
  14930. if (!foundOverlap || nextAvcDts > inputSamples[0].pts) {
  14931. firstDTS = nextAvcDts;
  14932. var firstPTS = inputSamples[0].pts - delta;
  14933. inputSamples[0].dts = firstDTS;
  14934. inputSamples[0].pts = firstPTS;
  14935. _utils_logger__WEBPACK_IMPORTED_MODULE_5__.logger.log("Video: First PTS/DTS adjusted: " + (0,_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__.toMsFromMpegTsClock)(firstPTS, true) + "/" + (0,_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__.toMsFromMpegTsClock)(firstDTS, true) + ", delta: " + (0,_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__.toMsFromMpegTsClock)(delta, true) + " ms");
  14936. }
  14937. }
  14938. }
  14939. firstDTS = Math.max(0, firstDTS);
  14940. var nbNalu = 0;
  14941. var naluLen = 0;
  14942. for (var _i = 0; _i < nbSamples; _i++) {
  14943. // compute total/avc sample length and nb of NAL units
  14944. var _sample = inputSamples[_i];
  14945. var units = _sample.units;
  14946. var nbUnits = units.length;
  14947. var sampleLen = 0;
  14948. for (var j = 0; j < nbUnits; j++) {
  14949. sampleLen += units[j].data.length;
  14950. }
  14951. naluLen += sampleLen;
  14952. nbNalu += nbUnits;
  14953. _sample.length = sampleLen;
  14954. // ensure sample monotonic DTS
  14955. _sample.dts = Math.max(_sample.dts, firstDTS);
  14956. minPTS = Math.min(_sample.pts, minPTS);
  14957. maxPTS = Math.max(_sample.pts, maxPTS);
  14958. }
  14959. lastDTS = inputSamples[nbSamples - 1].dts;
  14960. /* concatenate the video data and construct the mdat in place
  14961. (need 8 more bytes to fill length and mpdat type) */
  14962. var mdatSize = naluLen + 4 * nbNalu + 8;
  14963. var mdat;
  14964. try {
  14965. mdat = new Uint8Array(mdatSize);
  14966. } catch (err) {
  14967. this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_3__.Events.ERROR, _events__WEBPACK_IMPORTED_MODULE_3__.Events.ERROR, {
  14968. type: _errors__WEBPACK_IMPORTED_MODULE_4__.ErrorTypes.MUX_ERROR,
  14969. details: _errors__WEBPACK_IMPORTED_MODULE_4__.ErrorDetails.REMUX_ALLOC_ERROR,
  14970. fatal: false,
  14971. bytes: mdatSize,
  14972. reason: "fail allocating video mdat " + mdatSize
  14973. });
  14974. return;
  14975. }
  14976. var view = new DataView(mdat.buffer);
  14977. view.setUint32(0, mdatSize);
  14978. mdat.set(_mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].types.mdat, 4);
  14979. var stretchedLastFrame = false;
  14980. var minDtsDelta = Number.POSITIVE_INFINITY;
  14981. var minPtsDelta = Number.POSITIVE_INFINITY;
  14982. var maxDtsDelta = Number.NEGATIVE_INFINITY;
  14983. var maxPtsDelta = Number.NEGATIVE_INFINITY;
  14984. for (var _i2 = 0; _i2 < nbSamples; _i2++) {
  14985. var avcSample = inputSamples[_i2];
  14986. var avcSampleUnits = avcSample.units;
  14987. var mp4SampleLength = 0;
  14988. // convert NALU bitstream to MP4 format (prepend NALU with size field)
  14989. for (var _j = 0, _nbUnits = avcSampleUnits.length; _j < _nbUnits; _j++) {
  14990. var unit = avcSampleUnits[_j];
  14991. var unitData = unit.data;
  14992. var unitDataLen = unit.data.byteLength;
  14993. view.setUint32(offset, unitDataLen);
  14994. offset += 4;
  14995. mdat.set(unitData, offset);
  14996. offset += unitDataLen;
  14997. mp4SampleLength += 4 + unitDataLen;
  14998. }
  14999. // expected sample duration is the Decoding Timestamp diff of consecutive samples
  15000. var ptsDelta = void 0;
  15001. if (_i2 < nbSamples - 1) {
  15002. mp4SampleDuration = inputSamples[_i2 + 1].dts - avcSample.dts;
  15003. ptsDelta = inputSamples[_i2 + 1].pts - avcSample.pts;
  15004. } else {
  15005. var config = this.config;
  15006. var lastFrameDuration = _i2 > 0 ? avcSample.dts - inputSamples[_i2 - 1].dts : averageSampleDuration;
  15007. ptsDelta = _i2 > 0 ? avcSample.pts - inputSamples[_i2 - 1].pts : averageSampleDuration;
  15008. if (config.stretchShortVideoTrack && this.nextAudioPts !== null) {
  15009. // In some cases, a segment's audio track duration may exceed the video track duration.
  15010. // Since we've already remuxed audio, and we know how long the audio track is, we look to
  15011. // see if the delta to the next segment is longer than maxBufferHole.
  15012. // If so, playback would potentially get stuck, so we artificially inflate
  15013. // the duration of the last frame to minimize any potential gap between segments.
  15014. var gapTolerance = Math.floor(config.maxBufferHole * timeScale);
  15015. var deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts;
  15016. if (deltaToFrameEnd > gapTolerance) {
  15017. // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video
  15018. // frame overlap. maxBufferHole should be >> lastFrameDuration anyway.
  15019. mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
  15020. if (mp4SampleDuration < 0) {
  15021. mp4SampleDuration = lastFrameDuration;
  15022. } else {
  15023. stretchedLastFrame = true;
  15024. }
  15025. _utils_logger__WEBPACK_IMPORTED_MODULE_5__.logger.log("[mp4-remuxer]: It is approximately " + deltaToFrameEnd / 90 + " ms to the next segment; using duration " + mp4SampleDuration / 90 + " ms for the last video frame.");
  15026. } else {
  15027. mp4SampleDuration = lastFrameDuration;
  15028. }
  15029. } else {
  15030. mp4SampleDuration = lastFrameDuration;
  15031. }
  15032. }
  15033. var compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts);
  15034. minDtsDelta = Math.min(minDtsDelta, mp4SampleDuration);
  15035. maxDtsDelta = Math.max(maxDtsDelta, mp4SampleDuration);
  15036. minPtsDelta = Math.min(minPtsDelta, ptsDelta);
  15037. maxPtsDelta = Math.max(maxPtsDelta, ptsDelta);
  15038. outputSamples.push(new Mp4Sample(avcSample.key, mp4SampleDuration, mp4SampleLength, compositionTimeOffset));
  15039. }
  15040. if (outputSamples.length) {
  15041. if (chromeVersion) {
  15042. if (chromeVersion < 70) {
  15043. // Chrome workaround, mark first sample as being a Random Access Point (keyframe) to avoid sourcebuffer append issue
  15044. // https://code.google.com/p/chromium/issues/detail?id=229412
  15045. var flags = outputSamples[0].flags;
  15046. flags.dependsOn = 2;
  15047. flags.isNonSync = 0;
  15048. }
  15049. } else if (safariWebkitVersion) {
  15050. // Fix for "CNN special report, with CC" in test-streams (Safari browser only)
  15051. // Ignore DTS when frame durations are irregular. Safari MSE does not handle this leading to gaps.
  15052. if (maxPtsDelta - minPtsDelta < maxDtsDelta - minDtsDelta && averageSampleDuration / maxDtsDelta < 0.025 && outputSamples[0].cts === 0) {
  15053. _utils_logger__WEBPACK_IMPORTED_MODULE_5__.logger.warn('Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.');
  15054. var dts = firstDTS;
  15055. for (var _i3 = 0, len = outputSamples.length; _i3 < len; _i3++) {
  15056. var nextDts = dts + outputSamples[_i3].duration;
  15057. var _pts = dts + outputSamples[_i3].cts;
  15058. if (_i3 < len - 1) {
  15059. var nextPts = nextDts + outputSamples[_i3 + 1].cts;
  15060. outputSamples[_i3].duration = nextPts - _pts;
  15061. } else {
  15062. outputSamples[_i3].duration = _i3 ? outputSamples[_i3 - 1].duration : averageSampleDuration;
  15063. }
  15064. outputSamples[_i3].cts = 0;
  15065. dts = nextDts;
  15066. }
  15067. }
  15068. }
  15069. }
  15070. console.assert(mp4SampleDuration !== null, 'mp4SampleDuration must be computed');
  15071. // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)
  15072. mp4SampleDuration = stretchedLastFrame || !mp4SampleDuration ? averageSampleDuration : mp4SampleDuration;
  15073. this.nextAvcDts = nextAvcDts = lastDTS + mp4SampleDuration;
  15074. this.videoSampleDuration = mp4SampleDuration;
  15075. this.isVideoContiguous = true;
  15076. var moof = _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].moof(track.sequenceNumber++, firstDTS, _extends({}, track, {
  15077. samples: outputSamples
  15078. }));
  15079. var type = 'video';
  15080. var data = {
  15081. data1: moof,
  15082. data2: mdat,
  15083. startPTS: minPTS / timeScale,
  15084. endPTS: (maxPTS + mp4SampleDuration) / timeScale,
  15085. startDTS: firstDTS / timeScale,
  15086. endDTS: nextAvcDts / timeScale,
  15087. type: type,
  15088. hasAudio: false,
  15089. hasVideo: true,
  15090. nb: outputSamples.length,
  15091. dropped: track.dropped
  15092. };
  15093. track.samples = [];
  15094. track.dropped = 0;
  15095. console.assert(mdat.length, 'MDAT length must not be zero');
  15096. return data;
  15097. };
  15098. _proto.remuxAudio = function remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, videoTimeOffset) {
  15099. var inputTimeScale = track.inputTimeScale;
  15100. var mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
  15101. var scaleFactor = inputTimeScale / mp4timeScale;
  15102. var mp4SampleDuration = track.segmentCodec === 'aac' ? AAC_SAMPLES_PER_FRAME : MPEG_AUDIO_SAMPLE_PER_FRAME;
  15103. var inputSampleDuration = mp4SampleDuration * scaleFactor;
  15104. var initPTS = this._initPTS;
  15105. var rawMPEG = track.segmentCodec === 'mp3' && this.typeSupported.mpeg;
  15106. var outputSamples = [];
  15107. var alignedWithVideo = videoTimeOffset !== undefined;
  15108. var inputSamples = track.samples;
  15109. var offset = rawMPEG ? 0 : 8;
  15110. var nextAudioPts = this.nextAudioPts || -1;
  15111. // window.audioSamples ? window.audioSamples.push(inputSamples.map(s => s.pts)) : (window.audioSamples = [inputSamples.map(s => s.pts)]);
  15112. // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),
  15113. // for sake of clarity:
  15114. // consecutive fragments are frags with
  15115. // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
  15116. // - less than 20 audio frames distance
  15117. // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
  15118. // this helps ensuring audio continuity
  15119. // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame
  15120. var timeOffsetMpegTS = timeOffset * inputTimeScale;
  15121. this.isAudioContiguous = contiguous = contiguous || inputSamples.length && nextAudioPts > 0 && (accurateTimeOffset && Math.abs(timeOffsetMpegTS - nextAudioPts) < 9000 || Math.abs(normalizePts(inputSamples[0].pts - initPTS, timeOffsetMpegTS) - nextAudioPts) < 20 * inputSampleDuration);
  15122. // compute normalized PTS
  15123. inputSamples.forEach(function (sample) {
  15124. sample.pts = normalizePts(sample.pts - initPTS, timeOffsetMpegTS);
  15125. });
  15126. if (!contiguous || nextAudioPts < 0) {
  15127. // filter out sample with negative PTS that are not playable anyway
  15128. // if we don't remove these negative samples, they will shift all audio samples forward.
  15129. // leading to audio overlap between current / next fragment
  15130. inputSamples = inputSamples.filter(function (sample) {
  15131. return sample.pts >= 0;
  15132. });
  15133. // in case all samples have negative PTS, and have been filtered out, return now
  15134. if (!inputSamples.length) {
  15135. return;
  15136. }
  15137. if (videoTimeOffset === 0) {
  15138. // Set the start to 0 to match video so that start gaps larger than inputSampleDuration are filled with silence
  15139. nextAudioPts = 0;
  15140. } else if (accurateTimeOffset && !alignedWithVideo) {
  15141. // When not seeking, not live, and LevelDetails.PTSKnown, use fragment start as predicted next audio PTS
  15142. nextAudioPts = Math.max(0, timeOffsetMpegTS);
  15143. } else {
  15144. // if frags are not contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS
  15145. nextAudioPts = inputSamples[0].pts;
  15146. }
  15147. }
  15148. // If the audio track is missing samples, the frames seem to get "left-shifted" within the
  15149. // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.
  15150. // In an effort to prevent this from happening, we inject frames here where there are gaps.
  15151. // When possible, we inject a silent frame; when that's not possible, we duplicate the last
  15152. // frame.
  15153. if (track.segmentCodec === 'aac') {
  15154. var maxAudioFramesDrift = this.config.maxAudioFramesDrift;
  15155. for (var i = 0, nextPts = nextAudioPts; i < inputSamples.length; i++) {
  15156. // First, let's see how far off this frame is from where we expect it to be
  15157. var sample = inputSamples[i];
  15158. var pts = sample.pts;
  15159. var delta = pts - nextPts;
  15160. var duration = Math.abs(1000 * delta / inputTimeScale);
  15161. // When remuxing with video, if we're overlapping by more than a duration, drop this sample to stay in sync
  15162. if (delta <= -maxAudioFramesDrift * inputSampleDuration && alignedWithVideo) {
  15163. if (i === 0) {
  15164. _utils_logger__WEBPACK_IMPORTED_MODULE_5__.logger.warn("Audio frame @ " + (pts / inputTimeScale).toFixed(3) + "s overlaps nextAudioPts by " + Math.round(1000 * delta / inputTimeScale) + " ms.");
  15165. this.nextAudioPts = nextAudioPts = nextPts = pts;
  15166. }
  15167. } // eslint-disable-line brace-style
  15168. // Insert missing frames if:
  15169. // 1: We're more than maxAudioFramesDrift frame away
  15170. // 2: Not more than MAX_SILENT_FRAME_DURATION away
  15171. // 3: currentTime (aka nextPtsNorm) is not 0
  15172. // 4: remuxing with video (videoTimeOffset !== undefined)
  15173. else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && alignedWithVideo) {
  15174. var missing = Math.round(delta / inputSampleDuration);
  15175. // Adjust nextPts so that silent samples are aligned with media pts. This will prevent media samples from
  15176. // later being shifted if nextPts is based on timeOffset and delta is not a multiple of inputSampleDuration.
  15177. nextPts = pts - missing * inputSampleDuration;
  15178. if (nextPts < 0) {
  15179. missing--;
  15180. nextPts += inputSampleDuration;
  15181. }
  15182. if (i === 0) {
  15183. this.nextAudioPts = nextAudioPts = nextPts;
  15184. }
  15185. _utils_logger__WEBPACK_IMPORTED_MODULE_5__.logger.warn("[mp4-remuxer]: Injecting " + missing + " audio frame @ " + (nextPts / inputTimeScale).toFixed(3) + "s due to " + Math.round(1000 * delta / inputTimeScale) + " ms gap.");
  15186. for (var j = 0; j < missing; j++) {
  15187. var newStamp = Math.max(nextPts, 0);
  15188. var fillFrame = _aac_helper__WEBPACK_IMPORTED_MODULE_1__["default"].getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  15189. if (!fillFrame) {
  15190. _utils_logger__WEBPACK_IMPORTED_MODULE_5__.logger.log('[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead.');
  15191. fillFrame = sample.unit.subarray();
  15192. }
  15193. inputSamples.splice(i, 0, {
  15194. unit: fillFrame,
  15195. pts: newStamp
  15196. });
  15197. nextPts += inputSampleDuration;
  15198. i++;
  15199. }
  15200. }
  15201. sample.pts = nextPts;
  15202. nextPts += inputSampleDuration;
  15203. }
  15204. }
  15205. var firstPTS = null;
  15206. var lastPTS = null;
  15207. var mdat;
  15208. var mdatSize = 0;
  15209. var sampleLength = inputSamples.length;
  15210. while (sampleLength--) {
  15211. mdatSize += inputSamples[sampleLength].unit.byteLength;
  15212. }
  15213. for (var _j2 = 0, _nbSamples = inputSamples.length; _j2 < _nbSamples; _j2++) {
  15214. var audioSample = inputSamples[_j2];
  15215. var unit = audioSample.unit;
  15216. var _pts2 = audioSample.pts;
  15217. if (lastPTS !== null) {
  15218. // If we have more than one sample, set the duration of the sample to the "real" duration; the PTS diff with
  15219. // the previous sample
  15220. var prevSample = outputSamples[_j2 - 1];
  15221. prevSample.duration = Math.round((_pts2 - lastPTS) / scaleFactor);
  15222. } else {
  15223. if (contiguous && track.segmentCodec === 'aac') {
  15224. // set PTS/DTS to expected PTS/DTS
  15225. _pts2 = nextAudioPts;
  15226. }
  15227. // remember first PTS of our audioSamples
  15228. firstPTS = _pts2;
  15229. if (mdatSize > 0) {
  15230. /* concatenate the audio data and construct the mdat in place
  15231. (need 8 more bytes to fill length and mdat type) */
  15232. mdatSize += offset;
  15233. try {
  15234. mdat = new Uint8Array(mdatSize);
  15235. } catch (err) {
  15236. this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_3__.Events.ERROR, _events__WEBPACK_IMPORTED_MODULE_3__.Events.ERROR, {
  15237. type: _errors__WEBPACK_IMPORTED_MODULE_4__.ErrorTypes.MUX_ERROR,
  15238. details: _errors__WEBPACK_IMPORTED_MODULE_4__.ErrorDetails.REMUX_ALLOC_ERROR,
  15239. fatal: false,
  15240. bytes: mdatSize,
  15241. reason: "fail allocating audio mdat " + mdatSize
  15242. });
  15243. return;
  15244. }
  15245. if (!rawMPEG) {
  15246. var view = new DataView(mdat.buffer);
  15247. view.setUint32(0, mdatSize);
  15248. mdat.set(_mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].types.mdat, 4);
  15249. }
  15250. } else {
  15251. // no audio samples
  15252. return;
  15253. }
  15254. }
  15255. mdat.set(unit, offset);
  15256. var unitLen = unit.byteLength;
  15257. offset += unitLen;
  15258. // Default the sample's duration to the computed mp4SampleDuration, which will either be 1024 for AAC or 1152 for MPEG
  15259. // In the case that we have 1 sample, this will be the duration. If we have more than one sample, the duration
  15260. // becomes the PTS diff with the previous sample
  15261. outputSamples.push(new Mp4Sample(true, mp4SampleDuration, unitLen, 0));
  15262. lastPTS = _pts2;
  15263. }
  15264. // We could end up with no audio samples if all input samples were overlapping with the previously remuxed ones
  15265. var nbSamples = outputSamples.length;
  15266. if (!nbSamples) {
  15267. return;
  15268. }
  15269. // The next audio sample PTS should be equal to last sample PTS + duration
  15270. var lastSample = outputSamples[outputSamples.length - 1];
  15271. this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSample.duration;
  15272. // Set the track samples from inputSamples to outputSamples before remuxing
  15273. var moof = rawMPEG ? new Uint8Array(0) : _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].moof(track.sequenceNumber++, firstPTS / scaleFactor, _extends({}, track, {
  15274. samples: outputSamples
  15275. }));
  15276. // Clear the track samples. This also clears the samples array in the demuxer, since the reference is shared
  15277. track.samples = [];
  15278. var start = firstPTS / inputTimeScale;
  15279. var end = nextAudioPts / inputTimeScale;
  15280. var type = 'audio';
  15281. var audioData = {
  15282. data1: moof,
  15283. data2: mdat,
  15284. startPTS: start,
  15285. endPTS: end,
  15286. startDTS: start,
  15287. endDTS: end,
  15288. type: type,
  15289. hasAudio: true,
  15290. hasVideo: false,
  15291. nb: nbSamples
  15292. };
  15293. this.isAudioContiguous = true;
  15294. console.assert(mdat.length, 'MDAT length must not be zero');
  15295. return audioData;
  15296. };
  15297. _proto.remuxEmptyAudio = function remuxEmptyAudio(track, timeOffset, contiguous, videoData) {
  15298. var inputTimeScale = track.inputTimeScale;
  15299. var mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
  15300. var scaleFactor = inputTimeScale / mp4timeScale;
  15301. var nextAudioPts = this.nextAudioPts;
  15302. // sync with video's timestamp
  15303. var startDTS = (nextAudioPts !== null ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS;
  15304. var endDTS = videoData.endDTS * inputTimeScale + this._initDTS;
  15305. // one sample's duration value
  15306. var frameDuration = scaleFactor * AAC_SAMPLES_PER_FRAME;
  15307. // samples count of this segment's duration
  15308. var nbSamples = Math.ceil((endDTS - startDTS) / frameDuration);
  15309. // silent frame
  15310. var silentFrame = _aac_helper__WEBPACK_IMPORTED_MODULE_1__["default"].getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  15311. _utils_logger__WEBPACK_IMPORTED_MODULE_5__.logger.warn('[mp4-remuxer]: remux empty Audio');
  15312. // Can't remux if we can't generate a silent frame...
  15313. if (!silentFrame) {
  15314. _utils_logger__WEBPACK_IMPORTED_MODULE_5__.logger.trace('[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec');
  15315. return;
  15316. }
  15317. var samples = [];
  15318. for (var i = 0; i < nbSamples; i++) {
  15319. var stamp = startDTS + i * frameDuration;
  15320. samples.push({
  15321. unit: silentFrame,
  15322. pts: stamp,
  15323. dts: stamp
  15324. });
  15325. }
  15326. track.samples = samples;
  15327. return this.remuxAudio(track, timeOffset, contiguous, false);
  15328. };
  15329. return MP4Remuxer;
  15330. }();
  15331. function normalizePts(value, reference) {
  15332. var offset;
  15333. if (reference === null) {
  15334. return value;
  15335. }
  15336. if (reference < value) {
  15337. // - 2^33
  15338. offset = -8589934592;
  15339. } else {
  15340. // + 2^33
  15341. offset = 8589934592;
  15342. }
  15343. /* PTS is 33bit (from 0 to 2^33 -1)
  15344. if diff between value and reference is bigger than half of the amplitude (2^32) then it means that
  15345. PTS looping occured. fill the gap */
  15346. while (Math.abs(value - reference) > 4294967296) {
  15347. value += offset;
  15348. }
  15349. return value;
  15350. }
  15351. function findKeyframeIndex(samples) {
  15352. for (var i = 0; i < samples.length; i++) {
  15353. if (samples[i].key) {
  15354. return i;
  15355. }
  15356. }
  15357. return -1;
  15358. }
  15359. function flushTextTrackMetadataCueSamples(track, timeOffset, initPTS, initDTS) {
  15360. var length = track.samples.length;
  15361. if (!length) {
  15362. return;
  15363. }
  15364. var inputTimeScale = track.inputTimeScale;
  15365. for (var index = 0; index < length; index++) {
  15366. var sample = track.samples[index];
  15367. // setting id3 pts, dts to relative time
  15368. // using this._initPTS and this._initDTS to calculate relative time
  15369. sample.pts = normalizePts(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale;
  15370. sample.dts = normalizePts(sample.dts - initDTS, timeOffset * inputTimeScale) / inputTimeScale;
  15371. }
  15372. var samples = track.samples;
  15373. track.samples = [];
  15374. return {
  15375. samples: samples
  15376. };
  15377. }
  15378. function flushTextTrackUserdataCueSamples(track, timeOffset, initPTS) {
  15379. var length = track.samples.length;
  15380. if (!length) {
  15381. return;
  15382. }
  15383. var inputTimeScale = track.inputTimeScale;
  15384. for (var index = 0; index < length; index++) {
  15385. var sample = track.samples[index];
  15386. // setting text pts, dts to relative time
  15387. // using this._initPTS and this._initDTS to calculate relative time
  15388. sample.pts = normalizePts(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale;
  15389. }
  15390. track.samples.sort(function (a, b) {
  15391. return a.pts - b.pts;
  15392. });
  15393. var samples = track.samples;
  15394. track.samples = [];
  15395. return {
  15396. samples: samples
  15397. };
  15398. }
  15399. var Mp4Sample = function Mp4Sample(isKeyframe, duration, size, cts) {
  15400. this.size = void 0;
  15401. this.duration = void 0;
  15402. this.cts = void 0;
  15403. this.flags = void 0;
  15404. this.duration = duration;
  15405. this.size = size;
  15406. this.cts = cts;
  15407. this.flags = new Mp4SampleFlags(isKeyframe);
  15408. };
  15409. var Mp4SampleFlags = function Mp4SampleFlags(isKeyframe) {
  15410. this.isLeading = 0;
  15411. this.isDependedOn = 0;
  15412. this.hasRedundancy = 0;
  15413. this.degradPrio = 0;
  15414. this.dependsOn = 1;
  15415. this.isNonSync = 1;
  15416. this.dependsOn = isKeyframe ? 2 : 1;
  15417. this.isNonSync = isKeyframe ? 0 : 1;
  15418. };
  15419. /***/ }),
  15420. /***/ "./src/remux/passthrough-remuxer.ts":
  15421. /*!******************************************!*\
  15422. !*** ./src/remux/passthrough-remuxer.ts ***!
  15423. \******************************************/
  15424. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  15425. "use strict";
  15426. __webpack_require__.r(__webpack_exports__);
  15427. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  15428. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  15429. /* harmony export */ });
  15430. /* harmony import */ var _Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
  15431. /* harmony import */ var _mp4_remuxer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./mp4-remuxer */ "./src/remux/mp4-remuxer.ts");
  15432. /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
  15433. /* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
  15434. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
  15435. var PassThroughRemuxer = /*#__PURE__*/function () {
  15436. function PassThroughRemuxer() {
  15437. this.emitInitSegment = false;
  15438. this.audioCodec = void 0;
  15439. this.videoCodec = void 0;
  15440. this.initData = void 0;
  15441. this.initPTS = void 0;
  15442. this.initTracks = void 0;
  15443. this.lastEndTime = null;
  15444. }
  15445. var _proto = PassThroughRemuxer.prototype;
  15446. _proto.destroy = function destroy() {};
  15447. _proto.resetTimeStamp = function resetTimeStamp(defaultInitPTS) {
  15448. this.initPTS = defaultInitPTS;
  15449. this.lastEndTime = null;
  15450. };
  15451. _proto.resetNextTimestamp = function resetNextTimestamp() {
  15452. this.lastEndTime = null;
  15453. };
  15454. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec) {
  15455. this.audioCodec = audioCodec;
  15456. this.videoCodec = videoCodec;
  15457. this.generateInitSegment(initSegment);
  15458. this.emitInitSegment = true;
  15459. };
  15460. _proto.generateInitSegment = function generateInitSegment(initSegment) {
  15461. var audioCodec = this.audioCodec,
  15462. videoCodec = this.videoCodec;
  15463. if (!initSegment || !initSegment.byteLength) {
  15464. this.initTracks = undefined;
  15465. this.initData = undefined;
  15466. return;
  15467. }
  15468. var initData = this.initData = (0,_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_2__.parseInitSegment)(initSegment);
  15469. // Get codec from initSegment or fallback to default
  15470. if (!audioCodec) {
  15471. audioCodec = getParsedTrackCodec(initData.audio, _loader_fragment__WEBPACK_IMPORTED_MODULE_3__.ElementaryStreamTypes.AUDIO);
  15472. }
  15473. if (!videoCodec) {
  15474. videoCodec = getParsedTrackCodec(initData.video, _loader_fragment__WEBPACK_IMPORTED_MODULE_3__.ElementaryStreamTypes.VIDEO);
  15475. }
  15476. var tracks = {};
  15477. if (initData.audio && initData.video) {
  15478. tracks.audiovideo = {
  15479. container: 'video/mp4',
  15480. codec: audioCodec + ',' + videoCodec,
  15481. initSegment: initSegment,
  15482. id: 'main'
  15483. };
  15484. } else if (initData.audio) {
  15485. tracks.audio = {
  15486. container: 'audio/mp4',
  15487. codec: audioCodec,
  15488. initSegment: initSegment,
  15489. id: 'audio'
  15490. };
  15491. } else if (initData.video) {
  15492. tracks.video = {
  15493. container: 'video/mp4',
  15494. codec: videoCodec,
  15495. initSegment: initSegment,
  15496. id: 'main'
  15497. };
  15498. } else {
  15499. _utils_logger__WEBPACK_IMPORTED_MODULE_4__.logger.warn('[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes.');
  15500. }
  15501. this.initTracks = tracks;
  15502. };
  15503. _proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset) {
  15504. var _this$initPTS;
  15505. var initPTS = this.initPTS,
  15506. lastEndTime = this.lastEndTime;
  15507. var result = {
  15508. audio: undefined,
  15509. video: undefined,
  15510. text: textTrack,
  15511. id3: id3Track,
  15512. initSegment: undefined
  15513. };
  15514. // If we haven't yet set a lastEndDTS, or it was reset, set it to the provided timeOffset. We want to use the
  15515. // lastEndDTS over timeOffset whenever possible; during progressive playback, the media source will not update
  15516. // the media duration (which is what timeOffset is provided as) before we need to process the next chunk.
  15517. if (!(0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(lastEndTime)) {
  15518. lastEndTime = this.lastEndTime = timeOffset || 0;
  15519. }
  15520. // The binary segment data is added to the videoTrack in the mp4demuxer. We don't check to see if the data is only
  15521. // audio or video (or both); adding it to video was an arbitrary choice.
  15522. var data = videoTrack.samples;
  15523. if (!data || !data.length) {
  15524. return result;
  15525. }
  15526. var initSegment = {
  15527. initPTS: undefined,
  15528. timescale: 1
  15529. };
  15530. var initData = this.initData;
  15531. if (!initData || !initData.length) {
  15532. this.generateInitSegment(data);
  15533. initData = this.initData;
  15534. }
  15535. if (!initData || !initData.length) {
  15536. // We can't remux if the initSegment could not be generated
  15537. _utils_logger__WEBPACK_IMPORTED_MODULE_4__.logger.warn('[passthrough-remuxer.ts]: Failed to generate initSegment.');
  15538. return result;
  15539. }
  15540. if (this.emitInitSegment) {
  15541. initSegment.tracks = this.initTracks;
  15542. this.emitInitSegment = false;
  15543. }
  15544. var startDTS = (0,_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_2__.getStartDTS)(initData, data);
  15545. if (!(0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(initPTS)) {
  15546. this.initPTS = initSegment.initPTS = initPTS = startDTS - timeOffset;
  15547. }
  15548. var duration = (0,_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_2__.getDuration)(data, initData);
  15549. var startTime = audioTrack ? startDTS - initPTS : lastEndTime;
  15550. var endTime = startTime + duration;
  15551. (0,_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_2__.offsetStartDTS)(initData, data, initPTS);
  15552. if (duration > 0) {
  15553. this.lastEndTime = endTime;
  15554. } else {
  15555. _utils_logger__WEBPACK_IMPORTED_MODULE_4__.logger.warn('Duration parsed from mp4 should be greater than zero');
  15556. this.resetNextTimestamp();
  15557. }
  15558. var hasAudio = !!initData.audio;
  15559. var hasVideo = !!initData.video;
  15560. var type = '';
  15561. if (hasAudio) {
  15562. type += 'audio';
  15563. }
  15564. if (hasVideo) {
  15565. type += 'video';
  15566. }
  15567. var track = {
  15568. data1: data,
  15569. startPTS: startTime,
  15570. startDTS: startTime,
  15571. endPTS: endTime,
  15572. endDTS: endTime,
  15573. type: type,
  15574. hasAudio: hasAudio,
  15575. hasVideo: hasVideo,
  15576. nb: 1,
  15577. dropped: 0
  15578. };
  15579. result.audio = track.type === 'audio' ? track : undefined;
  15580. result.video = track.type !== 'audio' ? track : undefined;
  15581. result.initSegment = initSegment;
  15582. var initPtsNum = (_this$initPTS = this.initPTS) != null ? _this$initPTS : 0;
  15583. result.id3 = (0,_mp4_remuxer__WEBPACK_IMPORTED_MODULE_1__.flushTextTrackMetadataCueSamples)(id3Track, timeOffset, initPtsNum, initPtsNum);
  15584. if (textTrack.samples.length) {
  15585. result.text = (0,_mp4_remuxer__WEBPACK_IMPORTED_MODULE_1__.flushTextTrackUserdataCueSamples)(textTrack, timeOffset, initPtsNum);
  15586. }
  15587. return result;
  15588. };
  15589. return PassThroughRemuxer;
  15590. }();
  15591. function getParsedTrackCodec(track, type) {
  15592. var parsedCodec = track === null || track === void 0 ? void 0 : track.codec;
  15593. if (parsedCodec && parsedCodec.length > 4) {
  15594. return parsedCodec;
  15595. }
  15596. // Since mp4-tools cannot parse full codec string (see 'TODO: Parse codec details'... in mp4-tools)
  15597. // Provide defaults based on codec type
  15598. // This allows for some playback of some fmp4 playlists without CODECS defined in manifest
  15599. if (parsedCodec === 'hvc1' || parsedCodec === 'hev1') {
  15600. return 'hvc1.1.c.L120.90';
  15601. }
  15602. if (parsedCodec === 'av01') {
  15603. return 'av01.0.04M.08';
  15604. }
  15605. if (parsedCodec === 'avc1' || type === _loader_fragment__WEBPACK_IMPORTED_MODULE_3__.ElementaryStreamTypes.VIDEO) {
  15606. return 'avc1.42e01e';
  15607. }
  15608. return 'mp4a.40.5';
  15609. }
  15610. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (PassThroughRemuxer);
  15611. /***/ }),
  15612. /***/ "./src/task-loop.ts":
  15613. /*!**************************!*\
  15614. !*** ./src/task-loop.ts ***!
  15615. \**************************/
  15616. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  15617. "use strict";
  15618. __webpack_require__.r(__webpack_exports__);
  15619. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  15620. /* harmony export */ "default": () => (/* binding */ TaskLoop)
  15621. /* harmony export */ });
  15622. /**
  15623. * Sub-class specialization of EventHandler base class.
  15624. *
  15625. * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,
  15626. * scheduled asynchroneously, avoiding recursive calls in the same tick.
  15627. *
  15628. * The task itself is implemented in `doTick`. It can be requested and called for single execution
  15629. * using the `tick` method.
  15630. *
  15631. * It will be assured that the task execution method (`tick`) only gets called once per main loop "tick",
  15632. * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.
  15633. *
  15634. * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,
  15635. * and cancelled with `clearNextTick`.
  15636. *
  15637. * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).
  15638. *
  15639. * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.
  15640. *
  15641. * Further explanations:
  15642. *
  15643. * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously
  15644. * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.
  15645. *
  15646. * When the task execution (`tick` method) is called in re-entrant way this is detected and
  15647. * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further
  15648. * task processing on the next main loop iteration (also known as "next tick" in the Node/JS runtime lingo).
  15649. */
  15650. var TaskLoop = /*#__PURE__*/function () {
  15651. function TaskLoop() {
  15652. this._boundTick = void 0;
  15653. this._tickTimer = null;
  15654. this._tickInterval = null;
  15655. this._tickCallCount = 0;
  15656. this._boundTick = this.tick.bind(this);
  15657. }
  15658. var _proto = TaskLoop.prototype;
  15659. _proto.destroy = function destroy() {
  15660. this.onHandlerDestroying();
  15661. this.onHandlerDestroyed();
  15662. };
  15663. _proto.onHandlerDestroying = function onHandlerDestroying() {
  15664. // clear all timers before unregistering from event bus
  15665. this.clearNextTick();
  15666. this.clearInterval();
  15667. };
  15668. _proto.onHandlerDestroyed = function onHandlerDestroyed() {}
  15669. /**
  15670. * @returns {boolean}
  15671. */;
  15672. _proto.hasInterval = function hasInterval() {
  15673. return !!this._tickInterval;
  15674. }
  15675. /**
  15676. * @returns {boolean}
  15677. */;
  15678. _proto.hasNextTick = function hasNextTick() {
  15679. return !!this._tickTimer;
  15680. }
  15681. /**
  15682. * @param {number} millis Interval time (ms)
  15683. * @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect)
  15684. */;
  15685. _proto.setInterval = function setInterval(millis) {
  15686. if (!this._tickInterval) {
  15687. this._tickInterval = self.setInterval(this._boundTick, millis);
  15688. return true;
  15689. }
  15690. return false;
  15691. }
  15692. /**
  15693. * @returns {boolean} True when interval was cleared, false when none was set (no effect)
  15694. */;
  15695. _proto.clearInterval = function clearInterval() {
  15696. if (this._tickInterval) {
  15697. self.clearInterval(this._tickInterval);
  15698. this._tickInterval = null;
  15699. return true;
  15700. }
  15701. return false;
  15702. }
  15703. /**
  15704. * @returns {boolean} True when timeout was cleared, false when none was set (no effect)
  15705. */;
  15706. _proto.clearNextTick = function clearNextTick() {
  15707. if (this._tickTimer) {
  15708. self.clearTimeout(this._tickTimer);
  15709. this._tickTimer = null;
  15710. return true;
  15711. }
  15712. return false;
  15713. }
  15714. /**
  15715. * Will call the subclass doTick implementation in this main loop tick
  15716. * or in the next one (via setTimeout(,0)) in case it has already been called
  15717. * in this tick (in case this is a re-entrant call).
  15718. */;
  15719. _proto.tick = function tick() {
  15720. this._tickCallCount++;
  15721. if (this._tickCallCount === 1) {
  15722. this.doTick();
  15723. // re-entrant call to tick from previous doTick call stack
  15724. // -> schedule a call on the next main loop iteration to process this task processing request
  15725. if (this._tickCallCount > 1) {
  15726. // make sure only one timer exists at any time at max
  15727. this.tickImmediate();
  15728. }
  15729. this._tickCallCount = 0;
  15730. }
  15731. };
  15732. _proto.tickImmediate = function tickImmediate() {
  15733. this.clearNextTick();
  15734. this._tickTimer = self.setTimeout(this._boundTick, 0);
  15735. }
  15736. /**
  15737. * For subclass to implement task logic
  15738. * @abstract
  15739. */;
  15740. _proto.doTick = function doTick() {};
  15741. return TaskLoop;
  15742. }();
  15743. /***/ }),
  15744. /***/ "./src/types/demuxer.ts":
  15745. /*!******************************!*\
  15746. !*** ./src/types/demuxer.ts ***!
  15747. \******************************/
  15748. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  15749. "use strict";
  15750. __webpack_require__.r(__webpack_exports__);
  15751. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  15752. /* harmony export */ "MetadataSchema": () => (/* binding */ MetadataSchema)
  15753. /* harmony export */ });
  15754. var MetadataSchema;
  15755. (function (MetadataSchema) {
  15756. MetadataSchema["audioId3"] = "org.id3";
  15757. MetadataSchema["dateRange"] = "com.apple.quicktime.HLS";
  15758. MetadataSchema["emsg"] = "https://aomedia.org/emsg/ID3";
  15759. })(MetadataSchema || (MetadataSchema = {}));
  15760. /***/ }),
  15761. /***/ "./src/types/level.ts":
  15762. /*!****************************!*\
  15763. !*** ./src/types/level.ts ***!
  15764. \****************************/
  15765. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  15766. "use strict";
  15767. __webpack_require__.r(__webpack_exports__);
  15768. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  15769. /* harmony export */ "HlsSkip": () => (/* binding */ HlsSkip),
  15770. /* harmony export */ "HlsUrlParameters": () => (/* binding */ HlsUrlParameters),
  15771. /* harmony export */ "Level": () => (/* binding */ Level),
  15772. /* harmony export */ "getSkipValue": () => (/* binding */ getSkipValue)
  15773. /* harmony export */ });
  15774. 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, _toPropertyKey(descriptor.key), descriptor); } }
  15775. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  15776. function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
  15777. function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
  15778. var HlsSkip;
  15779. (function (HlsSkip) {
  15780. HlsSkip["No"] = "";
  15781. HlsSkip["Yes"] = "YES";
  15782. HlsSkip["v2"] = "v2";
  15783. })(HlsSkip || (HlsSkip = {}));
  15784. function getSkipValue(details, msn) {
  15785. var canSkipUntil = details.canSkipUntil,
  15786. canSkipDateRanges = details.canSkipDateRanges,
  15787. endSN = details.endSN;
  15788. var snChangeGoal = msn !== undefined ? msn - endSN : 0;
  15789. if (canSkipUntil && snChangeGoal < canSkipUntil) {
  15790. if (canSkipDateRanges) {
  15791. return HlsSkip.v2;
  15792. }
  15793. return HlsSkip.Yes;
  15794. }
  15795. return HlsSkip.No;
  15796. }
  15797. var HlsUrlParameters = /*#__PURE__*/function () {
  15798. function HlsUrlParameters(msn, part, skip) {
  15799. this.msn = void 0;
  15800. this.part = void 0;
  15801. this.skip = void 0;
  15802. this.msn = msn;
  15803. this.part = part;
  15804. this.skip = skip;
  15805. }
  15806. var _proto = HlsUrlParameters.prototype;
  15807. _proto.addDirectives = function addDirectives(uri) {
  15808. var url = new self.URL(uri);
  15809. if (this.msn !== undefined) {
  15810. url.searchParams.set('_HLS_msn', this.msn.toString());
  15811. }
  15812. if (this.part !== undefined) {
  15813. url.searchParams.set('_HLS_part', this.part.toString());
  15814. }
  15815. if (this.skip) {
  15816. url.searchParams.set('_HLS_skip', this.skip);
  15817. }
  15818. return url.toString();
  15819. };
  15820. return HlsUrlParameters;
  15821. }();
  15822. var Level = /*#__PURE__*/function () {
  15823. function Level(data) {
  15824. this.attrs = void 0;
  15825. this.audioCodec = void 0;
  15826. this.bitrate = void 0;
  15827. this.codecSet = void 0;
  15828. this.height = void 0;
  15829. this.id = void 0;
  15830. this.name = void 0;
  15831. this.videoCodec = void 0;
  15832. this.width = void 0;
  15833. this.unknownCodecs = void 0;
  15834. this.audioGroupIds = void 0;
  15835. this.details = void 0;
  15836. this.fragmentError = 0;
  15837. this.loadError = 0;
  15838. this.loaded = void 0;
  15839. this.realBitrate = 0;
  15840. this.textGroupIds = void 0;
  15841. this.url = void 0;
  15842. this._urlId = 0;
  15843. this.url = [data.url];
  15844. this.attrs = data.attrs;
  15845. this.bitrate = data.bitrate;
  15846. if (data.details) {
  15847. this.details = data.details;
  15848. }
  15849. this.id = data.id || 0;
  15850. this.name = data.name;
  15851. this.width = data.width || 0;
  15852. this.height = data.height || 0;
  15853. this.audioCodec = data.audioCodec;
  15854. this.videoCodec = data.videoCodec;
  15855. this.unknownCodecs = data.unknownCodecs;
  15856. this.codecSet = [data.videoCodec, data.audioCodec].filter(function (c) {
  15857. return c;
  15858. }).join(',').replace(/\.[^.,]+/g, '');
  15859. }
  15860. _createClass(Level, [{
  15861. key: "maxBitrate",
  15862. get: function get() {
  15863. return Math.max(this.realBitrate, this.bitrate);
  15864. }
  15865. }, {
  15866. key: "uri",
  15867. get: function get() {
  15868. return this.url[this._urlId] || '';
  15869. }
  15870. }, {
  15871. key: "urlId",
  15872. get: function get() {
  15873. return this._urlId;
  15874. },
  15875. set: function set(value) {
  15876. var newValue = value % this.url.length;
  15877. if (this._urlId !== newValue) {
  15878. this.details = undefined;
  15879. this._urlId = newValue;
  15880. }
  15881. }
  15882. }]);
  15883. return Level;
  15884. }();
  15885. /***/ }),
  15886. /***/ "./src/types/loader.ts":
  15887. /*!*****************************!*\
  15888. !*** ./src/types/loader.ts ***!
  15889. \*****************************/
  15890. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  15891. "use strict";
  15892. __webpack_require__.r(__webpack_exports__);
  15893. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  15894. /* harmony export */ "PlaylistContextType": () => (/* binding */ PlaylistContextType),
  15895. /* harmony export */ "PlaylistLevelType": () => (/* binding */ PlaylistLevelType)
  15896. /* harmony export */ });
  15897. var PlaylistContextType;
  15898. (function (PlaylistContextType) {
  15899. PlaylistContextType["MANIFEST"] = "manifest";
  15900. PlaylistContextType["LEVEL"] = "level";
  15901. PlaylistContextType["AUDIO_TRACK"] = "audioTrack";
  15902. PlaylistContextType["SUBTITLE_TRACK"] = "subtitleTrack";
  15903. })(PlaylistContextType || (PlaylistContextType = {}));
  15904. var PlaylistLevelType;
  15905. (function (PlaylistLevelType) {
  15906. PlaylistLevelType["MAIN"] = "main";
  15907. PlaylistLevelType["AUDIO"] = "audio";
  15908. PlaylistLevelType["SUBTITLE"] = "subtitle";
  15909. })(PlaylistLevelType || (PlaylistLevelType = {}));
  15910. /***/ }),
  15911. /***/ "./src/types/transmuxer.ts":
  15912. /*!*********************************!*\
  15913. !*** ./src/types/transmuxer.ts ***!
  15914. \*********************************/
  15915. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  15916. "use strict";
  15917. __webpack_require__.r(__webpack_exports__);
  15918. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  15919. /* harmony export */ "ChunkMetadata": () => (/* binding */ ChunkMetadata)
  15920. /* harmony export */ });
  15921. var ChunkMetadata = function ChunkMetadata(level, sn, id, size, part, partial) {
  15922. if (size === void 0) {
  15923. size = 0;
  15924. }
  15925. if (part === void 0) {
  15926. part = -1;
  15927. }
  15928. if (partial === void 0) {
  15929. partial = false;
  15930. }
  15931. this.level = void 0;
  15932. this.sn = void 0;
  15933. this.part = void 0;
  15934. this.id = void 0;
  15935. this.size = void 0;
  15936. this.partial = void 0;
  15937. this.transmuxing = getNewPerformanceTiming();
  15938. this.buffering = {
  15939. audio: getNewPerformanceTiming(),
  15940. video: getNewPerformanceTiming(),
  15941. audiovideo: getNewPerformanceTiming()
  15942. };
  15943. this.level = level;
  15944. this.sn = sn;
  15945. this.id = id;
  15946. this.size = size;
  15947. this.part = part;
  15948. this.partial = partial;
  15949. };
  15950. function getNewPerformanceTiming() {
  15951. return {
  15952. start: 0,
  15953. executeStart: 0,
  15954. executeEnd: 0,
  15955. end: 0
  15956. };
  15957. }
  15958. /***/ }),
  15959. /***/ "./src/utils/attr-list.ts":
  15960. /*!********************************!*\
  15961. !*** ./src/utils/attr-list.ts ***!
  15962. \********************************/
  15963. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  15964. "use strict";
  15965. __webpack_require__.r(__webpack_exports__);
  15966. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  15967. /* harmony export */ "AttrList": () => (/* binding */ AttrList)
  15968. /* harmony export */ });
  15969. var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/; // eslint-disable-line no-useless-escape
  15970. var ATTR_LIST_REGEX = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape
  15971. // adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
  15972. var AttrList = /*#__PURE__*/function () {
  15973. function AttrList(attrs) {
  15974. if (typeof attrs === 'string') {
  15975. attrs = AttrList.parseAttrList(attrs);
  15976. }
  15977. for (var attr in attrs) {
  15978. if (attrs.hasOwnProperty(attr)) {
  15979. this[attr] = attrs[attr];
  15980. }
  15981. }
  15982. }
  15983. var _proto = AttrList.prototype;
  15984. _proto.decimalInteger = function decimalInteger(attrName) {
  15985. var intValue = parseInt(this[attrName], 10);
  15986. if (intValue > Number.MAX_SAFE_INTEGER) {
  15987. return Infinity;
  15988. }
  15989. return intValue;
  15990. };
  15991. _proto.hexadecimalInteger = function hexadecimalInteger(attrName) {
  15992. if (this[attrName]) {
  15993. var stringValue = (this[attrName] || '0x').slice(2);
  15994. stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;
  15995. var value = new Uint8Array(stringValue.length / 2);
  15996. for (var i = 0; i < stringValue.length / 2; i++) {
  15997. value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
  15998. }
  15999. return value;
  16000. } else {
  16001. return null;
  16002. }
  16003. };
  16004. _proto.hexadecimalIntegerAsNumber = function hexadecimalIntegerAsNumber(attrName) {
  16005. var intValue = parseInt(this[attrName], 16);
  16006. if (intValue > Number.MAX_SAFE_INTEGER) {
  16007. return Infinity;
  16008. }
  16009. return intValue;
  16010. };
  16011. _proto.decimalFloatingPoint = function decimalFloatingPoint(attrName) {
  16012. return parseFloat(this[attrName]);
  16013. };
  16014. _proto.optionalFloat = function optionalFloat(attrName, defaultValue) {
  16015. var value = this[attrName];
  16016. return value ? parseFloat(value) : defaultValue;
  16017. };
  16018. _proto.enumeratedString = function enumeratedString(attrName) {
  16019. return this[attrName];
  16020. };
  16021. _proto.bool = function bool(attrName) {
  16022. return this[attrName] === 'YES';
  16023. };
  16024. _proto.decimalResolution = function decimalResolution(attrName) {
  16025. var res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
  16026. if (res === null) {
  16027. return undefined;
  16028. }
  16029. return {
  16030. width: parseInt(res[1], 10),
  16031. height: parseInt(res[2], 10)
  16032. };
  16033. };
  16034. AttrList.parseAttrList = function parseAttrList(input) {
  16035. var match;
  16036. var attrs = {};
  16037. var quote = '"';
  16038. ATTR_LIST_REGEX.lastIndex = 0;
  16039. while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
  16040. var value = match[2];
  16041. if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) {
  16042. value = value.slice(1, -1);
  16043. }
  16044. attrs[match[1]] = value;
  16045. }
  16046. return attrs;
  16047. };
  16048. return AttrList;
  16049. }();
  16050. /***/ }),
  16051. /***/ "./src/utils/binary-search.ts":
  16052. /*!************************************!*\
  16053. !*** ./src/utils/binary-search.ts ***!
  16054. \************************************/
  16055. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  16056. "use strict";
  16057. __webpack_require__.r(__webpack_exports__);
  16058. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  16059. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  16060. /* harmony export */ });
  16061. var BinarySearch = {
  16062. /**
  16063. * Searches for an item in an array which matches a certain condition.
  16064. * This requires the condition to only match one item in the array,
  16065. * and for the array to be ordered.
  16066. *
  16067. * @param {Array<T>} list The array to search.
  16068. * @param {BinarySearchComparison<T>} comparisonFn
  16069. * Called and provided a candidate item as the first argument.
  16070. * Should return:
  16071. * > -1 if the item should be located at a lower index than the provided item.
  16072. * > 1 if the item should be located at a higher index than the provided item.
  16073. * > 0 if the item is the item you're looking for.
  16074. *
  16075. * @return {T | null} The object if it is found or null otherwise.
  16076. */
  16077. search: function search(list, comparisonFn) {
  16078. var minIndex = 0;
  16079. var maxIndex = list.length - 1;
  16080. var currentIndex = null;
  16081. var currentElement = null;
  16082. while (minIndex <= maxIndex) {
  16083. currentIndex = (minIndex + maxIndex) / 2 | 0;
  16084. currentElement = list[currentIndex];
  16085. var comparisonResult = comparisonFn(currentElement);
  16086. if (comparisonResult > 0) {
  16087. minIndex = currentIndex + 1;
  16088. } else if (comparisonResult < 0) {
  16089. maxIndex = currentIndex - 1;
  16090. } else {
  16091. return currentElement;
  16092. }
  16093. }
  16094. return null;
  16095. }
  16096. };
  16097. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (BinarySearch);
  16098. /***/ }),
  16099. /***/ "./src/utils/buffer-helper.ts":
  16100. /*!************************************!*\
  16101. !*** ./src/utils/buffer-helper.ts ***!
  16102. \************************************/
  16103. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  16104. "use strict";
  16105. __webpack_require__.r(__webpack_exports__);
  16106. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  16107. /* harmony export */ "BufferHelper": () => (/* binding */ BufferHelper)
  16108. /* harmony export */ });
  16109. /* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./logger */ "./src/utils/logger.ts");
  16110. /**
  16111. * @module BufferHelper
  16112. *
  16113. * Providing methods dealing with buffer length retrieval for example.
  16114. *
  16115. * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.
  16116. *
  16117. * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered
  16118. */
  16119. var noopBuffered = {
  16120. length: 0,
  16121. start: function start() {
  16122. return 0;
  16123. },
  16124. end: function end() {
  16125. return 0;
  16126. }
  16127. };
  16128. var BufferHelper = /*#__PURE__*/function () {
  16129. function BufferHelper() {}
  16130. /**
  16131. * Return true if `media`'s buffered include `position`
  16132. * @param {Bufferable} media
  16133. * @param {number} position
  16134. * @returns {boolean}
  16135. */
  16136. BufferHelper.isBuffered = function isBuffered(media, position) {
  16137. try {
  16138. if (media) {
  16139. var buffered = BufferHelper.getBuffered(media);
  16140. for (var i = 0; i < buffered.length; i++) {
  16141. if (position >= buffered.start(i) && position <= buffered.end(i)) {
  16142. return true;
  16143. }
  16144. }
  16145. }
  16146. } catch (error) {
  16147. // this is to catch
  16148. // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
  16149. // This SourceBuffer has been removed from the parent media source
  16150. }
  16151. return false;
  16152. };
  16153. BufferHelper.bufferInfo = function bufferInfo(media, pos, maxHoleDuration) {
  16154. try {
  16155. if (media) {
  16156. var vbuffered = BufferHelper.getBuffered(media);
  16157. var buffered = [];
  16158. var i;
  16159. for (i = 0; i < vbuffered.length; i++) {
  16160. buffered.push({
  16161. start: vbuffered.start(i),
  16162. end: vbuffered.end(i)
  16163. });
  16164. }
  16165. return this.bufferedInfo(buffered, pos, maxHoleDuration);
  16166. }
  16167. } catch (error) {
  16168. // this is to catch
  16169. // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
  16170. // This SourceBuffer has been removed from the parent media source
  16171. }
  16172. return {
  16173. len: 0,
  16174. start: pos,
  16175. end: pos,
  16176. nextStart: undefined
  16177. };
  16178. };
  16179. BufferHelper.bufferedInfo = function bufferedInfo(buffered, pos, maxHoleDuration) {
  16180. pos = Math.max(0, pos);
  16181. // sort on buffer.start/smaller end (IE does not always return sorted buffered range)
  16182. buffered.sort(function (a, b) {
  16183. var diff = a.start - b.start;
  16184. if (diff) {
  16185. return diff;
  16186. } else {
  16187. return b.end - a.end;
  16188. }
  16189. });
  16190. var buffered2 = [];
  16191. if (maxHoleDuration) {
  16192. // there might be some small holes between buffer time range
  16193. // consider that holes smaller than maxHoleDuration are irrelevant and build another
  16194. // buffer time range representations that discards those holes
  16195. for (var i = 0; i < buffered.length; i++) {
  16196. var buf2len = buffered2.length;
  16197. if (buf2len) {
  16198. var buf2end = buffered2[buf2len - 1].end;
  16199. // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)
  16200. if (buffered[i].start - buf2end < maxHoleDuration) {
  16201. // merge overlapping time ranges
  16202. // update lastRange.end only if smaller than item.end
  16203. // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)
  16204. // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])
  16205. if (buffered[i].end > buf2end) {
  16206. buffered2[buf2len - 1].end = buffered[i].end;
  16207. }
  16208. } else {
  16209. // big hole
  16210. buffered2.push(buffered[i]);
  16211. }
  16212. } else {
  16213. // first value
  16214. buffered2.push(buffered[i]);
  16215. }
  16216. }
  16217. } else {
  16218. buffered2 = buffered;
  16219. }
  16220. var bufferLen = 0;
  16221. // bufferStartNext can possibly be undefined based on the conditional logic below
  16222. var bufferStartNext;
  16223. // bufferStart and bufferEnd are buffer boundaries around current video position
  16224. var bufferStart = pos;
  16225. var bufferEnd = pos;
  16226. for (var _i = 0; _i < buffered2.length; _i++) {
  16227. var start = buffered2[_i].start;
  16228. var end = buffered2[_i].end;
  16229. // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));
  16230. if (pos + maxHoleDuration >= start && pos < end) {
  16231. // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
  16232. bufferStart = start;
  16233. bufferEnd = end;
  16234. bufferLen = bufferEnd - pos;
  16235. } else if (pos + maxHoleDuration < start) {
  16236. bufferStartNext = start;
  16237. break;
  16238. }
  16239. }
  16240. return {
  16241. len: bufferLen,
  16242. start: bufferStart || 0,
  16243. end: bufferEnd || 0,
  16244. nextStart: bufferStartNext
  16245. };
  16246. }
  16247. /**
  16248. * Safe method to get buffered property.
  16249. * SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource
  16250. */;
  16251. BufferHelper.getBuffered = function getBuffered(media) {
  16252. try {
  16253. return media.buffered;
  16254. } catch (e) {
  16255. _logger__WEBPACK_IMPORTED_MODULE_0__.logger.log('failed to get media.buffered', e);
  16256. return noopBuffered;
  16257. }
  16258. };
  16259. return BufferHelper;
  16260. }();
  16261. /***/ }),
  16262. /***/ "./src/utils/codecs.ts":
  16263. /*!*****************************!*\
  16264. !*** ./src/utils/codecs.ts ***!
  16265. \*****************************/
  16266. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  16267. "use strict";
  16268. __webpack_require__.r(__webpack_exports__);
  16269. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  16270. /* harmony export */ "isCodecSupportedInMp4": () => (/* binding */ isCodecSupportedInMp4),
  16271. /* harmony export */ "isCodecType": () => (/* binding */ isCodecType)
  16272. /* harmony export */ });
  16273. // from http://mp4ra.org/codecs.html
  16274. var sampleEntryCodesISO = {
  16275. audio: {
  16276. a3ds: true,
  16277. 'ac-3': true,
  16278. 'ac-4': true,
  16279. alac: true,
  16280. alaw: true,
  16281. dra1: true,
  16282. 'dts+': true,
  16283. 'dts-': true,
  16284. dtsc: true,
  16285. dtse: true,
  16286. dtsh: true,
  16287. 'ec-3': true,
  16288. enca: true,
  16289. g719: true,
  16290. g726: true,
  16291. m4ae: true,
  16292. mha1: true,
  16293. mha2: true,
  16294. mhm1: true,
  16295. mhm2: true,
  16296. mlpa: true,
  16297. mp4a: true,
  16298. 'raw ': true,
  16299. Opus: true,
  16300. opus: true,
  16301. // browsers expect this to be lowercase despite MP4RA says 'Opus'
  16302. samr: true,
  16303. sawb: true,
  16304. sawp: true,
  16305. sevc: true,
  16306. sqcp: true,
  16307. ssmv: true,
  16308. twos: true,
  16309. ulaw: true
  16310. },
  16311. video: {
  16312. avc1: true,
  16313. avc2: true,
  16314. avc3: true,
  16315. avc4: true,
  16316. avcp: true,
  16317. av01: true,
  16318. drac: true,
  16319. dva1: true,
  16320. dvav: true,
  16321. dvh1: true,
  16322. dvhe: true,
  16323. encv: true,
  16324. hev1: true,
  16325. hvc1: true,
  16326. mjp2: true,
  16327. mp4v: true,
  16328. mvc1: true,
  16329. mvc2: true,
  16330. mvc3: true,
  16331. mvc4: true,
  16332. resv: true,
  16333. rv60: true,
  16334. s263: true,
  16335. svc1: true,
  16336. svc2: true,
  16337. 'vc-1': true,
  16338. vp08: true,
  16339. vp09: true
  16340. },
  16341. text: {
  16342. stpp: true,
  16343. wvtt: true
  16344. }
  16345. };
  16346. function isCodecType(codec, type) {
  16347. var typeCodes = sampleEntryCodesISO[type];
  16348. return !!typeCodes && typeCodes[codec.slice(0, 4)] === true;
  16349. }
  16350. function isCodecSupportedInMp4(codec, type) {
  16351. return MediaSource.isTypeSupported((type || 'video') + "/mp4;codecs=\"" + codec + "\"");
  16352. }
  16353. /***/ }),
  16354. /***/ "./src/utils/discontinuities.ts":
  16355. /*!**************************************!*\
  16356. !*** ./src/utils/discontinuities.ts ***!
  16357. \**************************************/
  16358. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  16359. "use strict";
  16360. __webpack_require__.r(__webpack_exports__);
  16361. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  16362. /* harmony export */ "adjustSlidingStart": () => (/* binding */ adjustSlidingStart),
  16363. /* harmony export */ "alignMediaPlaylistByPDT": () => (/* binding */ alignMediaPlaylistByPDT),
  16364. /* harmony export */ "alignPDT": () => (/* binding */ alignPDT),
  16365. /* harmony export */ "alignStream": () => (/* binding */ alignStream),
  16366. /* harmony export */ "findDiscontinuousReferenceFrag": () => (/* binding */ findDiscontinuousReferenceFrag),
  16367. /* harmony export */ "findFirstFragWithCC": () => (/* binding */ findFirstFragWithCC),
  16368. /* harmony export */ "shouldAlignOnDiscontinuities": () => (/* binding */ shouldAlignOnDiscontinuities)
  16369. /* harmony export */ });
  16370. /* harmony import */ var _Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
  16371. /* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./logger */ "./src/utils/logger.ts");
  16372. /* harmony import */ var _controller_level_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../controller/level-helper */ "./src/controller/level-helper.ts");
  16373. function findFirstFragWithCC(fragments, cc) {
  16374. var firstFrag = null;
  16375. for (var i = 0, len = fragments.length; i < len; i++) {
  16376. var currentFrag = fragments[i];
  16377. if (currentFrag && currentFrag.cc === cc) {
  16378. firstFrag = currentFrag;
  16379. break;
  16380. }
  16381. }
  16382. return firstFrag;
  16383. }
  16384. function shouldAlignOnDiscontinuities(lastFrag, lastLevel, details) {
  16385. if (lastLevel.details) {
  16386. if (details.endCC > details.startCC || lastFrag && lastFrag.cc < details.startCC) {
  16387. return true;
  16388. }
  16389. }
  16390. return false;
  16391. }
  16392. // Find the first frag in the previous level which matches the CC of the first frag of the new level
  16393. function findDiscontinuousReferenceFrag(prevDetails, curDetails, referenceIndex) {
  16394. if (referenceIndex === void 0) {
  16395. referenceIndex = 0;
  16396. }
  16397. var prevFrags = prevDetails.fragments;
  16398. var curFrags = curDetails.fragments;
  16399. if (!curFrags.length || !prevFrags.length) {
  16400. _logger__WEBPACK_IMPORTED_MODULE_1__.logger.log('No fragments to align');
  16401. return;
  16402. }
  16403. var prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);
  16404. if (!prevStartFrag || prevStartFrag && !prevStartFrag.startPTS) {
  16405. _logger__WEBPACK_IMPORTED_MODULE_1__.logger.log('No frag in previous level to align on');
  16406. return;
  16407. }
  16408. return prevStartFrag;
  16409. }
  16410. function adjustFragmentStart(frag, sliding) {
  16411. if (frag) {
  16412. var start = frag.start + sliding;
  16413. frag.start = frag.startPTS = start;
  16414. frag.endPTS = start + frag.duration;
  16415. }
  16416. }
  16417. function adjustSlidingStart(sliding, details) {
  16418. // Update segments
  16419. var fragments = details.fragments;
  16420. for (var i = 0, len = fragments.length; i < len; i++) {
  16421. adjustFragmentStart(fragments[i], sliding);
  16422. }
  16423. // Update LL-HLS parts at the end of the playlist
  16424. if (details.fragmentHint) {
  16425. adjustFragmentStart(details.fragmentHint, sliding);
  16426. }
  16427. details.alignedSliding = true;
  16428. }
  16429. /**
  16430. * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a
  16431. * contiguous stream with the last fragments.
  16432. * The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to
  16433. * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time
  16434. * and an extra download.
  16435. * @param lastFrag
  16436. * @param lastLevel
  16437. * @param details
  16438. */
  16439. function alignStream(lastFrag, lastLevel, details) {
  16440. if (!lastLevel) {
  16441. return;
  16442. }
  16443. alignDiscontinuities(lastFrag, details, lastLevel);
  16444. if (!details.alignedSliding && lastLevel.details) {
  16445. // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.
  16446. // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same
  16447. // discontinuity sequence.
  16448. alignPDT(details, lastLevel.details);
  16449. }
  16450. if (!details.alignedSliding && lastLevel.details && !details.skippedSegments) {
  16451. // Try to align on sn so that we pick a better start fragment.
  16452. // Do not perform this on playlists with delta updates as this is only to align levels on switch
  16453. // and adjustSliding only adjusts fragments after skippedSegments.
  16454. (0,_controller_level_helper__WEBPACK_IMPORTED_MODULE_2__.adjustSliding)(lastLevel.details, details);
  16455. }
  16456. }
  16457. /**
  16458. * Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same
  16459. * discontinuity sequence.
  16460. * @param lastFrag - The last Fragment which shares the same discontinuity sequence
  16461. * @param lastLevel - The details of the last loaded level
  16462. * @param details - The details of the new level
  16463. */
  16464. function alignDiscontinuities(lastFrag, details, lastLevel) {
  16465. if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) {
  16466. var referenceFrag = findDiscontinuousReferenceFrag(lastLevel.details, details);
  16467. if (referenceFrag && (0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(referenceFrag.start)) {
  16468. _logger__WEBPACK_IMPORTED_MODULE_1__.logger.log("Adjusting PTS using last level due to CC increase within current level " + details.url);
  16469. adjustSlidingStart(referenceFrag.start, details);
  16470. }
  16471. }
  16472. }
  16473. /**
  16474. * Computes the PTS of a new level's fragments using the difference in Program Date Time from the last level.
  16475. * @param details - The details of the new level
  16476. * @param lastDetails - The details of the last loaded level
  16477. */
  16478. function alignPDT(details, lastDetails) {
  16479. // This check protects the unsafe "!" usage below for null program date time access.
  16480. if (!lastDetails.fragments.length || !details.hasProgramDateTime || !lastDetails.hasProgramDateTime) {
  16481. return;
  16482. }
  16483. // if last level sliding is 1000 and its first frag PROGRAM-DATE-TIME is 2017-08-20 1:10:00 AM
  16484. // and if new details first frag PROGRAM DATE-TIME is 2017-08-20 1:10:08 AM
  16485. // then we can deduce that playlist B sliding is 1000+8 = 1008s
  16486. var lastPDT = lastDetails.fragments[0].programDateTime; // hasProgramDateTime check above makes this safe.
  16487. var newPDT = details.fragments[0].programDateTime;
  16488. // date diff is in ms. frag.start is in seconds
  16489. var sliding = (newPDT - lastPDT) / 1000 + lastDetails.fragments[0].start;
  16490. if (sliding && (0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(sliding)) {
  16491. _logger__WEBPACK_IMPORTED_MODULE_1__.logger.log("Adjusting PTS using programDateTime delta " + (newPDT - lastPDT) + "ms, sliding:" + sliding.toFixed(3) + " " + details.url + " ");
  16492. adjustSlidingStart(sliding, details);
  16493. }
  16494. }
  16495. /**
  16496. * Ensures appropriate time-alignment between renditions based on PDT. Unlike `alignPDT`, which adjusts
  16497. * the timeline based on the delta between PDTs of the 0th fragment of two playlists/`LevelDetails`,
  16498. * this function assumes the timelines represented in `refDetails` are accurate, including the PDTs,
  16499. * and uses the "wallclock"/PDT timeline as a cross-reference to `details`, adjusting the presentation
  16500. * times/timelines of `details` accordingly.
  16501. * Given the asynchronous nature of fetches and initial loads of live `main` and audio/subtitle tracks,
  16502. * the primary purpose of this function is to ensure the "local timelines" of audio/subtitle tracks
  16503. * are aligned to the main/video timeline, using PDT as the cross-reference/"anchor" that should
  16504. * be consistent across playlists, per the HLS spec.
  16505. * @param details - The details of the rendition you'd like to time-align (e.g. an audio rendition).
  16506. * @param refDetails - The details of the reference rendition with start and PDT times for alignment.
  16507. */
  16508. function alignMediaPlaylistByPDT(details, refDetails) {
  16509. if (!details.hasProgramDateTime || !refDetails.hasProgramDateTime) {
  16510. return;
  16511. }
  16512. var fragments = details.fragments;
  16513. var refFragments = refDetails.fragments;
  16514. if (!fragments.length || !refFragments.length) {
  16515. return;
  16516. }
  16517. // Calculate a delta to apply to all fragments according to the delta in PDT times and start times
  16518. // of a fragment in the reference details, and a fragment in the target details of the same discontinuity.
  16519. // If a fragment of the same discontinuity was not found use the middle fragment of both.
  16520. var middleFrag = Math.round(refFragments.length / 2) - 1;
  16521. var refFrag = refFragments[middleFrag];
  16522. var frag = findFirstFragWithCC(fragments, refFrag.cc) || fragments[Math.round(fragments.length / 2) - 1];
  16523. var refPDT = refFrag.programDateTime;
  16524. var targetPDT = frag.programDateTime;
  16525. if (refPDT === null || targetPDT === null) {
  16526. return;
  16527. }
  16528. var delta = (targetPDT - refPDT) / 1000 - (frag.start - refFrag.start);
  16529. adjustSlidingStart(delta, details);
  16530. }
  16531. /***/ }),
  16532. /***/ "./src/utils/ewma-bandwidth-estimator.ts":
  16533. /*!***********************************************!*\
  16534. !*** ./src/utils/ewma-bandwidth-estimator.ts ***!
  16535. \***********************************************/
  16536. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  16537. "use strict";
  16538. __webpack_require__.r(__webpack_exports__);
  16539. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  16540. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  16541. /* harmony export */ });
  16542. /* harmony import */ var _utils_ewma__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/ewma */ "./src/utils/ewma.ts");
  16543. /*
  16544. * EWMA Bandwidth Estimator
  16545. * - heavily inspired from shaka-player
  16546. * Tracks bandwidth samples and estimates available bandwidth.
  16547. * Based on the minimum of two exponentially-weighted moving averages with
  16548. * different half-lives.
  16549. */
  16550. var EwmaBandWidthEstimator = /*#__PURE__*/function () {
  16551. function EwmaBandWidthEstimator(slow, fast, defaultEstimate) {
  16552. this.defaultEstimate_ = void 0;
  16553. this.minWeight_ = void 0;
  16554. this.minDelayMs_ = void 0;
  16555. this.slow_ = void 0;
  16556. this.fast_ = void 0;
  16557. this.defaultEstimate_ = defaultEstimate;
  16558. this.minWeight_ = 0.001;
  16559. this.minDelayMs_ = 50;
  16560. this.slow_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](slow);
  16561. this.fast_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](fast);
  16562. }
  16563. var _proto = EwmaBandWidthEstimator.prototype;
  16564. _proto.update = function update(slow, fast) {
  16565. var slow_ = this.slow_,
  16566. fast_ = this.fast_;
  16567. if (this.slow_.halfLife !== slow) {
  16568. this.slow_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](slow, slow_.getEstimate(), slow_.getTotalWeight());
  16569. }
  16570. if (this.fast_.halfLife !== fast) {
  16571. this.fast_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](fast, fast_.getEstimate(), fast_.getTotalWeight());
  16572. }
  16573. };
  16574. _proto.sample = function sample(durationMs, numBytes) {
  16575. durationMs = Math.max(durationMs, this.minDelayMs_);
  16576. var numBits = 8 * numBytes;
  16577. // weight is duration in seconds
  16578. var durationS = durationMs / 1000;
  16579. // value is bandwidth in bits/s
  16580. var bandwidthInBps = numBits / durationS;
  16581. this.fast_.sample(durationS, bandwidthInBps);
  16582. this.slow_.sample(durationS, bandwidthInBps);
  16583. };
  16584. _proto.canEstimate = function canEstimate() {
  16585. var fast = this.fast_;
  16586. return fast && fast.getTotalWeight() >= this.minWeight_;
  16587. };
  16588. _proto.getEstimate = function getEstimate() {
  16589. if (this.canEstimate()) {
  16590. // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));
  16591. // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));
  16592. // Take the minimum of these two estimates. This should have the effect of
  16593. // adapting down quickly, but up more slowly.
  16594. return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
  16595. } else {
  16596. return this.defaultEstimate_;
  16597. }
  16598. };
  16599. _proto.destroy = function destroy() {};
  16600. return EwmaBandWidthEstimator;
  16601. }();
  16602. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (EwmaBandWidthEstimator);
  16603. /***/ }),
  16604. /***/ "./src/utils/ewma.ts":
  16605. /*!***************************!*\
  16606. !*** ./src/utils/ewma.ts ***!
  16607. \***************************/
  16608. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  16609. "use strict";
  16610. __webpack_require__.r(__webpack_exports__);
  16611. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  16612. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  16613. /* harmony export */ });
  16614. /*
  16615. * compute an Exponential Weighted moving average
  16616. * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  16617. * - heavily inspired from shaka-player
  16618. */
  16619. var EWMA = /*#__PURE__*/function () {
  16620. // About half of the estimated value will be from the last |halfLife| samples by weight.
  16621. function EWMA(halfLife, estimate, weight) {
  16622. if (estimate === void 0) {
  16623. estimate = 0;
  16624. }
  16625. if (weight === void 0) {
  16626. weight = 0;
  16627. }
  16628. this.halfLife = void 0;
  16629. this.alpha_ = void 0;
  16630. this.estimate_ = void 0;
  16631. this.totalWeight_ = void 0;
  16632. this.halfLife = halfLife;
  16633. // Larger values of alpha expire historical data more slowly.
  16634. this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
  16635. this.estimate_ = estimate;
  16636. this.totalWeight_ = weight;
  16637. }
  16638. var _proto = EWMA.prototype;
  16639. _proto.sample = function sample(weight, value) {
  16640. var adjAlpha = Math.pow(this.alpha_, weight);
  16641. this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
  16642. this.totalWeight_ += weight;
  16643. };
  16644. _proto.getTotalWeight = function getTotalWeight() {
  16645. return this.totalWeight_;
  16646. };
  16647. _proto.getEstimate = function getEstimate() {
  16648. if (this.alpha_) {
  16649. var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
  16650. if (zeroFactor) {
  16651. return this.estimate_ / zeroFactor;
  16652. }
  16653. }
  16654. return this.estimate_;
  16655. };
  16656. return EWMA;
  16657. }();
  16658. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (EWMA);
  16659. /***/ }),
  16660. /***/ "./src/utils/fetch-loader.ts":
  16661. /*!***********************************!*\
  16662. !*** ./src/utils/fetch-loader.ts ***!
  16663. \***********************************/
  16664. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  16665. "use strict";
  16666. __webpack_require__.r(__webpack_exports__);
  16667. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  16668. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__),
  16669. /* harmony export */ "fetchSupported": () => (/* binding */ fetchSupported)
  16670. /* harmony export */ });
  16671. /* harmony import */ var _Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
  16672. /* harmony import */ var _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loader/load-stats */ "./src/loader/load-stats.ts");
  16673. /* harmony import */ var _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/chunk-cache */ "./src/demux/chunk-cache.ts");
  16674. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  16675. function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
  16676. function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct.bind(); } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
  16677. function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
  16678. function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
  16679. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  16680. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  16681. function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
  16682. function fetchSupported() {
  16683. if (
  16684. // @ts-ignore
  16685. self.fetch && self.AbortController && self.ReadableStream && self.Request) {
  16686. try {
  16687. new self.ReadableStream({}); // eslint-disable-line no-new
  16688. return true;
  16689. } catch (e) {
  16690. /* noop */
  16691. }
  16692. }
  16693. return false;
  16694. }
  16695. var FetchLoader = /*#__PURE__*/function () {
  16696. function FetchLoader(config /* HlsConfig */) {
  16697. this.fetchSetup = void 0;
  16698. this.requestTimeout = void 0;
  16699. this.request = void 0;
  16700. this.response = void 0;
  16701. this.controller = void 0;
  16702. this.context = void 0;
  16703. this.config = null;
  16704. this.callbacks = null;
  16705. this.stats = void 0;
  16706. this.loader = null;
  16707. this.fetchSetup = config.fetchSetup || getRequest;
  16708. this.controller = new self.AbortController();
  16709. this.stats = new _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__.LoadStats();
  16710. }
  16711. var _proto = FetchLoader.prototype;
  16712. _proto.destroy = function destroy() {
  16713. this.loader = this.callbacks = null;
  16714. this.abortInternal();
  16715. };
  16716. _proto.abortInternal = function abortInternal() {
  16717. var response = this.response;
  16718. if (!response || !response.ok) {
  16719. this.stats.aborted = true;
  16720. this.controller.abort();
  16721. }
  16722. };
  16723. _proto.abort = function abort() {
  16724. var _this$callbacks;
  16725. this.abortInternal();
  16726. if ((_this$callbacks = this.callbacks) !== null && _this$callbacks !== void 0 && _this$callbacks.onAbort) {
  16727. this.callbacks.onAbort(this.stats, this.context, this.response);
  16728. }
  16729. };
  16730. _proto.load = function load(context, config, callbacks) {
  16731. var _this = this;
  16732. var stats = this.stats;
  16733. if (stats.loading.start) {
  16734. throw new Error('Loader can only be used once.');
  16735. }
  16736. stats.loading.start = self.performance.now();
  16737. var initParams = getRequestParameters(context, this.controller.signal);
  16738. var onProgress = callbacks.onProgress;
  16739. var isArrayBuffer = context.responseType === 'arraybuffer';
  16740. var LENGTH = isArrayBuffer ? 'byteLength' : 'length';
  16741. this.context = context;
  16742. this.config = config;
  16743. this.callbacks = callbacks;
  16744. this.request = this.fetchSetup(context, initParams);
  16745. self.clearTimeout(this.requestTimeout);
  16746. this.requestTimeout = self.setTimeout(function () {
  16747. _this.abortInternal();
  16748. callbacks.onTimeout(stats, context, _this.response);
  16749. }, config.timeout);
  16750. self.fetch(this.request).then(function (response) {
  16751. _this.response = _this.loader = response;
  16752. if (!response.ok) {
  16753. var status = response.status,
  16754. statusText = response.statusText;
  16755. throw new FetchError(statusText || 'fetch, bad network response', status, response);
  16756. }
  16757. stats.loading.first = Math.max(self.performance.now(), stats.loading.start);
  16758. stats.total = parseInt(response.headers.get('Content-Length') || '0');
  16759. if (onProgress && (0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(config.highWaterMark)) {
  16760. return _this.loadProgressively(response, stats, context, config.highWaterMark, onProgress);
  16761. }
  16762. if (isArrayBuffer) {
  16763. return response.arrayBuffer();
  16764. }
  16765. return response.text();
  16766. }).then(function (responseData) {
  16767. var response = _this.response;
  16768. self.clearTimeout(_this.requestTimeout);
  16769. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  16770. var total = responseData[LENGTH];
  16771. if (total) {
  16772. stats.loaded = stats.total = total;
  16773. }
  16774. var loaderResponse = {
  16775. url: response.url,
  16776. data: responseData
  16777. };
  16778. if (onProgress && !(0,_Users_dexter_project_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__.isFiniteNumber)(config.highWaterMark)) {
  16779. onProgress(stats, context, responseData, response);
  16780. }
  16781. callbacks.onSuccess(loaderResponse, stats, context, response);
  16782. }).catch(function (error) {
  16783. self.clearTimeout(_this.requestTimeout);
  16784. if (stats.aborted) {
  16785. return;
  16786. }
  16787. // CORS errors result in an undefined code. Set it to 0 here to align with XHR's behavior
  16788. // when destroying, 'error' itself can be undefined
  16789. var code = !error ? 0 : error.code || 0;
  16790. var text = !error ? null : error.message;
  16791. callbacks.onError({
  16792. code: code,
  16793. text: text
  16794. }, context, error ? error.details : null);
  16795. });
  16796. };
  16797. _proto.getCacheAge = function getCacheAge() {
  16798. var result = null;
  16799. if (this.response) {
  16800. var ageHeader = this.response.headers.get('age');
  16801. result = ageHeader ? parseFloat(ageHeader) : null;
  16802. }
  16803. return result;
  16804. };
  16805. _proto.loadProgressively = function loadProgressively(response, stats, context, highWaterMark, onProgress) {
  16806. if (highWaterMark === void 0) {
  16807. highWaterMark = 0;
  16808. }
  16809. var chunkCache = new _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_2__["default"]();
  16810. var reader = response.body.getReader();
  16811. var pump = function pump() {
  16812. return reader.read().then(function (data) {
  16813. if (data.done) {
  16814. if (chunkCache.dataLength) {
  16815. onProgress(stats, context, chunkCache.flush(), response);
  16816. }
  16817. return Promise.resolve(new ArrayBuffer(0));
  16818. }
  16819. var chunk = data.value;
  16820. var len = chunk.length;
  16821. stats.loaded += len;
  16822. if (len < highWaterMark || chunkCache.dataLength) {
  16823. // The current chunk is too small to to be emitted or the cache already has data
  16824. // Push it to the cache
  16825. chunkCache.push(chunk);
  16826. if (chunkCache.dataLength >= highWaterMark) {
  16827. // flush in order to join the typed arrays
  16828. onProgress(stats, context, chunkCache.flush(), response);
  16829. }
  16830. } else {
  16831. // If there's nothing cached already, and the chache is large enough
  16832. // just emit the progress event
  16833. onProgress(stats, context, chunk, response);
  16834. }
  16835. return pump();
  16836. }).catch(function () {
  16837. /* aborted */
  16838. return Promise.reject();
  16839. });
  16840. };
  16841. return pump();
  16842. };
  16843. return FetchLoader;
  16844. }();
  16845. function getRequestParameters(context, signal) {
  16846. var initParams = {
  16847. method: 'GET',
  16848. mode: 'cors',
  16849. credentials: 'same-origin',
  16850. signal: signal,
  16851. headers: new self.Headers(_extends({}, context.headers))
  16852. };
  16853. if (context.rangeEnd) {
  16854. initParams.headers.set('Range', 'bytes=' + context.rangeStart + '-' + String(context.rangeEnd - 1));
  16855. }
  16856. return initParams;
  16857. }
  16858. function getRequest(context, initParams) {
  16859. return new self.Request(context.url, initParams);
  16860. }
  16861. var FetchError = /*#__PURE__*/function (_Error) {
  16862. _inheritsLoose(FetchError, _Error);
  16863. function FetchError(message, code, details) {
  16864. var _this2;
  16865. _this2 = _Error.call(this, message) || this;
  16866. _this2.code = void 0;
  16867. _this2.details = void 0;
  16868. _this2.code = code;
  16869. _this2.details = details;
  16870. return _this2;
  16871. }
  16872. return FetchError;
  16873. }( /*#__PURE__*/_wrapNativeSuper(Error));
  16874. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (FetchLoader);
  16875. /***/ }),
  16876. /***/ "./src/utils/logger.ts":
  16877. /*!*****************************!*\
  16878. !*** ./src/utils/logger.ts ***!
  16879. \*****************************/
  16880. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  16881. "use strict";
  16882. __webpack_require__.r(__webpack_exports__);
  16883. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  16884. /* harmony export */ "enableLogs": () => (/* binding */ enableLogs),
  16885. /* harmony export */ "logger": () => (/* binding */ logger)
  16886. /* harmony export */ });
  16887. var noop = function noop() {};
  16888. var fakeLogger = {
  16889. trace: noop,
  16890. debug: noop,
  16891. log: noop,
  16892. warn: noop,
  16893. info: noop,
  16894. error: noop
  16895. };
  16896. var exportedLogger = fakeLogger;
  16897. // let lastCallTime;
  16898. // function formatMsgWithTimeInfo(type, msg) {
  16899. // const now = Date.now();
  16900. // const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';
  16901. // lastCallTime = now;
  16902. // msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';
  16903. // return msg;
  16904. // }
  16905. function consolePrintFn(type) {
  16906. var func = self.console[type];
  16907. if (func) {
  16908. return func.bind(self.console, "[" + type + "] >");
  16909. }
  16910. return noop;
  16911. }
  16912. function exportLoggerFunctions(debugConfig) {
  16913. for (var _len = arguments.length, functions = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  16914. functions[_key - 1] = arguments[_key];
  16915. }
  16916. functions.forEach(function (type) {
  16917. exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);
  16918. });
  16919. }
  16920. function enableLogs(debugConfig, id) {
  16921. // check that console is available
  16922. if (self.console && debugConfig === true || typeof debugConfig === 'object') {
  16923. exportLoggerFunctions(debugConfig,
  16924. // Remove out from list here to hard-disable a log-level
  16925. // 'trace',
  16926. 'debug', 'log', 'info', 'warn', 'error');
  16927. // Some browsers don't allow to use bind on console object anyway
  16928. // fallback to default if needed
  16929. try {
  16930. exportedLogger.log("Debug logs enabled for \"" + id + "\"");
  16931. } catch (e) {
  16932. exportedLogger = fakeLogger;
  16933. }
  16934. } else {
  16935. exportedLogger = fakeLogger;
  16936. }
  16937. }
  16938. var logger = exportedLogger;
  16939. /***/ }),
  16940. /***/ "./src/utils/mediakeys-helper.ts":
  16941. /*!***************************************!*\
  16942. !*** ./src/utils/mediakeys-helper.ts ***!
  16943. \***************************************/
  16944. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  16945. "use strict";
  16946. __webpack_require__.r(__webpack_exports__);
  16947. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  16948. /* harmony export */ "KeySystems": () => (/* binding */ KeySystems),
  16949. /* harmony export */ "requestMediaKeySystemAccess": () => (/* binding */ requestMediaKeySystemAccess)
  16950. /* harmony export */ });
  16951. /**
  16952. * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess
  16953. */
  16954. var KeySystems;
  16955. (function (KeySystems) {
  16956. KeySystems["WIDEVINE"] = "com.widevine.alpha";
  16957. KeySystems["PLAYREADY"] = "com.microsoft.playready";
  16958. })(KeySystems || (KeySystems = {}));
  16959. var requestMediaKeySystemAccess = function () {
  16960. if (typeof self !== 'undefined' && self.navigator && self.navigator.requestMediaKeySystemAccess) {
  16961. return self.navigator.requestMediaKeySystemAccess.bind(self.navigator);
  16962. } else {
  16963. return null;
  16964. }
  16965. }();
  16966. /***/ }),
  16967. /***/ "./src/utils/mediasource-helper.ts":
  16968. /*!*****************************************!*\
  16969. !*** ./src/utils/mediasource-helper.ts ***!
  16970. \*****************************************/
  16971. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  16972. "use strict";
  16973. __webpack_require__.r(__webpack_exports__);
  16974. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  16975. /* harmony export */ "getMediaSource": () => (/* binding */ getMediaSource)
  16976. /* harmony export */ });
  16977. /**
  16978. * MediaSource helper
  16979. */
  16980. function getMediaSource() {
  16981. return self.MediaSource || self.WebKitMediaSource;
  16982. }
  16983. /***/ }),
  16984. /***/ "./src/utils/mp4-tools.ts":
  16985. /*!********************************!*\
  16986. !*** ./src/utils/mp4-tools.ts ***!
  16987. \********************************/
  16988. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  16989. "use strict";
  16990. __webpack_require__.r(__webpack_exports__);
  16991. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  16992. /* harmony export */ "RemuxerTrackIdConfig": () => (/* binding */ RemuxerTrackIdConfig),
  16993. /* harmony export */ "appendUint8Array": () => (/* binding */ appendUint8Array),
  16994. /* harmony export */ "bin2str": () => (/* binding */ bin2str),
  16995. /* harmony export */ "computeRawDurationFromSamples": () => (/* binding */ computeRawDurationFromSamples),
  16996. /* harmony export */ "discardEPB": () => (/* binding */ discardEPB),
  16997. /* harmony export */ "findBox": () => (/* binding */ findBox),
  16998. /* harmony export */ "getDuration": () => (/* binding */ getDuration),
  16999. /* harmony export */ "getStartDTS": () => (/* binding */ getStartDTS),
  17000. /* harmony export */ "offsetStartDTS": () => (/* binding */ offsetStartDTS),
  17001. /* harmony export */ "parseEmsg": () => (/* binding */ parseEmsg),
  17002. /* harmony export */ "parseInitSegment": () => (/* binding */ parseInitSegment),
  17003. /* harmony export */ "parseSEIMessageFromNALu": () => (/* binding */ parseSEIMessageFromNALu),
  17004. /* harmony export */ "parseSamples": () => (/* binding */ parseSamples),
  17005. /* harmony export */ "parseSegmentIndex": () => (/* binding */ parseSegmentIndex),
  17006. /* harmony export */ "readSint32": () => (/* binding */ readSint32),
  17007. /* harmony export */ "readUint16": () => (/* binding */ readUint16),
  17008. /* harmony export */ "readUint32": () => (/* binding */ readUint32),
  17009. /* harmony export */ "segmentValidRange": () => (/* binding */ segmentValidRange),
  17010. /* harmony export */ "writeUint32": () => (/* binding */ writeUint32)
  17011. /* harmony export */ });
  17012. /* harmony import */ var _typed_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./typed-array */ "./src/utils/typed-array.ts");
  17013. /* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
  17014. /* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
  17015. var UINT32_MAX = Math.pow(2, 32) - 1;
  17016. var push = [].push;
  17017. // We are using fixed track IDs for driving the MP4 remuxer
  17018. // instead of following the TS PIDs.
  17019. // There is no reason not to do this and some browsers/SourceBuffer-demuxers
  17020. // may not like if there are TrackID "switches"
  17021. // See https://github.com/video-dev/hls.js/issues/1331
  17022. // Here we are mapping our internal track types to constant MP4 track IDs
  17023. // With MSE currently one can only have one track of each, and we are muxing
  17024. // whatever video/audio rendition in them.
  17025. var RemuxerTrackIdConfig = {
  17026. video: 1,
  17027. audio: 2,
  17028. id3: 3,
  17029. text: 4
  17030. };
  17031. function bin2str(data) {
  17032. return String.fromCharCode.apply(null, data);
  17033. }
  17034. function readUint16(buffer, offset) {
  17035. var val = buffer[offset] << 8 | buffer[offset + 1];
  17036. return val < 0 ? 65536 + val : val;
  17037. }
  17038. function readUint32(buffer, offset) {
  17039. var val = readSint32(buffer, offset);
  17040. return val < 0 ? 4294967296 + val : val;
  17041. }
  17042. function readSint32(buffer, offset) {
  17043. return buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];
  17044. }
  17045. function writeUint32(buffer, offset, value) {
  17046. buffer[offset] = value >> 24;
  17047. buffer[offset + 1] = value >> 16 & 0xff;
  17048. buffer[offset + 2] = value >> 8 & 0xff;
  17049. buffer[offset + 3] = value & 0xff;
  17050. }
  17051. // Find the data for a box specified by its path
  17052. function findBox(data, path) {
  17053. var results = [];
  17054. if (!path.length) {
  17055. // short-circuit the search for empty paths
  17056. return results;
  17057. }
  17058. var end = data.byteLength;
  17059. for (var i = 0; i < end;) {
  17060. var size = readUint32(data, i);
  17061. var type = bin2str(data.subarray(i + 4, i + 8));
  17062. var endbox = size > 1 ? i + size : end;
  17063. if (type === path[0]) {
  17064. if (path.length === 1) {
  17065. // this is the end of the path and we've found the box we were
  17066. // looking for
  17067. results.push(data.subarray(i + 8, endbox));
  17068. } else {
  17069. // recursively search for the next box along the path
  17070. var subresults = findBox(data.subarray(i + 8, endbox), path.slice(1));
  17071. if (subresults.length) {
  17072. push.apply(results, subresults);
  17073. }
  17074. }
  17075. }
  17076. i = endbox;
  17077. }
  17078. // we've finished searching all of data
  17079. return results;
  17080. }
  17081. function parseSegmentIndex(sidx) {
  17082. var references = [];
  17083. var version = sidx[0];
  17084. // set initial offset, we skip the reference ID (not needed)
  17085. var index = 8;
  17086. var timescale = readUint32(sidx, index);
  17087. index += 4;
  17088. // TODO: parse earliestPresentationTime and firstOffset
  17089. // usually zero in our case
  17090. var earliestPresentationTime = 0;
  17091. var firstOffset = 0;
  17092. if (version === 0) {
  17093. index += 8;
  17094. } else {
  17095. index += 16;
  17096. }
  17097. // skip reserved
  17098. index += 2;
  17099. var startByte = sidx.length + firstOffset;
  17100. var referencesCount = readUint16(sidx, index);
  17101. index += 2;
  17102. for (var i = 0; i < referencesCount; i++) {
  17103. var referenceIndex = index;
  17104. var referenceInfo = readUint32(sidx, referenceIndex);
  17105. referenceIndex += 4;
  17106. var referenceSize = referenceInfo & 0x7fffffff;
  17107. var referenceType = (referenceInfo & 0x80000000) >>> 31;
  17108. if (referenceType === 1) {
  17109. // eslint-disable-next-line no-console
  17110. console.warn('SIDX has hierarchical references (not supported)');
  17111. return null;
  17112. }
  17113. var subsegmentDuration = readUint32(sidx, referenceIndex);
  17114. referenceIndex += 4;
  17115. references.push({
  17116. referenceSize: referenceSize,
  17117. subsegmentDuration: subsegmentDuration,
  17118. // unscaled
  17119. info: {
  17120. duration: subsegmentDuration / timescale,
  17121. start: startByte,
  17122. end: startByte + referenceSize - 1
  17123. }
  17124. });
  17125. startByte += referenceSize;
  17126. // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits
  17127. // for |sapDelta|.
  17128. referenceIndex += 4;
  17129. // skip to next ref
  17130. index = referenceIndex;
  17131. }
  17132. return {
  17133. earliestPresentationTime: earliestPresentationTime,
  17134. timescale: timescale,
  17135. version: version,
  17136. referencesCount: referencesCount,
  17137. references: references
  17138. };
  17139. }
  17140. /**
  17141. * Parses an MP4 initialization segment and extracts stream type and
  17142. * timescale values for any declared tracks. Timescale values indicate the
  17143. * number of clock ticks per second to assume for time-based values
  17144. * elsewhere in the MP4.
  17145. *
  17146. * To determine the start time of an MP4, you need two pieces of
  17147. * information: the timescale unit and the earliest base media decode
  17148. * time. Multiple timescales can be specified within an MP4 but the
  17149. * base media decode time is always expressed in the timescale from
  17150. * the media header box for the track:
  17151. * ```
  17152. * moov > trak > mdia > mdhd.timescale
  17153. * moov > trak > mdia > hdlr
  17154. * ```
  17155. * @param initSegment {Uint8Array} the bytes of the init segment
  17156. * @return {InitData} a hash of track type to timescale values or null if
  17157. * the init segment is malformed.
  17158. */
  17159. function parseInitSegment(initSegment) {
  17160. var result = [];
  17161. var traks = findBox(initSegment, ['moov', 'trak']);
  17162. for (var i = 0; i < traks.length; i++) {
  17163. var trak = traks[i];
  17164. var tkhd = findBox(trak, ['tkhd'])[0];
  17165. if (tkhd) {
  17166. var version = tkhd[0];
  17167. var _index = version === 0 ? 12 : 20;
  17168. var trackId = readUint32(tkhd, _index);
  17169. var mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  17170. if (mdhd) {
  17171. version = mdhd[0];
  17172. _index = version === 0 ? 12 : 20;
  17173. var timescale = readUint32(mdhd, _index);
  17174. var hdlr = findBox(trak, ['mdia', 'hdlr'])[0];
  17175. if (hdlr) {
  17176. var hdlrType = bin2str(hdlr.subarray(8, 12));
  17177. var type = {
  17178. soun: _loader_fragment__WEBPACK_IMPORTED_MODULE_1__.ElementaryStreamTypes.AUDIO,
  17179. vide: _loader_fragment__WEBPACK_IMPORTED_MODULE_1__.ElementaryStreamTypes.VIDEO
  17180. }[hdlrType];
  17181. if (type) {
  17182. // Parse codec details
  17183. var stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  17184. var codec = void 0;
  17185. if (stsd) {
  17186. codec = bin2str(stsd.subarray(12, 16));
  17187. // TODO: Parse codec details to be able to build MIME type.
  17188. // stsd.start += 8;
  17189. // const codecBox = findBox(stsd, [codec])[0];
  17190. // if (codecBox) {
  17191. // TODO: Codec parsing support for avc1, mp4a, hevc, av01...
  17192. // }
  17193. }
  17194. result[trackId] = {
  17195. timescale: timescale,
  17196. type: type
  17197. };
  17198. result[type] = {
  17199. timescale: timescale,
  17200. id: trackId,
  17201. codec: codec
  17202. };
  17203. }
  17204. }
  17205. }
  17206. }
  17207. }
  17208. var trex = findBox(initSegment, ['moov', 'mvex', 'trex']);
  17209. trex.forEach(function (trex) {
  17210. var trackId = readUint32(trex, 4);
  17211. var track = result[trackId];
  17212. if (track) {
  17213. track.default = {
  17214. duration: readUint32(trex, 12),
  17215. flags: readUint32(trex, 20)
  17216. };
  17217. }
  17218. });
  17219. return result;
  17220. }
  17221. /**
  17222. * Determine the base media decode start time, in seconds, for an MP4
  17223. * fragment. If multiple fragments are specified, the earliest time is
  17224. * returned.
  17225. *
  17226. * The base media decode time can be parsed from track fragment
  17227. * metadata:
  17228. * ```
  17229. * moof > traf > tfdt.baseMediaDecodeTime
  17230. * ```
  17231. * It requires the timescale value from the mdhd to interpret.
  17232. *
  17233. * @param initData {InitData} a hash of track type to timescale values
  17234. * @param fmp4 {Uint8Array} the bytes of the mp4 fragment
  17235. * @return {number} the earliest base media decode start time for the
  17236. * fragment, in seconds
  17237. */
  17238. function getStartDTS(initData, fmp4) {
  17239. // we need info from two children of each track fragment box
  17240. return findBox(fmp4, ['moof', 'traf']).reduce(function (result, traf) {
  17241. var tfdt = findBox(traf, ['tfdt'])[0];
  17242. var version = tfdt[0];
  17243. var start = findBox(traf, ['tfhd']).reduce(function (result, tfhd) {
  17244. // get the track id from the tfhd
  17245. var id = readUint32(tfhd, 4);
  17246. var track = initData[id];
  17247. if (track) {
  17248. var baseTime = readUint32(tfdt, 4);
  17249. if (version === 1) {
  17250. baseTime *= Math.pow(2, 32);
  17251. baseTime += readUint32(tfdt, 8);
  17252. }
  17253. // assume a 90kHz clock if no timescale was specified
  17254. var scale = track.timescale || 90e3;
  17255. // convert base time to seconds
  17256. var startTime = baseTime / scale;
  17257. if (isFinite(startTime) && (result === null || startTime < result)) {
  17258. return startTime;
  17259. }
  17260. }
  17261. return result;
  17262. }, null);
  17263. if (start !== null && isFinite(start) && (result === null || start < result)) {
  17264. return start;
  17265. }
  17266. return result;
  17267. }, null) || 0;
  17268. }
  17269. /*
  17270. For Reference:
  17271. aligned(8) class TrackFragmentHeaderBox
  17272. extends FullBox(‘tfhd’, 0, tf_flags){
  17273. unsigned int(32) track_ID;
  17274. // all the following are optional fields
  17275. unsigned int(64) base_data_offset;
  17276. unsigned int(32) sample_description_index;
  17277. unsigned int(32) default_sample_duration;
  17278. unsigned int(32) default_sample_size;
  17279. unsigned int(32) default_sample_flags
  17280. }
  17281. */
  17282. function getDuration(data, initData) {
  17283. var rawDuration = 0;
  17284. var videoDuration = 0;
  17285. var audioDuration = 0;
  17286. var trafs = findBox(data, ['moof', 'traf']);
  17287. for (var i = 0; i < trafs.length; i++) {
  17288. var traf = trafs[i];
  17289. // There is only one tfhd & trun per traf
  17290. // This is true for CMAF style content, and we should perhaps check the ftyp
  17291. // and only look for a single trun then, but for ISOBMFF we should check
  17292. // for multiple track runs.
  17293. var tfhd = findBox(traf, ['tfhd'])[0];
  17294. // get the track id from the tfhd
  17295. var id = readUint32(tfhd, 4);
  17296. var track = initData[id];
  17297. if (!track) {
  17298. continue;
  17299. }
  17300. var trackDefault = track.default;
  17301. var tfhdFlags = readUint32(tfhd, 0) | (trackDefault === null || trackDefault === void 0 ? void 0 : trackDefault.flags);
  17302. var sampleDuration = trackDefault === null || trackDefault === void 0 ? void 0 : trackDefault.duration;
  17303. if (tfhdFlags & 0x000008) {
  17304. // 0x000008 indicates the presence of the default_sample_duration field
  17305. if (tfhdFlags & 0x000002) {
  17306. // 0x000002 indicates the presence of the sample_description_index field, which precedes default_sample_duration
  17307. // If present, the default_sample_duration exists at byte offset 12
  17308. sampleDuration = readUint32(tfhd, 12);
  17309. } else {
  17310. // Otherwise, the duration is at byte offset 8
  17311. sampleDuration = readUint32(tfhd, 8);
  17312. }
  17313. }
  17314. // assume a 90kHz clock if no timescale was specified
  17315. var timescale = track.timescale || 90e3;
  17316. var truns = findBox(traf, ['trun']);
  17317. for (var j = 0; j < truns.length; j++) {
  17318. rawDuration = computeRawDurationFromSamples(truns[j]);
  17319. if (!rawDuration && sampleDuration) {
  17320. var sampleCount = readUint32(truns[j], 4);
  17321. rawDuration = sampleDuration * sampleCount;
  17322. }
  17323. if (track.type === _loader_fragment__WEBPACK_IMPORTED_MODULE_1__.ElementaryStreamTypes.VIDEO) {
  17324. videoDuration += rawDuration / timescale;
  17325. } else if (track.type === _loader_fragment__WEBPACK_IMPORTED_MODULE_1__.ElementaryStreamTypes.AUDIO) {
  17326. audioDuration += rawDuration / timescale;
  17327. }
  17328. }
  17329. }
  17330. if (videoDuration === 0 && audioDuration === 0) {
  17331. // If duration samples are not available in the traf use sidx subsegment_duration
  17332. var sidxDuration = 0;
  17333. var sidxs = findBox(data, ['sidx']);
  17334. for (var _i = 0; _i < sidxs.length; _i++) {
  17335. var sidx = parseSegmentIndex(sidxs[_i]);
  17336. if (sidx !== null && sidx !== void 0 && sidx.references) {
  17337. sidxDuration += sidx.references.reduce(function (dur, ref) {
  17338. return dur + ref.info.duration || 0;
  17339. }, 0);
  17340. }
  17341. }
  17342. return sidxDuration;
  17343. }
  17344. if (videoDuration) {
  17345. return videoDuration;
  17346. }
  17347. return audioDuration;
  17348. }
  17349. /*
  17350. For Reference:
  17351. aligned(8) class TrackRunBox
  17352. extends FullBox(‘trun’, version, tr_flags) {
  17353. unsigned int(32) sample_count;
  17354. // the following are optional fields
  17355. signed int(32) data_offset;
  17356. unsigned int(32) first_sample_flags;
  17357. // all fields in the following array are optional
  17358. {
  17359. unsigned int(32) sample_duration;
  17360. unsigned int(32) sample_size;
  17361. unsigned int(32) sample_flags
  17362. if (version == 0)
  17363. { unsigned int(32)
  17364. else
  17365. { signed int(32)
  17366. }[ sample_count ]
  17367. }
  17368. */
  17369. function computeRawDurationFromSamples(trun) {
  17370. var flags = readUint32(trun, 0);
  17371. // Flags are at offset 0, non-optional sample_count is at offset 4. Therefore we start 8 bytes in.
  17372. // Each field is an int32, which is 4 bytes
  17373. var offset = 8;
  17374. // data-offset-present flag
  17375. if (flags & 0x000001) {
  17376. offset += 4;
  17377. }
  17378. // first-sample-flags-present flag
  17379. if (flags & 0x000004) {
  17380. offset += 4;
  17381. }
  17382. var duration = 0;
  17383. var sampleCount = readUint32(trun, 4);
  17384. for (var i = 0; i < sampleCount; i++) {
  17385. // sample-duration-present flag
  17386. if (flags & 0x000100) {
  17387. var sampleDuration = readUint32(trun, offset);
  17388. duration += sampleDuration;
  17389. offset += 4;
  17390. }
  17391. // sample-size-present flag
  17392. if (flags & 0x000200) {
  17393. offset += 4;
  17394. }
  17395. // sample-flags-present flag
  17396. if (flags & 0x000400) {
  17397. offset += 4;
  17398. }
  17399. // sample-composition-time-offsets-present flag
  17400. if (flags & 0x000800) {
  17401. offset += 4;
  17402. }
  17403. }
  17404. return duration;
  17405. }
  17406. function offsetStartDTS(initData, fmp4, timeOffset) {
  17407. findBox(fmp4, ['moof', 'traf']).forEach(function (traf) {
  17408. findBox(traf, ['tfhd']).forEach(function (tfhd) {
  17409. // get the track id from the tfhd
  17410. var id = readUint32(tfhd, 4);
  17411. var track = initData[id];
  17412. if (!track) {
  17413. return;
  17414. }
  17415. // assume a 90kHz clock if no timescale was specified
  17416. var timescale = track.timescale || 90e3;
  17417. // get the base media decode time from the tfdt
  17418. findBox(traf, ['tfdt']).forEach(function (tfdt) {
  17419. var version = tfdt[0];
  17420. var baseMediaDecodeTime = readUint32(tfdt, 4);
  17421. if (version === 0) {
  17422. baseMediaDecodeTime -= timeOffset * timescale;
  17423. baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);
  17424. writeUint32(tfdt, 4, baseMediaDecodeTime);
  17425. } else {
  17426. baseMediaDecodeTime *= Math.pow(2, 32);
  17427. baseMediaDecodeTime += readUint32(tfdt, 8);
  17428. baseMediaDecodeTime -= timeOffset * timescale;
  17429. baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);
  17430. var upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
  17431. var lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
  17432. writeUint32(tfdt, 4, upper);
  17433. writeUint32(tfdt, 8, lower);
  17434. }
  17435. });
  17436. });
  17437. });
  17438. }
  17439. // TODO: Check if the last moof+mdat pair is part of the valid range
  17440. function segmentValidRange(data) {
  17441. var segmentedRange = {
  17442. valid: null,
  17443. remainder: null
  17444. };
  17445. var moofs = findBox(data, ['moof']);
  17446. if (!moofs) {
  17447. return segmentedRange;
  17448. } else if (moofs.length < 2) {
  17449. segmentedRange.remainder = data;
  17450. return segmentedRange;
  17451. }
  17452. var last = moofs[moofs.length - 1];
  17453. // Offset by 8 bytes; findBox offsets the start by as much
  17454. segmentedRange.valid = (0,_typed_array__WEBPACK_IMPORTED_MODULE_0__.sliceUint8)(data, 0, last.byteOffset - 8);
  17455. segmentedRange.remainder = (0,_typed_array__WEBPACK_IMPORTED_MODULE_0__.sliceUint8)(data, last.byteOffset - 8);
  17456. return segmentedRange;
  17457. }
  17458. function appendUint8Array(data1, data2) {
  17459. var temp = new Uint8Array(data1.length + data2.length);
  17460. temp.set(data1);
  17461. temp.set(data2, data1.length);
  17462. return temp;
  17463. }
  17464. function parseSamples(timeOffset, track) {
  17465. var seiSamples = [];
  17466. var videoData = track.samples;
  17467. var timescale = track.timescale;
  17468. var trackId = track.id;
  17469. var isHEVCFlavor = false;
  17470. var moofs = findBox(videoData, ['moof']);
  17471. moofs.map(function (moof) {
  17472. var moofOffset = moof.byteOffset - 8;
  17473. var trafs = findBox(moof, ['traf']);
  17474. trafs.map(function (traf) {
  17475. // get the base media decode time from the tfdt
  17476. var baseTime = findBox(traf, ['tfdt']).map(function (tfdt) {
  17477. var version = tfdt[0];
  17478. var result = readUint32(tfdt, 4);
  17479. if (version === 1) {
  17480. result *= Math.pow(2, 32);
  17481. result += readUint32(tfdt, 8);
  17482. }
  17483. return result / timescale;
  17484. })[0];
  17485. if (baseTime !== undefined) {
  17486. timeOffset = baseTime;
  17487. }
  17488. return findBox(traf, ['tfhd']).map(function (tfhd) {
  17489. var id = readUint32(tfhd, 4);
  17490. var tfhdFlags = readUint32(tfhd, 0) & 0xffffff;
  17491. var baseDataOffsetPresent = (tfhdFlags & 0x000001) !== 0;
  17492. var sampleDescriptionIndexPresent = (tfhdFlags & 0x000002) !== 0;
  17493. var defaultSampleDurationPresent = (tfhdFlags & 0x000008) !== 0;
  17494. var defaultSampleDuration = 0;
  17495. var defaultSampleSizePresent = (tfhdFlags & 0x000010) !== 0;
  17496. var defaultSampleSize = 0;
  17497. var defaultSampleFlagsPresent = (tfhdFlags & 0x000020) !== 0;
  17498. var tfhdOffset = 8;
  17499. if (id === trackId) {
  17500. if (baseDataOffsetPresent) {
  17501. tfhdOffset += 8;
  17502. }
  17503. if (sampleDescriptionIndexPresent) {
  17504. tfhdOffset += 4;
  17505. }
  17506. if (defaultSampleDurationPresent) {
  17507. defaultSampleDuration = readUint32(tfhd, tfhdOffset);
  17508. tfhdOffset += 4;
  17509. }
  17510. if (defaultSampleSizePresent) {
  17511. defaultSampleSize = readUint32(tfhd, tfhdOffset);
  17512. tfhdOffset += 4;
  17513. }
  17514. if (defaultSampleFlagsPresent) {
  17515. tfhdOffset += 4;
  17516. }
  17517. if (track.type === 'video') {
  17518. isHEVCFlavor = isHEVC(track.codec);
  17519. }
  17520. findBox(traf, ['trun']).map(function (trun) {
  17521. var version = trun[0];
  17522. var flags = readUint32(trun, 0) & 0xffffff;
  17523. var dataOffsetPresent = (flags & 0x000001) !== 0;
  17524. var dataOffset = 0;
  17525. var firstSampleFlagsPresent = (flags & 0x000004) !== 0;
  17526. var sampleDurationPresent = (flags & 0x000100) !== 0;
  17527. var sampleDuration = 0;
  17528. var sampleSizePresent = (flags & 0x000200) !== 0;
  17529. var sampleSize = 0;
  17530. var sampleFlagsPresent = (flags & 0x000400) !== 0;
  17531. var sampleCompositionOffsetsPresent = (flags & 0x000800) !== 0;
  17532. var compositionOffset = 0;
  17533. var sampleCount = readUint32(trun, 4);
  17534. var trunOffset = 8; // past version, flags, and sample count
  17535. if (dataOffsetPresent) {
  17536. dataOffset = readUint32(trun, trunOffset);
  17537. trunOffset += 4;
  17538. }
  17539. if (firstSampleFlagsPresent) {
  17540. trunOffset += 4;
  17541. }
  17542. var sampleOffset = dataOffset + moofOffset;
  17543. for (var ix = 0; ix < sampleCount; ix++) {
  17544. if (sampleDurationPresent) {
  17545. sampleDuration = readUint32(trun, trunOffset);
  17546. trunOffset += 4;
  17547. } else {
  17548. sampleDuration = defaultSampleDuration;
  17549. }
  17550. if (sampleSizePresent) {
  17551. sampleSize = readUint32(trun, trunOffset);
  17552. trunOffset += 4;
  17553. } else {
  17554. sampleSize = defaultSampleSize;
  17555. }
  17556. if (sampleFlagsPresent) {
  17557. trunOffset += 4;
  17558. }
  17559. if (sampleCompositionOffsetsPresent) {
  17560. if (version === 0) {
  17561. compositionOffset = readUint32(trun, trunOffset);
  17562. } else {
  17563. compositionOffset = readSint32(trun, trunOffset);
  17564. }
  17565. trunOffset += 4;
  17566. }
  17567. if (track.type === _loader_fragment__WEBPACK_IMPORTED_MODULE_1__.ElementaryStreamTypes.VIDEO) {
  17568. var naluTotalSize = 0;
  17569. while (naluTotalSize < sampleSize) {
  17570. var naluSize = readUint32(videoData, sampleOffset);
  17571. sampleOffset += 4;
  17572. if (isSEIMessage(isHEVCFlavor, videoData[sampleOffset])) {
  17573. var data = videoData.subarray(sampleOffset, sampleOffset + naluSize);
  17574. parseSEIMessageFromNALu(data, isHEVCFlavor ? 2 : 1, timeOffset + compositionOffset / timescale, seiSamples);
  17575. }
  17576. sampleOffset += naluSize;
  17577. naluTotalSize += naluSize + 4;
  17578. }
  17579. }
  17580. timeOffset += sampleDuration / timescale;
  17581. }
  17582. });
  17583. }
  17584. });
  17585. });
  17586. });
  17587. return seiSamples;
  17588. }
  17589. function isHEVC(codec) {
  17590. if (!codec) {
  17591. return false;
  17592. }
  17593. var delimit = codec.indexOf('.');
  17594. var baseCodec = delimit < 0 ? codec : codec.substring(0, delimit);
  17595. return baseCodec === 'hvc1' || baseCodec === 'hev1' ||
  17596. // Dolby Vision
  17597. baseCodec === 'dvh1' || baseCodec === 'dvhe';
  17598. }
  17599. function isSEIMessage(isHEVCFlavor, naluHeader) {
  17600. if (isHEVCFlavor) {
  17601. var naluType = naluHeader >> 1 & 0x3f;
  17602. return naluType === 39 || naluType === 40;
  17603. } else {
  17604. var _naluType = naluHeader & 0x1f;
  17605. return _naluType === 6;
  17606. }
  17607. }
  17608. function parseSEIMessageFromNALu(unescapedData, headerSize, pts, samples) {
  17609. var data = discardEPB(unescapedData);
  17610. var seiPtr = 0;
  17611. // skip nal header
  17612. seiPtr += headerSize;
  17613. var payloadType = 0;
  17614. var payloadSize = 0;
  17615. var endOfCaptions = false;
  17616. var b = 0;
  17617. while (seiPtr < data.length) {
  17618. payloadType = 0;
  17619. do {
  17620. if (seiPtr >= data.length) {
  17621. break;
  17622. }
  17623. b = data[seiPtr++];
  17624. payloadType += b;
  17625. } while (b === 0xff);
  17626. // Parse payload size.
  17627. payloadSize = 0;
  17628. do {
  17629. if (seiPtr >= data.length) {
  17630. break;
  17631. }
  17632. b = data[seiPtr++];
  17633. payloadSize += b;
  17634. } while (b === 0xff);
  17635. var leftOver = data.length - seiPtr;
  17636. if (!endOfCaptions && payloadType === 4 && seiPtr < data.length) {
  17637. endOfCaptions = true;
  17638. var countryCode = data[seiPtr++];
  17639. if (countryCode === 181) {
  17640. var providerCode = readUint16(data, seiPtr);
  17641. seiPtr += 2;
  17642. if (providerCode === 49) {
  17643. var userStructure = readUint32(data, seiPtr);
  17644. seiPtr += 4;
  17645. if (userStructure === 0x47413934) {
  17646. var userDataType = data[seiPtr++];
  17647. // Raw CEA-608 bytes wrapped in CEA-708 packet
  17648. if (userDataType === 3) {
  17649. var firstByte = data[seiPtr++];
  17650. var totalCCs = 0x1f & firstByte;
  17651. var enabled = 0x40 & firstByte;
  17652. var totalBytes = enabled ? 2 + totalCCs * 3 : 0;
  17653. var byteArray = new Uint8Array(totalBytes);
  17654. if (enabled) {
  17655. byteArray[0] = firstByte;
  17656. for (var i = 1; i < totalBytes; i++) {
  17657. byteArray[i] = data[seiPtr++];
  17658. }
  17659. }
  17660. samples.push({
  17661. type: userDataType,
  17662. payloadType: payloadType,
  17663. pts: pts,
  17664. bytes: byteArray
  17665. });
  17666. }
  17667. }
  17668. }
  17669. }
  17670. } else if (payloadType === 5 && payloadSize < leftOver) {
  17671. endOfCaptions = true;
  17672. if (payloadSize > 16) {
  17673. var uuidStrArray = [];
  17674. for (var _i2 = 0; _i2 < 16; _i2++) {
  17675. var _b = data[seiPtr++].toString(16);
  17676. uuidStrArray.push(_b.length == 1 ? '0' + _b : _b);
  17677. if (_i2 === 3 || _i2 === 5 || _i2 === 7 || _i2 === 9) {
  17678. uuidStrArray.push('-');
  17679. }
  17680. }
  17681. var length = payloadSize - 16;
  17682. var userDataBytes = new Uint8Array(length);
  17683. for (var _i3 = 0; _i3 < length; _i3++) {
  17684. userDataBytes[_i3] = data[seiPtr++];
  17685. }
  17686. samples.push({
  17687. payloadType: payloadType,
  17688. pts: pts,
  17689. uuid: uuidStrArray.join(''),
  17690. userData: (0,_demux_id3__WEBPACK_IMPORTED_MODULE_2__.utf8ArrayToStr)(userDataBytes),
  17691. userDataBytes: userDataBytes
  17692. });
  17693. }
  17694. } else if (payloadSize < leftOver) {
  17695. seiPtr += payloadSize;
  17696. } else if (payloadSize > leftOver) {
  17697. break;
  17698. }
  17699. }
  17700. }
  17701. /**
  17702. * remove Emulation Prevention bytes from a RBSP
  17703. */
  17704. function discardEPB(data) {
  17705. var length = data.byteLength;
  17706. var EPBPositions = [];
  17707. var i = 1;
  17708. // Find all `Emulation Prevention Bytes`
  17709. while (i < length - 2) {
  17710. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  17711. EPBPositions.push(i + 2);
  17712. i += 2;
  17713. } else {
  17714. i++;
  17715. }
  17716. }
  17717. // If no Emulation Prevention Bytes were found just return the original
  17718. // array
  17719. if (EPBPositions.length === 0) {
  17720. return data;
  17721. }
  17722. // Create a new array to hold the NAL unit data
  17723. var newLength = length - EPBPositions.length;
  17724. var newData = new Uint8Array(newLength);
  17725. var sourceIndex = 0;
  17726. for (i = 0; i < newLength; sourceIndex++, i++) {
  17727. if (sourceIndex === EPBPositions[0]) {
  17728. // Skip this byte
  17729. sourceIndex++;
  17730. // Remove this position index
  17731. EPBPositions.shift();
  17732. }
  17733. newData[i] = data[sourceIndex];
  17734. }
  17735. return newData;
  17736. }
  17737. function parseEmsg(data) {
  17738. var version = data[0];
  17739. var schemeIdUri = '';
  17740. var value = '';
  17741. var timeScale = 0;
  17742. var presentationTimeDelta = 0;
  17743. var presentationTime = 0;
  17744. var eventDuration = 0;
  17745. var id = 0;
  17746. var offset = 0;
  17747. if (version === 0) {
  17748. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  17749. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  17750. offset += 1;
  17751. }
  17752. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  17753. offset += 1;
  17754. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  17755. value += bin2str(data.subarray(offset, offset + 1));
  17756. offset += 1;
  17757. }
  17758. value += bin2str(data.subarray(offset, offset + 1));
  17759. offset += 1;
  17760. timeScale = readUint32(data, 12);
  17761. presentationTimeDelta = readUint32(data, 16);
  17762. eventDuration = readUint32(data, 20);
  17763. id = readUint32(data, 24);
  17764. offset = 28;
  17765. } else if (version === 1) {
  17766. offset += 4;
  17767. timeScale = readUint32(data, offset);
  17768. offset += 4;
  17769. var leftPresentationTime = readUint32(data, offset);
  17770. offset += 4;
  17771. var rightPresentationTime = readUint32(data, offset);
  17772. offset += 4;
  17773. presentationTime = Math.pow(2, 32) * leftPresentationTime + rightPresentationTime;
  17774. if (!Number.isSafeInteger(presentationTime)) {
  17775. presentationTime = Number.MAX_SAFE_INTEGER;
  17776. // eslint-disable-next-line no-console
  17777. console.warn('Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box');
  17778. }
  17779. eventDuration = readUint32(data, offset);
  17780. offset += 4;
  17781. id = readUint32(data, offset);
  17782. offset += 4;
  17783. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  17784. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  17785. offset += 1;
  17786. }
  17787. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  17788. offset += 1;
  17789. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  17790. value += bin2str(data.subarray(offset, offset + 1));
  17791. offset += 1;
  17792. }
  17793. value += bin2str(data.subarray(offset, offset + 1));
  17794. offset += 1;
  17795. }
  17796. var payload = data.subarray(offset, data.byteLength);
  17797. return {
  17798. schemeIdUri: schemeIdUri,
  17799. value: value,
  17800. timeScale: timeScale,
  17801. presentationTime: presentationTime,
  17802. presentationTimeDelta: presentationTimeDelta,
  17803. eventDuration: eventDuration,
  17804. id: id,
  17805. payload: payload
  17806. };
  17807. }
  17808. /***/ }),
  17809. /***/ "./src/utils/texttrack-utils.ts":
  17810. /*!**************************************!*\
  17811. !*** ./src/utils/texttrack-utils.ts ***!
  17812. \**************************************/
  17813. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  17814. "use strict";
  17815. __webpack_require__.r(__webpack_exports__);
  17816. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  17817. /* harmony export */ "addCueToTrack": () => (/* binding */ addCueToTrack),
  17818. /* harmony export */ "clearCurrentCues": () => (/* binding */ clearCurrentCues),
  17819. /* harmony export */ "getCuesInRange": () => (/* binding */ getCuesInRange),
  17820. /* harmony export */ "removeCuesInRange": () => (/* binding */ removeCuesInRange),
  17821. /* harmony export */ "sendAddTrackEvent": () => (/* binding */ sendAddTrackEvent)
  17822. /* harmony export */ });
  17823. /* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./logger */ "./src/utils/logger.ts");
  17824. function sendAddTrackEvent(track, videoEl) {
  17825. var event;
  17826. try {
  17827. event = new Event('addtrack');
  17828. } catch (err) {
  17829. // for IE11
  17830. event = document.createEvent('Event');
  17831. event.initEvent('addtrack', false, false);
  17832. }
  17833. event.track = track;
  17834. videoEl.dispatchEvent(event);
  17835. }
  17836. function addCueToTrack(track, cue) {
  17837. // Sometimes there are cue overlaps on segmented vtts so the same
  17838. // cue can appear more than once in different vtt files.
  17839. // This avoid showing duplicated cues with same timecode and text.
  17840. var mode = track.mode;
  17841. if (mode === 'disabled') {
  17842. track.mode = 'hidden';
  17843. }
  17844. if (track.cues && !track.cues.getCueById(cue.id)) {
  17845. try {
  17846. track.addCue(cue);
  17847. if (!track.cues.getCueById(cue.id)) {
  17848. throw new Error("addCue is failed for: " + cue);
  17849. }
  17850. } catch (err) {
  17851. _logger__WEBPACK_IMPORTED_MODULE_0__.logger.debug("[texttrack-utils]: " + err);
  17852. var textTrackCue = new self.TextTrackCue(cue.startTime, cue.endTime, cue.text);
  17853. textTrackCue.id = cue.id;
  17854. track.addCue(textTrackCue);
  17855. }
  17856. }
  17857. if (mode === 'disabled') {
  17858. track.mode = mode;
  17859. }
  17860. }
  17861. function clearCurrentCues(track) {
  17862. // When track.mode is disabled, track.cues will be null.
  17863. // To guarantee the removal of cues, we need to temporarily
  17864. // change the mode to hidden
  17865. var mode = track.mode;
  17866. if (mode === 'disabled') {
  17867. track.mode = 'hidden';
  17868. }
  17869. if (track.cues) {
  17870. for (var i = track.cues.length; i--;) {
  17871. track.removeCue(track.cues[i]);
  17872. }
  17873. }
  17874. if (mode === 'disabled') {
  17875. track.mode = mode;
  17876. }
  17877. }
  17878. function removeCuesInRange(track, start, end, predicate) {
  17879. var mode = track.mode;
  17880. if (mode === 'disabled') {
  17881. track.mode = 'hidden';
  17882. }
  17883. if (track.cues && track.cues.length > 0) {
  17884. var cues = getCuesInRange(track.cues, start, end);
  17885. for (var i = 0; i < cues.length; i++) {
  17886. if (!predicate || predicate(cues[i])) {
  17887. track.removeCue(cues[i]);
  17888. }
  17889. }
  17890. }
  17891. if (mode === 'disabled') {
  17892. track.mode = mode;
  17893. }
  17894. }
  17895. // Find first cue starting after given time.
  17896. // Modified version of binary search O(log(n)).
  17897. function getFirstCueIndexAfterTime(cues, time) {
  17898. // If first cue starts after time, start there
  17899. if (time < cues[0].startTime) {
  17900. return 0;
  17901. }
  17902. // If the last cue ends before time there is no overlap
  17903. var len = cues.length - 1;
  17904. if (time > cues[len].endTime) {
  17905. return -1;
  17906. }
  17907. var left = 0;
  17908. var right = len;
  17909. while (left <= right) {
  17910. var mid = Math.floor((right + left) / 2);
  17911. if (time < cues[mid].startTime) {
  17912. right = mid - 1;
  17913. } else if (time > cues[mid].startTime && left < len) {
  17914. left = mid + 1;
  17915. } else {
  17916. // If it's not lower or higher, it must be equal.
  17917. return mid;
  17918. }
  17919. }
  17920. // At this point, left and right have swapped.
  17921. // No direct match was found, left or right element must be the closest. Check which one has the smallest diff.
  17922. return cues[left].startTime - time < time - cues[right].startTime ? left : right;
  17923. }
  17924. function getCuesInRange(cues, start, end) {
  17925. var cuesFound = [];
  17926. var firstCueInRange = getFirstCueIndexAfterTime(cues, start);
  17927. if (firstCueInRange > -1) {
  17928. for (var i = firstCueInRange, len = cues.length; i < len; i++) {
  17929. var _cue = cues[i];
  17930. if (_cue.startTime >= start && _cue.endTime <= end) {
  17931. cuesFound.push(_cue);
  17932. } else if (_cue.startTime > end) {
  17933. return cuesFound;
  17934. }
  17935. }
  17936. }
  17937. return cuesFound;
  17938. }
  17939. /***/ }),
  17940. /***/ "./src/utils/time-ranges.ts":
  17941. /*!**********************************!*\
  17942. !*** ./src/utils/time-ranges.ts ***!
  17943. \**********************************/
  17944. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  17945. "use strict";
  17946. __webpack_require__.r(__webpack_exports__);
  17947. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  17948. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  17949. /* harmony export */ });
  17950. /**
  17951. * TimeRanges to string helper
  17952. */
  17953. var TimeRanges = {
  17954. toString: function toString(r) {
  17955. var log = '';
  17956. var len = r.length;
  17957. for (var i = 0; i < len; i++) {
  17958. log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']';
  17959. }
  17960. return log;
  17961. }
  17962. };
  17963. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (TimeRanges);
  17964. /***/ }),
  17965. /***/ "./src/utils/timescale-conversion.ts":
  17966. /*!*******************************************!*\
  17967. !*** ./src/utils/timescale-conversion.ts ***!
  17968. \*******************************************/
  17969. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  17970. "use strict";
  17971. __webpack_require__.r(__webpack_exports__);
  17972. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  17973. /* harmony export */ "toMpegTsClockFromTimescale": () => (/* binding */ toMpegTsClockFromTimescale),
  17974. /* harmony export */ "toMsFromMpegTsClock": () => (/* binding */ toMsFromMpegTsClock),
  17975. /* harmony export */ "toTimescaleFromBase": () => (/* binding */ toTimescaleFromBase),
  17976. /* harmony export */ "toTimescaleFromScale": () => (/* binding */ toTimescaleFromScale)
  17977. /* harmony export */ });
  17978. var MPEG_TS_CLOCK_FREQ_HZ = 90000;
  17979. function toTimescaleFromBase(value, destScale, srcBase, round) {
  17980. if (srcBase === void 0) {
  17981. srcBase = 1;
  17982. }
  17983. if (round === void 0) {
  17984. round = false;
  17985. }
  17986. var result = value * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)`
  17987. return round ? Math.round(result) : result;
  17988. }
  17989. function toTimescaleFromScale(value, destScale, srcScale, round) {
  17990. if (srcScale === void 0) {
  17991. srcScale = 1;
  17992. }
  17993. if (round === void 0) {
  17994. round = false;
  17995. }
  17996. return toTimescaleFromBase(value, destScale, 1 / srcScale, round);
  17997. }
  17998. function toMsFromMpegTsClock(value, round) {
  17999. if (round === void 0) {
  18000. round = false;
  18001. }
  18002. return toTimescaleFromBase(value, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);
  18003. }
  18004. function toMpegTsClockFromTimescale(value, srcScale) {
  18005. if (srcScale === void 0) {
  18006. srcScale = 1;
  18007. }
  18008. return toTimescaleFromBase(value, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);
  18009. }
  18010. /***/ }),
  18011. /***/ "./src/utils/typed-array.ts":
  18012. /*!**********************************!*\
  18013. !*** ./src/utils/typed-array.ts ***!
  18014. \**********************************/
  18015. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  18016. "use strict";
  18017. __webpack_require__.r(__webpack_exports__);
  18018. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  18019. /* harmony export */ "sliceUint8": () => (/* binding */ sliceUint8)
  18020. /* harmony export */ });
  18021. function sliceUint8(array, start, end) {
  18022. // @ts-expect-error This polyfills IE11 usage of Uint8Array slice.
  18023. // It always exists in the TypeScript definition so fails, but it fails at runtime on IE11.
  18024. return Uint8Array.prototype.slice ? array.slice(start, end) : new Uint8Array(Array.prototype.slice.call(array, start, end));
  18025. }
  18026. /***/ }),
  18027. /***/ "./src/utils/xhr-loader.ts":
  18028. /*!*********************************!*\
  18029. !*** ./src/utils/xhr-loader.ts ***!
  18030. \*********************************/
  18031. /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
  18032. "use strict";
  18033. __webpack_require__.r(__webpack_exports__);
  18034. /* harmony export */ __webpack_require__.d(__webpack_exports__, {
  18035. /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
  18036. /* harmony export */ });
  18037. /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
  18038. /* harmony import */ var _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loader/load-stats */ "./src/loader/load-stats.ts");
  18039. var AGE_HEADER_LINE_REGEX = /^age:\s*[\d.]+\s*$/m;
  18040. var XhrLoader = /*#__PURE__*/function () {
  18041. function XhrLoader(config /* HlsConfig */) {
  18042. this.xhrSetup = void 0;
  18043. this.requestTimeout = void 0;
  18044. this.retryTimeout = void 0;
  18045. this.retryDelay = void 0;
  18046. this.config = null;
  18047. this.callbacks = null;
  18048. this.context = void 0;
  18049. this.loader = null;
  18050. this.stats = void 0;
  18051. this.xhrSetup = config ? config.xhrSetup : null;
  18052. this.stats = new _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__.LoadStats();
  18053. this.retryDelay = 0;
  18054. }
  18055. var _proto = XhrLoader.prototype;
  18056. _proto.destroy = function destroy() {
  18057. this.callbacks = null;
  18058. this.abortInternal();
  18059. this.loader = null;
  18060. this.config = null;
  18061. };
  18062. _proto.abortInternal = function abortInternal() {
  18063. var loader = this.loader;
  18064. self.clearTimeout(this.requestTimeout);
  18065. self.clearTimeout(this.retryTimeout);
  18066. if (loader) {
  18067. loader.onreadystatechange = null;
  18068. loader.onprogress = null;
  18069. if (loader.readyState !== 4) {
  18070. this.stats.aborted = true;
  18071. loader.abort();
  18072. }
  18073. }
  18074. };
  18075. _proto.abort = function abort() {
  18076. var _this$callbacks;
  18077. this.abortInternal();
  18078. if ((_this$callbacks = this.callbacks) !== null && _this$callbacks !== void 0 && _this$callbacks.onAbort) {
  18079. this.callbacks.onAbort(this.stats, this.context, this.loader);
  18080. }
  18081. };
  18082. _proto.load = function load(context, config, callbacks) {
  18083. if (this.stats.loading.start) {
  18084. throw new Error('Loader can only be used once.');
  18085. }
  18086. this.stats.loading.start = self.performance.now();
  18087. this.context = context;
  18088. this.config = config;
  18089. this.callbacks = callbacks;
  18090. this.retryDelay = config.retryDelay;
  18091. this.loadInternal();
  18092. };
  18093. _proto.loadInternal = function loadInternal() {
  18094. var config = this.config,
  18095. context = this.context;
  18096. if (!config) {
  18097. return;
  18098. }
  18099. var xhr = this.loader = new self.XMLHttpRequest();
  18100. var stats = this.stats;
  18101. stats.loading.first = 0;
  18102. stats.loaded = 0;
  18103. var xhrSetup = this.xhrSetup;
  18104. try {
  18105. if (xhrSetup) {
  18106. try {
  18107. xhrSetup(xhr, context.url);
  18108. } catch (e) {
  18109. // fix xhrSetup: (xhr, url) => {xhr.setRequestHeader("Content-Language", "test");}
  18110. // not working, as xhr.setRequestHeader expects xhr.readyState === OPEN
  18111. xhr.open('GET', context.url, true);
  18112. xhrSetup(xhr, context.url);
  18113. }
  18114. }
  18115. if (!xhr.readyState) {
  18116. xhr.open('GET', context.url, true);
  18117. }
  18118. var headers = this.context.headers;
  18119. if (headers) {
  18120. for (var header in headers) {
  18121. xhr.setRequestHeader(header, headers[header]);
  18122. }
  18123. }
  18124. } catch (e) {
  18125. // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
  18126. this.callbacks.onError({
  18127. code: xhr.status,
  18128. text: e.message
  18129. }, context, xhr);
  18130. return;
  18131. }
  18132. if (context.rangeEnd) {
  18133. xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));
  18134. }
  18135. xhr.onreadystatechange = this.readystatechange.bind(this);
  18136. xhr.onprogress = this.loadprogress.bind(this);
  18137. xhr.responseType = context.responseType;
  18138. // setup timeout before we perform request
  18139. self.clearTimeout(this.requestTimeout);
  18140. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);
  18141. xhr.send();
  18142. };
  18143. _proto.readystatechange = function readystatechange() {
  18144. var context = this.context,
  18145. xhr = this.loader,
  18146. stats = this.stats;
  18147. if (!context || !xhr) {
  18148. return;
  18149. }
  18150. var readyState = xhr.readyState;
  18151. var config = this.config;
  18152. // don't proceed if xhr has been aborted
  18153. if (stats.aborted) {
  18154. return;
  18155. }
  18156. // >= HEADERS_RECEIVED
  18157. if (readyState >= 2) {
  18158. // clear xhr timeout and rearm it if readyState less than 4
  18159. self.clearTimeout(this.requestTimeout);
  18160. if (stats.loading.first === 0) {
  18161. stats.loading.first = Math.max(self.performance.now(), stats.loading.start);
  18162. }
  18163. if (readyState === 4) {
  18164. xhr.onreadystatechange = null;
  18165. xhr.onprogress = null;
  18166. var status = xhr.status;
  18167. // http status between 200 to 299 are all successful
  18168. var isArrayBuffer = xhr.responseType === 'arraybuffer';
  18169. if (status >= 200 && status < 300 && (isArrayBuffer && xhr.response || xhr.responseText !== null)) {
  18170. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  18171. var data;
  18172. var len;
  18173. if (isArrayBuffer) {
  18174. data = xhr.response;
  18175. len = data.byteLength;
  18176. } else {
  18177. data = xhr.responseText;
  18178. len = data.length;
  18179. }
  18180. stats.loaded = stats.total = len;
  18181. if (!this.callbacks) {
  18182. return;
  18183. }
  18184. var onProgress = this.callbacks.onProgress;
  18185. if (onProgress) {
  18186. onProgress(stats, context, data, xhr);
  18187. }
  18188. if (!this.callbacks) {
  18189. return;
  18190. }
  18191. var response = {
  18192. url: xhr.responseURL,
  18193. data: data
  18194. };
  18195. this.callbacks.onSuccess(response, stats, context, xhr);
  18196. } else {
  18197. // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error
  18198. if (stats.retry >= config.maxRetry || status >= 400 && status < 499) {
  18199. _utils_logger__WEBPACK_IMPORTED_MODULE_0__.logger.error(status + " while loading " + context.url);
  18200. this.callbacks.onError({
  18201. code: status,
  18202. text: xhr.statusText
  18203. }, context, xhr);
  18204. } else {
  18205. // retry
  18206. _utils_logger__WEBPACK_IMPORTED_MODULE_0__.logger.warn(status + " while loading " + context.url + ", retrying in " + this.retryDelay + "...");
  18207. // abort and reset internal state
  18208. this.abortInternal();
  18209. this.loader = null;
  18210. // schedule retry
  18211. self.clearTimeout(this.retryTimeout);
  18212. this.retryTimeout = self.setTimeout(this.loadInternal.bind(this), this.retryDelay);
  18213. // set exponential backoff
  18214. this.retryDelay = Math.min(2 * this.retryDelay, config.maxRetryDelay);
  18215. stats.retry++;
  18216. }
  18217. }
  18218. } else {
  18219. // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet
  18220. self.clearTimeout(this.requestTimeout);
  18221. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);
  18222. }
  18223. }
  18224. };
  18225. _proto.loadtimeout = function loadtimeout() {
  18226. _utils_logger__WEBPACK_IMPORTED_MODULE_0__.logger.warn("timeout while loading " + this.context.url);
  18227. var callbacks = this.callbacks;
  18228. if (callbacks) {
  18229. this.abortInternal();
  18230. callbacks.onTimeout(this.stats, this.context, this.loader);
  18231. }
  18232. };
  18233. _proto.loadprogress = function loadprogress(event) {
  18234. var stats = this.stats;
  18235. stats.loaded = event.loaded;
  18236. if (event.lengthComputable) {
  18237. stats.total = event.total;
  18238. }
  18239. };
  18240. _proto.getCacheAge = function getCacheAge() {
  18241. var result = null;
  18242. if (this.loader && AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())) {
  18243. var ageHeader = this.loader.getResponseHeader('age');
  18244. result = ageHeader ? parseFloat(ageHeader) : null;
  18245. }
  18246. return result;
  18247. };
  18248. return XhrLoader;
  18249. }();
  18250. /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (XhrLoader);
  18251. /***/ }),
  18252. /***/ "./node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js":
  18253. /*!************************************************************************************!*\
  18254. !*** ./node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js ***!
  18255. \************************************************************************************/
  18256. /***/ ((module) => {
  18257. "use strict";
  18258. var has = Object.prototype.hasOwnProperty
  18259. , prefix = '~';
  18260. /**
  18261. * Constructor to create a storage for our `EE` objects.
  18262. * An `Events` instance is a plain object whose properties are event names.
  18263. *
  18264. * @constructor
  18265. * @private
  18266. */
  18267. function Events() {}
  18268. //
  18269. // We try to not inherit from `Object.prototype`. In some engines creating an
  18270. // instance in this way is faster than calling `Object.create(null)` directly.
  18271. // If `Object.create(null)` is not supported we prefix the event names with a
  18272. // character to make sure that the built-in object properties are not
  18273. // overridden or used as an attack vector.
  18274. //
  18275. if (Object.create) {
  18276. Events.prototype = Object.create(null);
  18277. //
  18278. // This hack is needed because the `__proto__` property is still inherited in
  18279. // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  18280. //
  18281. if (!new Events().__proto__) prefix = false;
  18282. }
  18283. /**
  18284. * Representation of a single event listener.
  18285. *
  18286. * @param {Function} fn The listener function.
  18287. * @param {*} context The context to invoke the listener with.
  18288. * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
  18289. * @constructor
  18290. * @private
  18291. */
  18292. function EE(fn, context, once) {
  18293. this.fn = fn;
  18294. this.context = context;
  18295. this.once = once || false;
  18296. }
  18297. /**
  18298. * Add a listener for a given event.
  18299. *
  18300. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  18301. * @param {(String|Symbol)} event The event name.
  18302. * @param {Function} fn The listener function.
  18303. * @param {*} context The context to invoke the listener with.
  18304. * @param {Boolean} once Specify if the listener is a one-time listener.
  18305. * @returns {EventEmitter}
  18306. * @private
  18307. */
  18308. function addListener(emitter, event, fn, context, once) {
  18309. if (typeof fn !== 'function') {
  18310. throw new TypeError('The listener must be a function');
  18311. }
  18312. var listener = new EE(fn, context || emitter, once)
  18313. , evt = prefix ? prefix + event : event;
  18314. if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
  18315. else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
  18316. else emitter._events[evt] = [emitter._events[evt], listener];
  18317. return emitter;
  18318. }
  18319. /**
  18320. * Clear event by name.
  18321. *
  18322. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  18323. * @param {(String|Symbol)} evt The Event name.
  18324. * @private
  18325. */
  18326. function clearEvent(emitter, evt) {
  18327. if (--emitter._eventsCount === 0) emitter._events = new Events();
  18328. else delete emitter._events[evt];
  18329. }
  18330. /**
  18331. * Minimal `EventEmitter` interface that is molded against the Node.js
  18332. * `EventEmitter` interface.
  18333. *
  18334. * @constructor
  18335. * @public
  18336. */
  18337. function EventEmitter() {
  18338. this._events = new Events();
  18339. this._eventsCount = 0;
  18340. }
  18341. /**
  18342. * Return an array listing the events for which the emitter has registered
  18343. * listeners.
  18344. *
  18345. * @returns {Array}
  18346. * @public
  18347. */
  18348. EventEmitter.prototype.eventNames = function eventNames() {
  18349. var names = []
  18350. , events
  18351. , name;
  18352. if (this._eventsCount === 0) return names;
  18353. for (name in (events = this._events)) {
  18354. if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
  18355. }
  18356. if (Object.getOwnPropertySymbols) {
  18357. return names.concat(Object.getOwnPropertySymbols(events));
  18358. }
  18359. return names;
  18360. };
  18361. /**
  18362. * Return the listeners registered for a given event.
  18363. *
  18364. * @param {(String|Symbol)} event The event name.
  18365. * @returns {Array} The registered listeners.
  18366. * @public
  18367. */
  18368. EventEmitter.prototype.listeners = function listeners(event) {
  18369. var evt = prefix ? prefix + event : event
  18370. , handlers = this._events[evt];
  18371. if (!handlers) return [];
  18372. if (handlers.fn) return [handlers.fn];
  18373. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  18374. ee[i] = handlers[i].fn;
  18375. }
  18376. return ee;
  18377. };
  18378. /**
  18379. * Return the number of listeners listening to a given event.
  18380. *
  18381. * @param {(String|Symbol)} event The event name.
  18382. * @returns {Number} The number of listeners.
  18383. * @public
  18384. */
  18385. EventEmitter.prototype.listenerCount = function listenerCount(event) {
  18386. var evt = prefix ? prefix + event : event
  18387. , listeners = this._events[evt];
  18388. if (!listeners) return 0;
  18389. if (listeners.fn) return 1;
  18390. return listeners.length;
  18391. };
  18392. /**
  18393. * Calls each of the listeners registered for a given event.
  18394. *
  18395. * @param {(String|Symbol)} event The event name.
  18396. * @returns {Boolean} `true` if the event had listeners, else `false`.
  18397. * @public
  18398. */
  18399. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  18400. var evt = prefix ? prefix + event : event;
  18401. if (!this._events[evt]) return false;
  18402. var listeners = this._events[evt]
  18403. , len = arguments.length
  18404. , args
  18405. , i;
  18406. if (listeners.fn) {
  18407. if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  18408. switch (len) {
  18409. case 1: return listeners.fn.call(listeners.context), true;
  18410. case 2: return listeners.fn.call(listeners.context, a1), true;
  18411. case 3: return listeners.fn.call(listeners.context, a1, a2), true;
  18412. case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
  18413. case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  18414. case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  18415. }
  18416. for (i = 1, args = new Array(len -1); i < len; i++) {
  18417. args[i - 1] = arguments[i];
  18418. }
  18419. listeners.fn.apply(listeners.context, args);
  18420. } else {
  18421. var length = listeners.length
  18422. , j;
  18423. for (i = 0; i < length; i++) {
  18424. if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  18425. switch (len) {
  18426. case 1: listeners[i].fn.call(listeners[i].context); break;
  18427. case 2: listeners[i].fn.call(listeners[i].context, a1); break;
  18428. case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
  18429. case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
  18430. default:
  18431. if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
  18432. args[j - 1] = arguments[j];
  18433. }
  18434. listeners[i].fn.apply(listeners[i].context, args);
  18435. }
  18436. }
  18437. }
  18438. return true;
  18439. };
  18440. /**
  18441. * Add a listener for a given event.
  18442. *
  18443. * @param {(String|Symbol)} event The event name.
  18444. * @param {Function} fn The listener function.
  18445. * @param {*} [context=this] The context to invoke the listener with.
  18446. * @returns {EventEmitter} `this`.
  18447. * @public
  18448. */
  18449. EventEmitter.prototype.on = function on(event, fn, context) {
  18450. return addListener(this, event, fn, context, false);
  18451. };
  18452. /**
  18453. * Add a one-time listener for a given event.
  18454. *
  18455. * @param {(String|Symbol)} event The event name.
  18456. * @param {Function} fn The listener function.
  18457. * @param {*} [context=this] The context to invoke the listener with.
  18458. * @returns {EventEmitter} `this`.
  18459. * @public
  18460. */
  18461. EventEmitter.prototype.once = function once(event, fn, context) {
  18462. return addListener(this, event, fn, context, true);
  18463. };
  18464. /**
  18465. * Remove the listeners of a given event.
  18466. *
  18467. * @param {(String|Symbol)} event The event name.
  18468. * @param {Function} fn Only remove the listeners that match this function.
  18469. * @param {*} context Only remove the listeners that have this context.
  18470. * @param {Boolean} once Only remove one-time listeners.
  18471. * @returns {EventEmitter} `this`.
  18472. * @public
  18473. */
  18474. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  18475. var evt = prefix ? prefix + event : event;
  18476. if (!this._events[evt]) return this;
  18477. if (!fn) {
  18478. clearEvent(this, evt);
  18479. return this;
  18480. }
  18481. var listeners = this._events[evt];
  18482. if (listeners.fn) {
  18483. if (
  18484. listeners.fn === fn &&
  18485. (!once || listeners.once) &&
  18486. (!context || listeners.context === context)
  18487. ) {
  18488. clearEvent(this, evt);
  18489. }
  18490. } else {
  18491. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  18492. if (
  18493. listeners[i].fn !== fn ||
  18494. (once && !listeners[i].once) ||
  18495. (context && listeners[i].context !== context)
  18496. ) {
  18497. events.push(listeners[i]);
  18498. }
  18499. }
  18500. //
  18501. // Reset the array, or remove it completely if we have no more listeners.
  18502. //
  18503. if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
  18504. else clearEvent(this, evt);
  18505. }
  18506. return this;
  18507. };
  18508. /**
  18509. * Remove all listeners, or those of the specified event.
  18510. *
  18511. * @param {(String|Symbol)} [event] The event name.
  18512. * @returns {EventEmitter} `this`.
  18513. * @public
  18514. */
  18515. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  18516. var evt;
  18517. if (event) {
  18518. evt = prefix ? prefix + event : event;
  18519. if (this._events[evt]) clearEvent(this, evt);
  18520. } else {
  18521. this._events = new Events();
  18522. this._eventsCount = 0;
  18523. }
  18524. return this;
  18525. };
  18526. //
  18527. // Alias methods names because people roll like that.
  18528. //
  18529. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  18530. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  18531. //
  18532. // Expose the prefix.
  18533. //
  18534. EventEmitter.prefixed = prefix;
  18535. //
  18536. // Allow `EventEmitter` to be imported as module namespace.
  18537. //
  18538. EventEmitter.EventEmitter = EventEmitter;
  18539. //
  18540. // Expose the module.
  18541. //
  18542. if (true) {
  18543. module.exports = EventEmitter;
  18544. }
  18545. /***/ }),
  18546. /***/ "./node_modules/.pnpm/url-toolkit@2.2.5/node_modules/url-toolkit/src/url-toolkit.js":
  18547. /*!******************************************************************************************!*\
  18548. !*** ./node_modules/.pnpm/url-toolkit@2.2.5/node_modules/url-toolkit/src/url-toolkit.js ***!
  18549. \******************************************************************************************/
  18550. /***/ (function(module) {
  18551. // see https://tools.ietf.org/html/rfc1808
  18552. (function (root) {
  18553. var URL_REGEX =
  18554. /^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/;
  18555. var FIRST_SEGMENT_REGEX = /^(?=([^\/?#]*))\1([^]*)$/;
  18556. var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
  18557. var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
  18558. var URLToolkit = {
  18559. // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
  18560. // E.g
  18561. // With opts.alwaysNormalize = false (default, spec compliant)
  18562. // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
  18563. // With opts.alwaysNormalize = true (not spec compliant)
  18564. // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
  18565. buildAbsoluteURL: function (baseURL, relativeURL, opts) {
  18566. opts = opts || {};
  18567. // remove any remaining space and CRLF
  18568. baseURL = baseURL.trim();
  18569. relativeURL = relativeURL.trim();
  18570. if (!relativeURL) {
  18571. // 2a) If the embedded URL is entirely empty, it inherits the
  18572. // entire base URL (i.e., is set equal to the base URL)
  18573. // and we are done.
  18574. if (!opts.alwaysNormalize) {
  18575. return baseURL;
  18576. }
  18577. var basePartsForNormalise = URLToolkit.parseURL(baseURL);
  18578. if (!basePartsForNormalise) {
  18579. throw new Error('Error trying to parse base URL.');
  18580. }
  18581. basePartsForNormalise.path = URLToolkit.normalizePath(
  18582. basePartsForNormalise.path
  18583. );
  18584. return URLToolkit.buildURLFromParts(basePartsForNormalise);
  18585. }
  18586. var relativeParts = URLToolkit.parseURL(relativeURL);
  18587. if (!relativeParts) {
  18588. throw new Error('Error trying to parse relative URL.');
  18589. }
  18590. if (relativeParts.scheme) {
  18591. // 2b) If the embedded URL starts with a scheme name, it is
  18592. // interpreted as an absolute URL and we are done.
  18593. if (!opts.alwaysNormalize) {
  18594. return relativeURL;
  18595. }
  18596. relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
  18597. return URLToolkit.buildURLFromParts(relativeParts);
  18598. }
  18599. var baseParts = URLToolkit.parseURL(baseURL);
  18600. if (!baseParts) {
  18601. throw new Error('Error trying to parse base URL.');
  18602. }
  18603. if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
  18604. // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
  18605. // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
  18606. var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
  18607. baseParts.netLoc = pathParts[1];
  18608. baseParts.path = pathParts[2];
  18609. }
  18610. if (baseParts.netLoc && !baseParts.path) {
  18611. baseParts.path = '/';
  18612. }
  18613. var builtParts = {
  18614. // 2c) Otherwise, the embedded URL inherits the scheme of
  18615. // the base URL.
  18616. scheme: baseParts.scheme,
  18617. netLoc: relativeParts.netLoc,
  18618. path: null,
  18619. params: relativeParts.params,
  18620. query: relativeParts.query,
  18621. fragment: relativeParts.fragment,
  18622. };
  18623. if (!relativeParts.netLoc) {
  18624. // 3) If the embedded URL's <net_loc> is non-empty, we skip to
  18625. // Step 7. Otherwise, the embedded URL inherits the <net_loc>
  18626. // (if any) of the base URL.
  18627. builtParts.netLoc = baseParts.netLoc;
  18628. // 4) If the embedded URL path is preceded by a slash "/", the
  18629. // path is not relative and we skip to Step 7.
  18630. if (relativeParts.path[0] !== '/') {
  18631. if (!relativeParts.path) {
  18632. // 5) If the embedded URL path is empty (and not preceded by a
  18633. // slash), then the embedded URL inherits the base URL path
  18634. builtParts.path = baseParts.path;
  18635. // 5a) if the embedded URL's <params> is non-empty, we skip to
  18636. // step 7; otherwise, it inherits the <params> of the base
  18637. // URL (if any) and
  18638. if (!relativeParts.params) {
  18639. builtParts.params = baseParts.params;
  18640. // 5b) if the embedded URL's <query> is non-empty, we skip to
  18641. // step 7; otherwise, it inherits the <query> of the base
  18642. // URL (if any) and we skip to step 7.
  18643. if (!relativeParts.query) {
  18644. builtParts.query = baseParts.query;
  18645. }
  18646. }
  18647. } else {
  18648. // 6) The last segment of the base URL's path (anything
  18649. // following the rightmost slash "/", or the entire path if no
  18650. // slash is present) is removed and the embedded URL's path is
  18651. // appended in its place.
  18652. var baseURLPath = baseParts.path;
  18653. var newPath =
  18654. baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) +
  18655. relativeParts.path;
  18656. builtParts.path = URLToolkit.normalizePath(newPath);
  18657. }
  18658. }
  18659. }
  18660. if (builtParts.path === null) {
  18661. builtParts.path = opts.alwaysNormalize
  18662. ? URLToolkit.normalizePath(relativeParts.path)
  18663. : relativeParts.path;
  18664. }
  18665. return URLToolkit.buildURLFromParts(builtParts);
  18666. },
  18667. parseURL: function (url) {
  18668. var parts = URL_REGEX.exec(url);
  18669. if (!parts) {
  18670. return null;
  18671. }
  18672. return {
  18673. scheme: parts[1] || '',
  18674. netLoc: parts[2] || '',
  18675. path: parts[3] || '',
  18676. params: parts[4] || '',
  18677. query: parts[5] || '',
  18678. fragment: parts[6] || '',
  18679. };
  18680. },
  18681. normalizePath: function (path) {
  18682. // The following operations are
  18683. // then applied, in order, to the new path:
  18684. // 6a) All occurrences of "./", where "." is a complete path
  18685. // segment, are removed.
  18686. // 6b) If the path ends with "." as a complete path segment,
  18687. // that "." is removed.
  18688. path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');
  18689. // 6c) All occurrences of "<segment>/../", where <segment> is a
  18690. // complete path segment not equal to "..", are removed.
  18691. // Removal of these path segments is performed iteratively,
  18692. // removing the leftmost matching pattern on each iteration,
  18693. // until no matching pattern remains.
  18694. // 6d) If the path ends with "<segment>/..", where <segment> is a
  18695. // complete path segment not equal to "..", that
  18696. // "<segment>/.." is removed.
  18697. while (
  18698. path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length
  18699. ) {}
  18700. return path.split('').reverse().join('');
  18701. },
  18702. buildURLFromParts: function (parts) {
  18703. return (
  18704. parts.scheme +
  18705. parts.netLoc +
  18706. parts.path +
  18707. parts.params +
  18708. parts.query +
  18709. parts.fragment
  18710. );
  18711. },
  18712. };
  18713. if (true)
  18714. module.exports = URLToolkit;
  18715. else {}
  18716. })(this);
  18717. /***/ })
  18718. /******/ });
  18719. /************************************************************************/
  18720. /******/ // The module cache
  18721. /******/ var __webpack_module_cache__ = {};
  18722. /******/
  18723. /******/ // The require function
  18724. /******/ function __webpack_require__(moduleId) {
  18725. /******/ // Check if module is in cache
  18726. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  18727. /******/ if (cachedModule !== undefined) {
  18728. /******/ return cachedModule.exports;
  18729. /******/ }
  18730. /******/ // Create a new module (and put it into the cache)
  18731. /******/ var module = __webpack_module_cache__[moduleId] = {
  18732. /******/ // no module.id needed
  18733. /******/ // no module.loaded needed
  18734. /******/ exports: {}
  18735. /******/ };
  18736. /******/
  18737. /******/ // Execute the module function
  18738. /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  18739. /******/
  18740. /******/ // Return the exports of the module
  18741. /******/ return module.exports;
  18742. /******/ }
  18743. /******/
  18744. /******/ // expose the modules object (__webpack_modules__)
  18745. /******/ __webpack_require__.m = __webpack_modules__;
  18746. /******/
  18747. /************************************************************************/
  18748. /******/ /* webpack/runtime/compat get default export */
  18749. /******/ (() => {
  18750. /******/ // getDefaultExport function for compatibility with non-harmony modules
  18751. /******/ __webpack_require__.n = (module) => {
  18752. /******/ var getter = module && module.__esModule ?
  18753. /******/ () => (module['default']) :
  18754. /******/ () => (module);
  18755. /******/ __webpack_require__.d(getter, { a: getter });
  18756. /******/ return getter;
  18757. /******/ };
  18758. /******/ })();
  18759. /******/
  18760. /******/ /* webpack/runtime/define property getters */
  18761. /******/ (() => {
  18762. /******/ // define getter functions for harmony exports
  18763. /******/ __webpack_require__.d = (exports, definition) => {
  18764. /******/ for(var key in definition) {
  18765. /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
  18766. /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
  18767. /******/ }
  18768. /******/ }
  18769. /******/ };
  18770. /******/ })();
  18771. /******/
  18772. /******/ /* webpack/runtime/hasOwnProperty shorthand */
  18773. /******/ (() => {
  18774. /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
  18775. /******/ })();
  18776. /******/
  18777. /******/ /* webpack/runtime/make namespace object */
  18778. /******/ (() => {
  18779. /******/ // define __esModule on exports
  18780. /******/ __webpack_require__.r = (exports) => {
  18781. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  18782. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  18783. /******/ }
  18784. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  18785. /******/ };
  18786. /******/ })();
  18787. /******/
  18788. /************************************************************************/
  18789. /******/
  18790. /******/ // module factories are used so entry inlining is disabled
  18791. /******/ // startup
  18792. /******/ // Load entry module and return exports
  18793. /******/ var __webpack_exports__ = __webpack_require__("./src/hls.ts");
  18794. /******/ __webpack_exports__ = __webpack_exports__["default"];
  18795. /******/
  18796. /******/ return __webpack_exports__;
  18797. /******/ })()
  18798. ;
  18799. });
  18800. //# sourceMappingURL=hls.light.js.map