hls.light.js 941 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330
  1. (function __HLS_WORKER_BUNDLE__(__IN_WORKER__){
  2. (function (global, factory) {
  3. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  4. typeof define === 'function' && define.amd ? define(factory) :
  5. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Hls = factory());
  6. })(this, (function () { 'use strict';
  7. function _construct(t, e, r) {
  8. if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
  9. var o = [null];
  10. o.push.apply(o, e);
  11. var p = new (t.bind.apply(t, o))();
  12. return r && _setPrototypeOf(p, r.prototype), p;
  13. }
  14. function _defineProperties(e, r) {
  15. for (var t = 0; t < r.length; t++) {
  16. var o = r[t];
  17. o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o);
  18. }
  19. }
  20. function _createClass(e, r, t) {
  21. return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
  22. writable: false
  23. }), e;
  24. }
  25. function _defineProperty(e, r, t) {
  26. return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
  27. value: t,
  28. enumerable: true,
  29. configurable: true,
  30. writable: true
  31. }) : e[r] = t, e;
  32. }
  33. function _extends() {
  34. return _extends = Object.assign ? Object.assign.bind() : function (n) {
  35. for (var e = 1; e < arguments.length; e++) {
  36. var t = arguments[e];
  37. for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
  38. }
  39. return n;
  40. }, _extends.apply(null, arguments);
  41. }
  42. function _getPrototypeOf(t) {
  43. return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
  44. return t.__proto__ || Object.getPrototypeOf(t);
  45. }, _getPrototypeOf(t);
  46. }
  47. function _inheritsLoose(t, o) {
  48. t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o);
  49. }
  50. function _isNativeFunction(t) {
  51. try {
  52. return -1 !== Function.toString.call(t).indexOf("[native code]");
  53. } catch (n) {
  54. return "function" == typeof t;
  55. }
  56. }
  57. function _isNativeReflectConstruct() {
  58. try {
  59. var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
  60. } catch (t) {}
  61. return (_isNativeReflectConstruct = function () {
  62. return !!t;
  63. })();
  64. }
  65. function ownKeys(e, r) {
  66. var t = Object.keys(e);
  67. if (Object.getOwnPropertySymbols) {
  68. var o = Object.getOwnPropertySymbols(e);
  69. r && (o = o.filter(function (r) {
  70. return Object.getOwnPropertyDescriptor(e, r).enumerable;
  71. })), t.push.apply(t, o);
  72. }
  73. return t;
  74. }
  75. function _objectSpread2(e) {
  76. for (var r = 1; r < arguments.length; r++) {
  77. var t = null != arguments[r] ? arguments[r] : {};
  78. r % 2 ? ownKeys(Object(t), true).forEach(function (r) {
  79. _defineProperty(e, r, t[r]);
  80. }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
  81. Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
  82. });
  83. }
  84. return e;
  85. }
  86. function _setPrototypeOf(t, e) {
  87. return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
  88. return t.__proto__ = e, t;
  89. }, _setPrototypeOf(t, e);
  90. }
  91. function _toPrimitive(t, r) {
  92. if ("object" != typeof t || !t) return t;
  93. var e = t[Symbol.toPrimitive];
  94. if (void 0 !== e) {
  95. var i = e.call(t, r);
  96. if ("object" != typeof i) return i;
  97. throw new TypeError("@@toPrimitive must return a primitive value.");
  98. }
  99. return ("string" === r ? String : Number)(t);
  100. }
  101. function _toPropertyKey(t) {
  102. var i = _toPrimitive(t, "string");
  103. return "symbol" == typeof i ? i : i + "";
  104. }
  105. function _wrapNativeSuper(t) {
  106. var r = "function" == typeof Map ? new Map() : void 0;
  107. return _wrapNativeSuper = function (t) {
  108. if (null === t || !_isNativeFunction(t)) return t;
  109. if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function");
  110. if (void 0 !== r) {
  111. if (r.has(t)) return r.get(t);
  112. r.set(t, Wrapper);
  113. }
  114. function Wrapper() {
  115. return _construct(t, arguments, _getPrototypeOf(this).constructor);
  116. }
  117. return Wrapper.prototype = Object.create(t.prototype, {
  118. constructor: {
  119. value: Wrapper,
  120. enumerable: false,
  121. writable: true,
  122. configurable: true
  123. }
  124. }), _setPrototypeOf(Wrapper, t);
  125. }, _wrapNativeSuper(t);
  126. }
  127. /**
  128. * Generate a random v4 UUID
  129. *
  130. * @returns A random v4 UUID
  131. *
  132. * @group Utils
  133. *
  134. * @beta
  135. */
  136. function uuid() {
  137. try {
  138. return crypto.randomUUID();
  139. } catch (error) {
  140. try {
  141. var url = URL.createObjectURL(new Blob());
  142. var _uuid = url.toString();
  143. URL.revokeObjectURL(url);
  144. return _uuid.slice(_uuid.lastIndexOf('/') + 1);
  145. } catch (error) {
  146. var dt = new Date().getTime();
  147. var _uuid2 = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  148. var r = (dt + Math.random() * 16) % 16 | 0;
  149. dt = Math.floor(dt / 16);
  150. return (c == 'x' ? r : r & 0x3 | 0x8).toString(16);
  151. });
  152. return _uuid2;
  153. }
  154. }
  155. }
  156. function getDefaultExportFromCjs (x) {
  157. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  158. }
  159. var eventemitter3 = {exports: {}};
  160. var hasRequiredEventemitter3;
  161. function requireEventemitter3 () {
  162. if (hasRequiredEventemitter3) return eventemitter3.exports;
  163. hasRequiredEventemitter3 = 1;
  164. (function (module) {
  165. var has = Object.prototype.hasOwnProperty
  166. , prefix = '~';
  167. /**
  168. * Constructor to create a storage for our `EE` objects.
  169. * An `Events` instance is a plain object whose properties are event names.
  170. *
  171. * @constructor
  172. * @private
  173. */
  174. function Events() {}
  175. //
  176. // We try to not inherit from `Object.prototype`. In some engines creating an
  177. // instance in this way is faster than calling `Object.create(null)` directly.
  178. // If `Object.create(null)` is not supported we prefix the event names with a
  179. // character to make sure that the built-in object properties are not
  180. // overridden or used as an attack vector.
  181. //
  182. if (Object.create) {
  183. Events.prototype = Object.create(null);
  184. //
  185. // This hack is needed because the `__proto__` property is still inherited in
  186. // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  187. //
  188. if (!new Events().__proto__) prefix = false;
  189. }
  190. /**
  191. * Representation of a single event listener.
  192. *
  193. * @param {Function} fn The listener function.
  194. * @param {*} context The context to invoke the listener with.
  195. * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
  196. * @constructor
  197. * @private
  198. */
  199. function EE(fn, context, once) {
  200. this.fn = fn;
  201. this.context = context;
  202. this.once = once || false;
  203. }
  204. /**
  205. * Add a listener for a given event.
  206. *
  207. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  208. * @param {(String|Symbol)} event The event name.
  209. * @param {Function} fn The listener function.
  210. * @param {*} context The context to invoke the listener with.
  211. * @param {Boolean} once Specify if the listener is a one-time listener.
  212. * @returns {EventEmitter}
  213. * @private
  214. */
  215. function addListener(emitter, event, fn, context, once) {
  216. if (typeof fn !== 'function') {
  217. throw new TypeError('The listener must be a function');
  218. }
  219. var listener = new EE(fn, context || emitter, once)
  220. , evt = prefix ? prefix + event : event;
  221. if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
  222. else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
  223. else emitter._events[evt] = [emitter._events[evt], listener];
  224. return emitter;
  225. }
  226. /**
  227. * Clear event by name.
  228. *
  229. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  230. * @param {(String|Symbol)} evt The Event name.
  231. * @private
  232. */
  233. function clearEvent(emitter, evt) {
  234. if (--emitter._eventsCount === 0) emitter._events = new Events();
  235. else delete emitter._events[evt];
  236. }
  237. /**
  238. * Minimal `EventEmitter` interface that is molded against the Node.js
  239. * `EventEmitter` interface.
  240. *
  241. * @constructor
  242. * @public
  243. */
  244. function EventEmitter() {
  245. this._events = new Events();
  246. this._eventsCount = 0;
  247. }
  248. /**
  249. * Return an array listing the events for which the emitter has registered
  250. * listeners.
  251. *
  252. * @returns {Array}
  253. * @public
  254. */
  255. EventEmitter.prototype.eventNames = function eventNames() {
  256. var names = []
  257. , events
  258. , name;
  259. if (this._eventsCount === 0) return names;
  260. for (name in (events = this._events)) {
  261. if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
  262. }
  263. if (Object.getOwnPropertySymbols) {
  264. return names.concat(Object.getOwnPropertySymbols(events));
  265. }
  266. return names;
  267. };
  268. /**
  269. * Return the listeners registered for a given event.
  270. *
  271. * @param {(String|Symbol)} event The event name.
  272. * @returns {Array} The registered listeners.
  273. * @public
  274. */
  275. EventEmitter.prototype.listeners = function listeners(event) {
  276. var evt = prefix ? prefix + event : event
  277. , handlers = this._events[evt];
  278. if (!handlers) return [];
  279. if (handlers.fn) return [handlers.fn];
  280. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  281. ee[i] = handlers[i].fn;
  282. }
  283. return ee;
  284. };
  285. /**
  286. * Return the number of listeners listening to a given event.
  287. *
  288. * @param {(String|Symbol)} event The event name.
  289. * @returns {Number} The number of listeners.
  290. * @public
  291. */
  292. EventEmitter.prototype.listenerCount = function listenerCount(event) {
  293. var evt = prefix ? prefix + event : event
  294. , listeners = this._events[evt];
  295. if (!listeners) return 0;
  296. if (listeners.fn) return 1;
  297. return listeners.length;
  298. };
  299. /**
  300. * Calls each of the listeners registered for a given event.
  301. *
  302. * @param {(String|Symbol)} event The event name.
  303. * @returns {Boolean} `true` if the event had listeners, else `false`.
  304. * @public
  305. */
  306. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  307. var evt = prefix ? prefix + event : event;
  308. if (!this._events[evt]) return false;
  309. var listeners = this._events[evt]
  310. , len = arguments.length
  311. , args
  312. , i;
  313. if (listeners.fn) {
  314. if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  315. switch (len) {
  316. case 1: return listeners.fn.call(listeners.context), true;
  317. case 2: return listeners.fn.call(listeners.context, a1), true;
  318. case 3: return listeners.fn.call(listeners.context, a1, a2), true;
  319. case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
  320. case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  321. case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  322. }
  323. for (i = 1, args = new Array(len -1); i < len; i++) {
  324. args[i - 1] = arguments[i];
  325. }
  326. listeners.fn.apply(listeners.context, args);
  327. } else {
  328. var length = listeners.length
  329. , j;
  330. for (i = 0; i < length; i++) {
  331. if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  332. switch (len) {
  333. case 1: listeners[i].fn.call(listeners[i].context); break;
  334. case 2: listeners[i].fn.call(listeners[i].context, a1); break;
  335. case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
  336. case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
  337. default:
  338. if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
  339. args[j - 1] = arguments[j];
  340. }
  341. listeners[i].fn.apply(listeners[i].context, args);
  342. }
  343. }
  344. }
  345. return true;
  346. };
  347. /**
  348. * Add a listener for a given event.
  349. *
  350. * @param {(String|Symbol)} event The event name.
  351. * @param {Function} fn The listener function.
  352. * @param {*} [context=this] The context to invoke the listener with.
  353. * @returns {EventEmitter} `this`.
  354. * @public
  355. */
  356. EventEmitter.prototype.on = function on(event, fn, context) {
  357. return addListener(this, event, fn, context, false);
  358. };
  359. /**
  360. * Add a one-time listener for a given event.
  361. *
  362. * @param {(String|Symbol)} event The event name.
  363. * @param {Function} fn The listener function.
  364. * @param {*} [context=this] The context to invoke the listener with.
  365. * @returns {EventEmitter} `this`.
  366. * @public
  367. */
  368. EventEmitter.prototype.once = function once(event, fn, context) {
  369. return addListener(this, event, fn, context, true);
  370. };
  371. /**
  372. * Remove the listeners of a given event.
  373. *
  374. * @param {(String|Symbol)} event The event name.
  375. * @param {Function} fn Only remove the listeners that match this function.
  376. * @param {*} context Only remove the listeners that have this context.
  377. * @param {Boolean} once Only remove one-time listeners.
  378. * @returns {EventEmitter} `this`.
  379. * @public
  380. */
  381. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  382. var evt = prefix ? prefix + event : event;
  383. if (!this._events[evt]) return this;
  384. if (!fn) {
  385. clearEvent(this, evt);
  386. return this;
  387. }
  388. var listeners = this._events[evt];
  389. if (listeners.fn) {
  390. if (
  391. listeners.fn === fn &&
  392. (!once || listeners.once) &&
  393. (!context || listeners.context === context)
  394. ) {
  395. clearEvent(this, evt);
  396. }
  397. } else {
  398. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  399. if (
  400. listeners[i].fn !== fn ||
  401. (once && !listeners[i].once) ||
  402. (context && listeners[i].context !== context)
  403. ) {
  404. events.push(listeners[i]);
  405. }
  406. }
  407. //
  408. // Reset the array, or remove it completely if we have no more listeners.
  409. //
  410. if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
  411. else clearEvent(this, evt);
  412. }
  413. return this;
  414. };
  415. /**
  416. * Remove all listeners, or those of the specified event.
  417. *
  418. * @param {(String|Symbol)} [event] The event name.
  419. * @returns {EventEmitter} `this`.
  420. * @public
  421. */
  422. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  423. var evt;
  424. if (event) {
  425. evt = prefix ? prefix + event : event;
  426. if (this._events[evt]) clearEvent(this, evt);
  427. } else {
  428. this._events = new Events();
  429. this._eventsCount = 0;
  430. }
  431. return this;
  432. };
  433. //
  434. // Alias methods names because people roll like that.
  435. //
  436. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  437. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  438. //
  439. // Expose the prefix.
  440. //
  441. EventEmitter.prefixed = prefix;
  442. //
  443. // Allow `EventEmitter` to be imported as module namespace.
  444. //
  445. EventEmitter.EventEmitter = EventEmitter;
  446. //
  447. // Expose the module.
  448. //
  449. {
  450. module.exports = EventEmitter;
  451. }
  452. } (eventemitter3));
  453. return eventemitter3.exports;
  454. }
  455. var eventemitter3Exports = requireEventemitter3();
  456. var EventEmitter = /*@__PURE__*/getDefaultExportFromCjs(eventemitter3Exports);
  457. var urlToolkit = {exports: {}};
  458. var hasRequiredUrlToolkit;
  459. function requireUrlToolkit () {
  460. if (hasRequiredUrlToolkit) return urlToolkit.exports;
  461. hasRequiredUrlToolkit = 1;
  462. (function (module, exports) {
  463. // see https://tools.ietf.org/html/rfc1808
  464. (function (root) {
  465. var URL_REGEX =
  466. /^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/;
  467. var FIRST_SEGMENT_REGEX = /^(?=([^\/?#]*))\1([^]*)$/;
  468. var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
  469. var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
  470. var URLToolkit = {
  471. // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
  472. // E.g
  473. // With opts.alwaysNormalize = false (default, spec compliant)
  474. // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
  475. // With opts.alwaysNormalize = true (not spec compliant)
  476. // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
  477. buildAbsoluteURL: function (baseURL, relativeURL, opts) {
  478. opts = opts || {};
  479. // remove any remaining space and CRLF
  480. baseURL = baseURL.trim();
  481. relativeURL = relativeURL.trim();
  482. if (!relativeURL) {
  483. // 2a) If the embedded URL is entirely empty, it inherits the
  484. // entire base URL (i.e., is set equal to the base URL)
  485. // and we are done.
  486. if (!opts.alwaysNormalize) {
  487. return baseURL;
  488. }
  489. var basePartsForNormalise = URLToolkit.parseURL(baseURL);
  490. if (!basePartsForNormalise) {
  491. throw new Error('Error trying to parse base URL.');
  492. }
  493. basePartsForNormalise.path = URLToolkit.normalizePath(
  494. basePartsForNormalise.path
  495. );
  496. return URLToolkit.buildURLFromParts(basePartsForNormalise);
  497. }
  498. var relativeParts = URLToolkit.parseURL(relativeURL);
  499. if (!relativeParts) {
  500. throw new Error('Error trying to parse relative URL.');
  501. }
  502. if (relativeParts.scheme) {
  503. // 2b) If the embedded URL starts with a scheme name, it is
  504. // interpreted as an absolute URL and we are done.
  505. if (!opts.alwaysNormalize) {
  506. return relativeURL;
  507. }
  508. relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
  509. return URLToolkit.buildURLFromParts(relativeParts);
  510. }
  511. var baseParts = URLToolkit.parseURL(baseURL);
  512. if (!baseParts) {
  513. throw new Error('Error trying to parse base URL.');
  514. }
  515. if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
  516. // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
  517. // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
  518. var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
  519. baseParts.netLoc = pathParts[1];
  520. baseParts.path = pathParts[2];
  521. }
  522. if (baseParts.netLoc && !baseParts.path) {
  523. baseParts.path = '/';
  524. }
  525. var builtParts = {
  526. // 2c) Otherwise, the embedded URL inherits the scheme of
  527. // the base URL.
  528. scheme: baseParts.scheme,
  529. netLoc: relativeParts.netLoc,
  530. path: null,
  531. params: relativeParts.params,
  532. query: relativeParts.query,
  533. fragment: relativeParts.fragment,
  534. };
  535. if (!relativeParts.netLoc) {
  536. // 3) If the embedded URL's <net_loc> is non-empty, we skip to
  537. // Step 7. Otherwise, the embedded URL inherits the <net_loc>
  538. // (if any) of the base URL.
  539. builtParts.netLoc = baseParts.netLoc;
  540. // 4) If the embedded URL path is preceded by a slash "/", the
  541. // path is not relative and we skip to Step 7.
  542. if (relativeParts.path[0] !== '/') {
  543. if (!relativeParts.path) {
  544. // 5) If the embedded URL path is empty (and not preceded by a
  545. // slash), then the embedded URL inherits the base URL path
  546. builtParts.path = baseParts.path;
  547. // 5a) if the embedded URL's <params> is non-empty, we skip to
  548. // step 7; otherwise, it inherits the <params> of the base
  549. // URL (if any) and
  550. if (!relativeParts.params) {
  551. builtParts.params = baseParts.params;
  552. // 5b) if the embedded URL's <query> is non-empty, we skip to
  553. // step 7; otherwise, it inherits the <query> of the base
  554. // URL (if any) and we skip to step 7.
  555. if (!relativeParts.query) {
  556. builtParts.query = baseParts.query;
  557. }
  558. }
  559. } else {
  560. // 6) The last segment of the base URL's path (anything
  561. // following the rightmost slash "/", or the entire path if no
  562. // slash is present) is removed and the embedded URL's path is
  563. // appended in its place.
  564. var baseURLPath = baseParts.path;
  565. var newPath =
  566. baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) +
  567. relativeParts.path;
  568. builtParts.path = URLToolkit.normalizePath(newPath);
  569. }
  570. }
  571. }
  572. if (builtParts.path === null) {
  573. builtParts.path = opts.alwaysNormalize
  574. ? URLToolkit.normalizePath(relativeParts.path)
  575. : relativeParts.path;
  576. }
  577. return URLToolkit.buildURLFromParts(builtParts);
  578. },
  579. parseURL: function (url) {
  580. var parts = URL_REGEX.exec(url);
  581. if (!parts) {
  582. return null;
  583. }
  584. return {
  585. scheme: parts[1] || '',
  586. netLoc: parts[2] || '',
  587. path: parts[3] || '',
  588. params: parts[4] || '',
  589. query: parts[5] || '',
  590. fragment: parts[6] || '',
  591. };
  592. },
  593. normalizePath: function (path) {
  594. // The following operations are
  595. // then applied, in order, to the new path:
  596. // 6a) All occurrences of "./", where "." is a complete path
  597. // segment, are removed.
  598. // 6b) If the path ends with "." as a complete path segment,
  599. // that "." is removed.
  600. path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');
  601. // 6c) All occurrences of "<segment>/../", where <segment> is a
  602. // complete path segment not equal to "..", are removed.
  603. // Removal of these path segments is performed iteratively,
  604. // removing the leftmost matching pattern on each iteration,
  605. // until no matching pattern remains.
  606. // 6d) If the path ends with "<segment>/..", where <segment> is a
  607. // complete path segment not equal to "..", that
  608. // "<segment>/.." is removed.
  609. while (
  610. path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length
  611. ) {}
  612. return path.split('').reverse().join('');
  613. },
  614. buildURLFromParts: function (parts) {
  615. return (
  616. parts.scheme +
  617. parts.netLoc +
  618. parts.path +
  619. parts.params +
  620. parts.query +
  621. parts.fragment
  622. );
  623. },
  624. };
  625. module.exports = URLToolkit;
  626. })();
  627. } (urlToolkit));
  628. return urlToolkit.exports;
  629. }
  630. var urlToolkitExports = requireUrlToolkit();
  631. // https://caniuse.com/mdn-javascript_builtins_number_isfinite
  632. var isFiniteNumber = Number.isFinite || function (value) {
  633. return typeof value === 'number' && isFinite(value);
  634. };
  635. // https://caniuse.com/mdn-javascript_builtins_number_issafeinteger
  636. var isSafeInteger = Number.isSafeInteger || function (value) {
  637. return typeof value === 'number' && Math.abs(value) <= MAX_SAFE_INTEGER;
  638. };
  639. var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  640. var ErrorTypes = /*#__PURE__*/function (ErrorTypes) {
  641. // Identifier for a network error (loading error / timeout ...)
  642. ErrorTypes["NETWORK_ERROR"] = "networkError";
  643. // Identifier for a media Error (video/parsing/mediasource error)
  644. ErrorTypes["MEDIA_ERROR"] = "mediaError";
  645. // EME (encrypted media extensions) errors
  646. ErrorTypes["KEY_SYSTEM_ERROR"] = "keySystemError";
  647. // Identifier for a mux Error (demuxing/remuxing)
  648. ErrorTypes["MUX_ERROR"] = "muxError";
  649. // Identifier for all other errors
  650. ErrorTypes["OTHER_ERROR"] = "otherError";
  651. return ErrorTypes;
  652. }({});
  653. var ErrorDetails = /*#__PURE__*/function (ErrorDetails) {
  654. ErrorDetails["KEY_SYSTEM_NO_KEYS"] = "keySystemNoKeys";
  655. ErrorDetails["KEY_SYSTEM_NO_ACCESS"] = "keySystemNoAccess";
  656. ErrorDetails["KEY_SYSTEM_NO_SESSION"] = "keySystemNoSession";
  657. ErrorDetails["KEY_SYSTEM_NO_CONFIGURED_LICENSE"] = "keySystemNoConfiguredLicense";
  658. ErrorDetails["KEY_SYSTEM_LICENSE_REQUEST_FAILED"] = "keySystemLicenseRequestFailed";
  659. ErrorDetails["KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED"] = "keySystemServerCertificateRequestFailed";
  660. ErrorDetails["KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED"] = "keySystemServerCertificateUpdateFailed";
  661. ErrorDetails["KEY_SYSTEM_SESSION_UPDATE_FAILED"] = "keySystemSessionUpdateFailed";
  662. ErrorDetails["KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED"] = "keySystemStatusOutputRestricted";
  663. ErrorDetails["KEY_SYSTEM_STATUS_INTERNAL_ERROR"] = "keySystemStatusInternalError";
  664. ErrorDetails["KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR"] = "keySystemDestroyMediaKeysError";
  665. ErrorDetails["KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR"] = "keySystemDestroyCloseSessionError";
  666. ErrorDetails["KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR"] = "keySystemDestroyRemoveSessionError";
  667. // Identifier for a manifest load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  668. ErrorDetails["MANIFEST_LOAD_ERROR"] = "manifestLoadError";
  669. // Identifier for a manifest load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  670. ErrorDetails["MANIFEST_LOAD_TIMEOUT"] = "manifestLoadTimeOut";
  671. // Identifier for a manifest parsing error - data: { url : faulty URL, reason : error reason}
  672. ErrorDetails["MANIFEST_PARSING_ERROR"] = "manifestParsingError";
  673. // Identifier for a manifest with only incompatible codecs error - data: { url : faulty URL, reason : error reason}
  674. ErrorDetails["MANIFEST_INCOMPATIBLE_CODECS_ERROR"] = "manifestIncompatibleCodecsError";
  675. // Identifier for a level which contains no fragments - data: { url: faulty URL, reason: "no fragments found in level", level: index of the bad level }
  676. ErrorDetails["LEVEL_EMPTY_ERROR"] = "levelEmptyError";
  677. // Identifier for a level load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  678. ErrorDetails["LEVEL_LOAD_ERROR"] = "levelLoadError";
  679. // Identifier for a level load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  680. ErrorDetails["LEVEL_LOAD_TIMEOUT"] = "levelLoadTimeOut";
  681. // Identifier for a level parse error - data: { url : faulty URL, error: Error, reason: error message }
  682. ErrorDetails["LEVEL_PARSING_ERROR"] = "levelParsingError";
  683. // Identifier for a level switch error - data: { level : faulty level Id, event : error description}
  684. ErrorDetails["LEVEL_SWITCH_ERROR"] = "levelSwitchError";
  685. // Identifier for an audio track load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  686. ErrorDetails["AUDIO_TRACK_LOAD_ERROR"] = "audioTrackLoadError";
  687. // Identifier for an audio track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  688. ErrorDetails["AUDIO_TRACK_LOAD_TIMEOUT"] = "audioTrackLoadTimeOut";
  689. // Identifier for a subtitle track load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  690. ErrorDetails["SUBTITLE_LOAD_ERROR"] = "subtitleTrackLoadError";
  691. // Identifier for a subtitle track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  692. ErrorDetails["SUBTITLE_TRACK_LOAD_TIMEOUT"] = "subtitleTrackLoadTimeOut";
  693. // Identifier for fragment load error - data: { frag : fragment object, response : { code: error code, text: error text }}
  694. ErrorDetails["FRAG_LOAD_ERROR"] = "fragLoadError";
  695. // Identifier for fragment load timeout error - data: { frag : fragment object}
  696. ErrorDetails["FRAG_LOAD_TIMEOUT"] = "fragLoadTimeOut";
  697. // Identifier for a fragment decryption error event - data: {id : demuxer Id,frag: fragment object, reason : parsing error description }
  698. ErrorDetails["FRAG_DECRYPT_ERROR"] = "fragDecryptError";
  699. // Identifier for a fragment parsing error event - data: { id : demuxer Id, reason : parsing error description }
  700. // will be renamed DEMUX_PARSING_ERROR and switched to MUX_ERROR in the next major release
  701. ErrorDetails["FRAG_PARSING_ERROR"] = "fragParsingError";
  702. // Identifier for a fragment or part load skipped because of a GAP tag or attribute
  703. ErrorDetails["FRAG_GAP"] = "fragGap";
  704. // Identifier for a remux alloc error event - data: { id : demuxer Id, frag : fragment object, bytes : nb of bytes on which allocation failed , reason : error text }
  705. ErrorDetails["REMUX_ALLOC_ERROR"] = "remuxAllocError";
  706. // Identifier for decrypt key load error - data: { frag : fragment object, response : { code: error code, text: error text }}
  707. ErrorDetails["KEY_LOAD_ERROR"] = "keyLoadError";
  708. // Identifier for decrypt key load timeout error - data: { frag : fragment object}
  709. ErrorDetails["KEY_LOAD_TIMEOUT"] = "keyLoadTimeOut";
  710. // Triggered when an exception occurs while adding a sourceBuffer to MediaSource - data : { error : exception , mimeType : mimeType }
  711. ErrorDetails["BUFFER_ADD_CODEC_ERROR"] = "bufferAddCodecError";
  712. // Triggered when source buffer(s) could not be created using level (manifest CODECS attribute), parsed media, or best guess codec(s) - data: { reason : error reason }
  713. ErrorDetails["BUFFER_INCOMPATIBLE_CODECS_ERROR"] = "bufferIncompatibleCodecsError";
  714. // Identifier for a buffer append error - data: append error description
  715. ErrorDetails["BUFFER_APPEND_ERROR"] = "bufferAppendError";
  716. // Identifier for a buffer appending error event - data: appending error description
  717. ErrorDetails["BUFFER_APPENDING_ERROR"] = "bufferAppendingError";
  718. // Identifier for a buffer stalled error event
  719. ErrorDetails["BUFFER_STALLED_ERROR"] = "bufferStalledError";
  720. // Identifier for a buffer full event
  721. ErrorDetails["BUFFER_FULL_ERROR"] = "bufferFullError";
  722. // Identifier for a buffer seek over hole event
  723. ErrorDetails["BUFFER_SEEK_OVER_HOLE"] = "bufferSeekOverHole";
  724. // Identifier for a buffer nudge on stall (playback is stuck although currentTime is in a buffered area)
  725. ErrorDetails["BUFFER_NUDGE_ON_STALL"] = "bufferNudgeOnStall";
  726. // Identifier for a Interstitial Asset List load error - data: { url: faulty URL, response: { code: error code, text: error text } }
  727. ErrorDetails["ASSET_LIST_LOAD_ERROR"] = "assetListLoadError";
  728. // Identifier for a Interstitial Asset List load timeout - data: { url: faulty URL, response: { code: error code, text: error text } }
  729. ErrorDetails["ASSET_LIST_LOAD_TIMEOUT"] = "assetListLoadTimeout";
  730. // Identifier for a Interstitial Asset List parsing error - data: { url : faulty URL, reason : error reason, response : { code: error code, text: error text }}
  731. ErrorDetails["ASSET_LIST_PARSING_ERROR"] = "assetListParsingError";
  732. // Identifier for a Interstitial Asset List parsing error - data: { url : faulty URL, reason : error reason, response : { code: error code, text: error text }}
  733. ErrorDetails["INTERSTITIAL_ASSET_ITEM_ERROR"] = "interstitialAssetItemError";
  734. // Identifier for an internal exception happening inside hls.js while handling an event
  735. ErrorDetails["INTERNAL_EXCEPTION"] = "internalException";
  736. // Identifier for an internal call to abort a loader
  737. ErrorDetails["INTERNAL_ABORTED"] = "aborted";
  738. // Triggered when attachMedia fails
  739. ErrorDetails["ATTACH_MEDIA_ERROR"] = "attachMediaError";
  740. // Uncategorized error
  741. ErrorDetails["UNKNOWN"] = "unknown";
  742. return ErrorDetails;
  743. }({});
  744. var Events = /*#__PURE__*/function (Events) {
  745. // Fired before MediaSource is attaching to media element
  746. Events["MEDIA_ATTACHING"] = "hlsMediaAttaching";
  747. // Fired when MediaSource has been successfully attached to media element
  748. Events["MEDIA_ATTACHED"] = "hlsMediaAttached";
  749. // Fired before detaching MediaSource from media element
  750. Events["MEDIA_DETACHING"] = "hlsMediaDetaching";
  751. // Fired when MediaSource has been detached from media element
  752. Events["MEDIA_DETACHED"] = "hlsMediaDetached";
  753. // Fired when HTMLMediaElement dispatches "ended" event, or stalls at end of VOD program
  754. Events["MEDIA_ENDED"] = "hlsMediaEnded";
  755. // Fired after playback stall is resolved with playing, seeked, or ended event following BUFFER_STALLED_ERROR
  756. Events["STALL_RESOLVED"] = "hlsStallResolved";
  757. // Fired when the buffer is going to be reset
  758. Events["BUFFER_RESET"] = "hlsBufferReset";
  759. // Fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }}
  760. Events["BUFFER_CODECS"] = "hlsBufferCodecs";
  761. // fired when sourcebuffers have been created - data: { tracks : tracks }
  762. Events["BUFFER_CREATED"] = "hlsBufferCreated";
  763. // fired when we append a segment to the buffer - data: { segment: segment object }
  764. Events["BUFFER_APPENDING"] = "hlsBufferAppending";
  765. // fired when we are done with appending a media segment to the buffer - data : { parent : segment parent that triggered BUFFER_APPENDING, pending : nb of segments waiting for appending for this segment parent}
  766. Events["BUFFER_APPENDED"] = "hlsBufferAppended";
  767. // fired when the stream is finished and we want to notify the media buffer that there will be no more data - data: { }
  768. Events["BUFFER_EOS"] = "hlsBufferEos";
  769. // fired when all buffers are full to the end of the program, after calling MediaSource.endOfStream() (unless restricted)
  770. Events["BUFFERED_TO_END"] = "hlsBufferedToEnd";
  771. // fired when the media buffer should be flushed - data { startOffset, endOffset }
  772. Events["BUFFER_FLUSHING"] = "hlsBufferFlushing";
  773. // fired when the media buffer has been flushed - data: { }
  774. Events["BUFFER_FLUSHED"] = "hlsBufferFlushed";
  775. // fired to signal that a manifest loading starts - data: { url : manifestURL}
  776. Events["MANIFEST_LOADING"] = "hlsManifestLoading";
  777. // fired after manifest has been loaded - data: { levels : [available quality levels], audioTracks : [ available audio tracks ], url : manifestURL, stats : LoaderStats }
  778. Events["MANIFEST_LOADED"] = "hlsManifestLoaded";
  779. // fired after manifest has been parsed - data: { levels : [available quality levels], firstLevel : index of first quality level appearing in Manifest}
  780. Events["MANIFEST_PARSED"] = "hlsManifestParsed";
  781. // fired when a level switch is requested - data: { level : id of new level }
  782. Events["LEVEL_SWITCHING"] = "hlsLevelSwitching";
  783. // fired when a level switch is effective - data: { level : id of new level }
  784. Events["LEVEL_SWITCHED"] = "hlsLevelSwitched";
  785. // fired when a level playlist loading starts - data: { url : level URL, level : id of level being loaded}
  786. Events["LEVEL_LOADING"] = "hlsLevelLoading";
  787. // fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : LoaderStats }
  788. Events["LEVEL_LOADED"] = "hlsLevelLoaded";
  789. // fired when a level's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, level : id of updated level }
  790. Events["LEVEL_UPDATED"] = "hlsLevelUpdated";
  791. // fired when a level's PTS information has been updated after parsing a fragment - data: { details : levelDetails object, level : id of updated level, drift: PTS drift observed when parsing last fragment }
  792. Events["LEVEL_PTS_UPDATED"] = "hlsLevelPtsUpdated";
  793. // fired to notify that levels have changed after removing a level - data: { levels : [available quality levels] }
  794. Events["LEVELS_UPDATED"] = "hlsLevelsUpdated";
  795. // fired to notify that audio track lists has been updated - data: { audioTracks : audioTracks }
  796. Events["AUDIO_TRACKS_UPDATED"] = "hlsAudioTracksUpdated";
  797. // fired when an audio track switching is requested - data: { id : audio track id }
  798. Events["AUDIO_TRACK_SWITCHING"] = "hlsAudioTrackSwitching";
  799. // fired when an audio track switch actually occurs - data: { id : audio track id }
  800. Events["AUDIO_TRACK_SWITCHED"] = "hlsAudioTrackSwitched";
  801. // fired when an audio track loading starts - data: { url : audio track URL, id : audio track id }
  802. Events["AUDIO_TRACK_LOADING"] = "hlsAudioTrackLoading";
  803. // fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : LoaderStats }
  804. Events["AUDIO_TRACK_LOADED"] = "hlsAudioTrackLoaded";
  805. // fired when an audio tracks's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, id : track id }
  806. Events["AUDIO_TRACK_UPDATED"] = "hlsAudioTrackUpdated";
  807. // fired to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks }
  808. Events["SUBTITLE_TRACKS_UPDATED"] = "hlsSubtitleTracksUpdated";
  809. // fired to notify that subtitle tracks were cleared as a result of stopping the media
  810. Events["SUBTITLE_TRACKS_CLEARED"] = "hlsSubtitleTracksCleared";
  811. // fired when an subtitle track switch occurs - data: { id : subtitle track id }
  812. Events["SUBTITLE_TRACK_SWITCH"] = "hlsSubtitleTrackSwitch";
  813. // fired when a subtitle track loading starts - data: { url : subtitle track URL, id : subtitle track id }
  814. Events["SUBTITLE_TRACK_LOADING"] = "hlsSubtitleTrackLoading";
  815. // fired when a subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : LoaderStats }
  816. Events["SUBTITLE_TRACK_LOADED"] = "hlsSubtitleTrackLoaded";
  817. // fired when a subtitle racks's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, id : track id }
  818. Events["SUBTITLE_TRACK_UPDATED"] = "hlsSubtitleTrackUpdated";
  819. // fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag }
  820. Events["SUBTITLE_FRAG_PROCESSED"] = "hlsSubtitleFragProcessed";
  821. // fired when a set of VTTCues to be managed externally has been parsed - data: { type: string, track: string, cues: [ VTTCue ] }
  822. Events["CUES_PARSED"] = "hlsCuesParsed";
  823. // fired when a text track to be managed externally is found - data: { tracks: [ { label: string, kind: string, default: boolean } ] }
  824. Events["NON_NATIVE_TEXT_TRACKS_FOUND"] = "hlsNonNativeTextTracksFound";
  825. // fired when the first timestamp is found - data: { id : demuxer id, initPTS: initPTS, timescale: timescale, frag : fragment object }
  826. Events["INIT_PTS_FOUND"] = "hlsInitPtsFound";
  827. // fired when a fragment loading starts - data: { frag : fragment object }
  828. Events["FRAG_LOADING"] = "hlsFragLoading";
  829. // fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded } }
  830. // FRAG_LOAD_PROGRESS = 'hlsFragLoadProgress',
  831. // Identifier for fragment load aborting for emergency switch down - data: { frag : fragment object }
  832. Events["FRAG_LOAD_EMERGENCY_ABORTED"] = "hlsFragLoadEmergencyAborted";
  833. // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : LoaderStats }
  834. Events["FRAG_LOADED"] = "hlsFragLoaded";
  835. // fired when a fragment has finished decrypting - data: { id : demuxer id, frag: fragment object, payload : fragment payload, stats : { tstart, tdecrypt } }
  836. Events["FRAG_DECRYPTED"] = "hlsFragDecrypted";
  837. // fired when Init Segment has been extracted from fragment - data: { id : demuxer id, frag: fragment object, moov : moov MP4 box, codecs : codecs found while parsing fragment }
  838. Events["FRAG_PARSING_INIT_SEGMENT"] = "hlsFragParsingInitSegment";
  839. // fired when parsing sei text is completed - data: { id : demuxer id, frag: fragment object, samples : [ sei samples pes ] }
  840. Events["FRAG_PARSING_USERDATA"] = "hlsFragParsingUserdata";
  841. // fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] }
  842. Events["FRAG_PARSING_METADATA"] = "hlsFragParsingMetadata";
  843. // fired when data have been extracted from fragment - data: { id : demuxer id, frag: fragment object, data1 : moof MP4 box or TS fragments, data2 : mdat MP4 box or null}
  844. // FRAG_PARSING_DATA = 'hlsFragParsingData',
  845. // fired when fragment parsing is completed - data: { id : demuxer id, frag: fragment object }
  846. Events["FRAG_PARSED"] = "hlsFragParsed";
  847. // fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { id : demuxer id, frag : fragment object, stats : LoaderStats }
  848. Events["FRAG_BUFFERED"] = "hlsFragBuffered";
  849. // fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object }
  850. Events["FRAG_CHANGED"] = "hlsFragChanged";
  851. // Identifier for a FPS drop event - data: { currentDropped, currentDecoded, totalDroppedFrames }
  852. Events["FPS_DROP"] = "hlsFpsDrop";
  853. // triggered when FPS drop triggers auto level capping - data: { level, droppedLevel }
  854. Events["FPS_DROP_LEVEL_CAPPING"] = "hlsFpsDropLevelCapping";
  855. // triggered when maxAutoLevel changes - data { autoLevelCapping, levels, maxAutoLevel, minAutoLevel, maxHdcpLevel }
  856. Events["MAX_AUTO_LEVEL_UPDATED"] = "hlsMaxAutoLevelUpdated";
  857. // Identifier for an error event - data: { type : error type, details : error details, fatal : if true, hls.js cannot/will not try to recover, if false, hls.js will try to recover,other error specific data }
  858. Events["ERROR"] = "hlsError";
  859. // fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a media to the instance of hls.js to handle mid-rolls for example - data: { }
  860. Events["DESTROYING"] = "hlsDestroying";
  861. // fired when a decrypt key loading starts - data: { frag : fragment object }
  862. Events["KEY_LOADING"] = "hlsKeyLoading";
  863. // fired when a decrypt key loading is completed - data: { frag : fragment object, keyInfo : KeyLoaderInfo }
  864. Events["KEY_LOADED"] = "hlsKeyLoaded";
  865. // deprecated; please use BACK_BUFFER_REACHED - data : { bufferEnd: number }
  866. Events["LIVE_BACK_BUFFER_REACHED"] = "hlsLiveBackBufferReached";
  867. // fired when the back buffer is reached as defined by the backBufferLength config option - data : { bufferEnd: number }
  868. Events["BACK_BUFFER_REACHED"] = "hlsBackBufferReached";
  869. // fired after steering manifest has been loaded - data: { steeringManifest: SteeringManifest object, url: steering manifest URL }
  870. Events["STEERING_MANIFEST_LOADED"] = "hlsSteeringManifestLoaded";
  871. // fired when asset list has begun loading
  872. Events["ASSET_LIST_LOADING"] = "hlsAssetListLoading";
  873. // fired when a valid asset list is loaded
  874. Events["ASSET_LIST_LOADED"] = "hlsAssetListLoaded";
  875. // fired when the list of Interstitial Events and Interstitial Schedule is updated
  876. Events["INTERSTITIALS_UPDATED"] = "hlsInterstitialsUpdated";
  877. // fired when the buffer reaches an Interstitial Schedule boundary (both Primary segments and Interstitial Assets)
  878. Events["INTERSTITIALS_BUFFERED_TO_BOUNDARY"] = "hlsInterstitialsBufferedToBoundary";
  879. // fired when a player instance for an Interstitial Asset has been created
  880. Events["INTERSTITIAL_ASSET_PLAYER_CREATED"] = "hlsInterstitialAssetPlayerCreated";
  881. // Interstitial playback started
  882. Events["INTERSTITIAL_STARTED"] = "hlsInterstitialStarted";
  883. // InterstitialAsset playback started
  884. Events["INTERSTITIAL_ASSET_STARTED"] = "hlsInterstitialAssetStarted";
  885. // InterstitialAsset playback ended
  886. Events["INTERSTITIAL_ASSET_ENDED"] = "hlsInterstitialAssetEnded";
  887. // InterstitialAsset playback errored
  888. Events["INTERSTITIAL_ASSET_ERROR"] = "hlsInterstitialAssetError";
  889. // Interstitial playback ended
  890. Events["INTERSTITIAL_ENDED"] = "hlsInterstitialEnded";
  891. // Interstitial schedule resumed primary playback
  892. Events["INTERSTITIALS_PRIMARY_RESUMED"] = "hlsInterstitialsPrimaryResumed";
  893. // Interstitial players dispatch this event when playout limit is reached
  894. Events["PLAYOUT_LIMIT_REACHED"] = "hlsPlayoutLimitReached";
  895. // Event DateRange cue "enter" event dispatched
  896. Events["EVENT_CUE_ENTER"] = "hlsEventCueEnter";
  897. return Events;
  898. }({});
  899. /**
  900. * Defines each Event type and payload by Event name. Used in {@link hls.js#HlsEventEmitter} to strongly type the event listener API.
  901. */
  902. var PlaylistContextType = {
  903. MANIFEST: "manifest",
  904. LEVEL: "level",
  905. AUDIO_TRACK: "audioTrack",
  906. SUBTITLE_TRACK: "subtitleTrack"
  907. };
  908. var PlaylistLevelType = {
  909. MAIN: "main",
  910. AUDIO: "audio",
  911. SUBTITLE: "subtitle"
  912. };
  913. /*
  914. * compute an Exponential Weighted moving average
  915. * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  916. * - heavily inspired from shaka-player
  917. */
  918. var EWMA = /*#__PURE__*/function () {
  919. // About half of the estimated value will be from the last |halfLife| samples by weight.
  920. function EWMA(halfLife, estimate, weight) {
  921. if (estimate === void 0) {
  922. estimate = 0;
  923. }
  924. if (weight === void 0) {
  925. weight = 0;
  926. }
  927. this.halfLife = void 0;
  928. this.alpha_ = void 0;
  929. this.estimate_ = void 0;
  930. this.totalWeight_ = void 0;
  931. this.halfLife = halfLife;
  932. // Larger values of alpha expire historical data more slowly.
  933. this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
  934. this.estimate_ = estimate;
  935. this.totalWeight_ = weight;
  936. }
  937. var _proto = EWMA.prototype;
  938. _proto.sample = function sample(weight, value) {
  939. var adjAlpha = Math.pow(this.alpha_, weight);
  940. this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
  941. this.totalWeight_ += weight;
  942. };
  943. _proto.getTotalWeight = function getTotalWeight() {
  944. return this.totalWeight_;
  945. };
  946. _proto.getEstimate = function getEstimate() {
  947. if (this.alpha_) {
  948. var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
  949. if (zeroFactor) {
  950. return this.estimate_ / zeroFactor;
  951. }
  952. }
  953. return this.estimate_;
  954. };
  955. return EWMA;
  956. }();
  957. var EwmaBandWidthEstimator = /*#__PURE__*/function () {
  958. function EwmaBandWidthEstimator(slow, fast, defaultEstimate, defaultTTFB) {
  959. if (defaultTTFB === void 0) {
  960. defaultTTFB = 100;
  961. }
  962. this.defaultEstimate_ = void 0;
  963. this.minWeight_ = void 0;
  964. this.minDelayMs_ = void 0;
  965. this.slow_ = void 0;
  966. this.fast_ = void 0;
  967. this.defaultTTFB_ = void 0;
  968. this.ttfb_ = void 0;
  969. this.defaultEstimate_ = defaultEstimate;
  970. this.minWeight_ = 0.001;
  971. this.minDelayMs_ = 50;
  972. this.slow_ = new EWMA(slow);
  973. this.fast_ = new EWMA(fast);
  974. this.defaultTTFB_ = defaultTTFB;
  975. this.ttfb_ = new EWMA(slow);
  976. }
  977. var _proto = EwmaBandWidthEstimator.prototype;
  978. _proto.update = function update(slow, fast) {
  979. var slow_ = this.slow_,
  980. fast_ = this.fast_,
  981. ttfb_ = this.ttfb_;
  982. if (slow_.halfLife !== slow) {
  983. this.slow_ = new EWMA(slow, slow_.getEstimate(), slow_.getTotalWeight());
  984. }
  985. if (fast_.halfLife !== fast) {
  986. this.fast_ = new EWMA(fast, fast_.getEstimate(), fast_.getTotalWeight());
  987. }
  988. if (ttfb_.halfLife !== slow) {
  989. this.ttfb_ = new EWMA(slow, ttfb_.getEstimate(), ttfb_.getTotalWeight());
  990. }
  991. };
  992. _proto.sample = function sample(durationMs, numBytes) {
  993. durationMs = Math.max(durationMs, this.minDelayMs_);
  994. var numBits = 8 * numBytes;
  995. // weight is duration in seconds
  996. var durationS = durationMs / 1000;
  997. // value is bandwidth in bits/s
  998. var bandwidthInBps = numBits / durationS;
  999. this.fast_.sample(durationS, bandwidthInBps);
  1000. this.slow_.sample(durationS, bandwidthInBps);
  1001. };
  1002. _proto.sampleTTFB = function sampleTTFB(ttfb) {
  1003. // weight is frequency curve applied to TTFB in seconds
  1004. // (longer times have less weight with expected input under 1 second)
  1005. var seconds = ttfb / 1000;
  1006. var weight = Math.sqrt(2) * Math.exp(-Math.pow(seconds, 2) / 2);
  1007. this.ttfb_.sample(weight, Math.max(ttfb, 5));
  1008. };
  1009. _proto.canEstimate = function canEstimate() {
  1010. return this.fast_.getTotalWeight() >= this.minWeight_;
  1011. };
  1012. _proto.getEstimate = function getEstimate() {
  1013. if (this.canEstimate()) {
  1014. // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));
  1015. // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));
  1016. // Take the minimum of these two estimates. This should have the effect of
  1017. // adapting down quickly, but up more slowly.
  1018. return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
  1019. } else {
  1020. return this.defaultEstimate_;
  1021. }
  1022. };
  1023. _proto.getEstimateTTFB = function getEstimateTTFB() {
  1024. if (this.ttfb_.getTotalWeight() >= this.minWeight_) {
  1025. return this.ttfb_.getEstimate();
  1026. } else {
  1027. return this.defaultTTFB_;
  1028. }
  1029. };
  1030. _proto.destroy = function destroy() {};
  1031. return _createClass(EwmaBandWidthEstimator, [{
  1032. key: "defaultEstimate",
  1033. get: function get() {
  1034. return this.defaultEstimate_;
  1035. }
  1036. }]);
  1037. }();
  1038. var Logger = function Logger(label, logger) {
  1039. this.trace = void 0;
  1040. this.debug = void 0;
  1041. this.log = void 0;
  1042. this.warn = void 0;
  1043. this.info = void 0;
  1044. this.error = void 0;
  1045. var lb = "[" + label + "]:";
  1046. this.trace = noop;
  1047. this.debug = logger.debug.bind(null, lb);
  1048. this.log = logger.log.bind(null, lb);
  1049. this.warn = logger.warn.bind(null, lb);
  1050. this.info = logger.info.bind(null, lb);
  1051. this.error = logger.error.bind(null, lb);
  1052. };
  1053. var noop = function noop() {};
  1054. var fakeLogger = {
  1055. trace: noop,
  1056. debug: noop,
  1057. log: noop,
  1058. warn: noop,
  1059. info: noop,
  1060. error: noop
  1061. };
  1062. function createLogger() {
  1063. return _extends({}, fakeLogger);
  1064. }
  1065. // let lastCallTime;
  1066. // function formatMsgWithTimeInfo(type, msg) {
  1067. // const now = Date.now();
  1068. // const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';
  1069. // lastCallTime = now;
  1070. // msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';
  1071. // return msg;
  1072. // }
  1073. function consolePrintFn(type, id) {
  1074. var func = self.console[type];
  1075. return func ? func.bind(self.console, (id ? '[' + id + '] ' : '') + "[" + type + "] >") : noop;
  1076. }
  1077. function getLoggerFn(key, debugConfig, id) {
  1078. return debugConfig[key] ? debugConfig[key].bind(debugConfig) : consolePrintFn(key, id);
  1079. }
  1080. var exportedLogger = createLogger();
  1081. function enableLogs(debugConfig, context, id) {
  1082. // check that console is available
  1083. var newLogger = createLogger();
  1084. if (typeof console === 'object' && debugConfig === true || typeof debugConfig === 'object') {
  1085. var keys = [
  1086. // Remove out from list here to hard-disable a log-level
  1087. // 'trace',
  1088. 'debug', 'log', 'info', 'warn', 'error'];
  1089. keys.forEach(function (key) {
  1090. newLogger[key] = getLoggerFn(key, debugConfig, id);
  1091. });
  1092. // Some browsers don't allow to use bind on console object anyway
  1093. // fallback to default if needed
  1094. try {
  1095. newLogger.log("Debug logs enabled for \"" + context + "\" in hls.js version " + "1.6.7");
  1096. } catch (e) {
  1097. /* log fn threw an exception. All logger methods are no-ops. */
  1098. return createLogger();
  1099. }
  1100. // global exported logger uses the same functions as new logger without `id`
  1101. keys.forEach(function (key) {
  1102. exportedLogger[key] = getLoggerFn(key, debugConfig);
  1103. });
  1104. } else {
  1105. // Reset global exported logger
  1106. _extends(exportedLogger, newLogger);
  1107. }
  1108. return newLogger;
  1109. }
  1110. var logger = exportedLogger;
  1111. var empty;
  1112. var hasRequiredEmpty;
  1113. function requireEmpty() {
  1114. if (hasRequiredEmpty) return empty;
  1115. hasRequiredEmpty = 1;
  1116. // This file is inserted as a shim for modules which we do not want to include into the distro.
  1117. // This replacement is done in the "alias" plugin of the rollup config.
  1118. empty = undefined;
  1119. return empty;
  1120. }
  1121. var emptyExports = requireEmpty();
  1122. var Cues = /*@__PURE__*/getDefaultExportFromCjs(emptyExports);
  1123. function getMediaSource(preferManagedMediaSource) {
  1124. if (preferManagedMediaSource === void 0) {
  1125. preferManagedMediaSource = true;
  1126. }
  1127. if (typeof self === 'undefined') return undefined;
  1128. var mms = (preferManagedMediaSource || !self.MediaSource) && self.ManagedMediaSource;
  1129. return mms || self.MediaSource || self.WebKitMediaSource;
  1130. }
  1131. function isManagedMediaSource(source) {
  1132. return typeof self !== 'undefined' && source === self.ManagedMediaSource;
  1133. }
  1134. function isCompatibleTrackChange(currentTracks, requiredTracks) {
  1135. var trackNames = Object.keys(currentTracks);
  1136. var requiredTrackNames = Object.keys(requiredTracks);
  1137. var trackCount = trackNames.length;
  1138. var requiredTrackCount = requiredTrackNames.length;
  1139. return !trackCount || !requiredTrackCount || trackCount === requiredTrackCount && !trackNames.some(function (name) {
  1140. return requiredTrackNames.indexOf(name) === -1;
  1141. });
  1142. }
  1143. // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197
  1144. // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
  1145. /* utf.js - UTF-8 <=> UTF-16 convertion
  1146. *
  1147. * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
  1148. * Version: 1.0
  1149. * LastModified: Dec 25 1999
  1150. * This library is free. You can redistribute it and/or modify it.
  1151. */
  1152. /**
  1153. * Converts a UTF-8 array to a string.
  1154. *
  1155. * @param array - The UTF-8 array to convert
  1156. *
  1157. * @returns The string
  1158. *
  1159. * @group Utils
  1160. *
  1161. * @beta
  1162. */
  1163. function utf8ArrayToStr(array, exitOnNull) {
  1164. if (exitOnNull === void 0) {
  1165. exitOnNull = false;
  1166. }
  1167. if (typeof TextDecoder !== 'undefined') {
  1168. var decoder = new TextDecoder('utf-8');
  1169. var decoded = decoder.decode(array);
  1170. if (exitOnNull) {
  1171. // grab up to the first null
  1172. var idx = decoded.indexOf('\0');
  1173. return idx !== -1 ? decoded.substring(0, idx) : decoded;
  1174. }
  1175. // remove any null characters
  1176. return decoded.replace(/\0/g, '');
  1177. }
  1178. var len = array.length;
  1179. var c;
  1180. var char2;
  1181. var char3;
  1182. var out = '';
  1183. var i = 0;
  1184. while (i < len) {
  1185. c = array[i++];
  1186. if (c === 0x00 && exitOnNull) {
  1187. return out;
  1188. } else if (c === 0x00 || c === 0x03) {
  1189. // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it
  1190. continue;
  1191. }
  1192. switch (c >> 4) {
  1193. case 0:
  1194. case 1:
  1195. case 2:
  1196. case 3:
  1197. case 4:
  1198. case 5:
  1199. case 6:
  1200. case 7:
  1201. // 0xxxxxxx
  1202. out += String.fromCharCode(c);
  1203. break;
  1204. case 12:
  1205. case 13:
  1206. // 110x xxxx 10xx xxxx
  1207. char2 = array[i++];
  1208. out += String.fromCharCode((c & 0x1f) << 6 | char2 & 0x3f);
  1209. break;
  1210. case 14:
  1211. // 1110 xxxx 10xx xxxx 10xx xxxx
  1212. char2 = array[i++];
  1213. char3 = array[i++];
  1214. out += String.fromCharCode((c & 0x0f) << 12 | (char2 & 0x3f) << 6 | (char3 & 0x3f) << 0);
  1215. break;
  1216. }
  1217. }
  1218. return out;
  1219. }
  1220. /**
  1221. * hex dump helper class
  1222. */
  1223. var Hex = {
  1224. hexDump: function hexDump(array) {
  1225. var str = '';
  1226. for (var i = 0; i < array.length; i++) {
  1227. var h = array[i].toString(16);
  1228. if (h.length < 2) {
  1229. h = '0' + h;
  1230. }
  1231. str += h;
  1232. }
  1233. return str;
  1234. }
  1235. };
  1236. function hexToArrayBuffer(str) {
  1237. return Uint8Array.from(str.replace(/^0x/, '').replace(/([\da-fA-F]{2}) ?/g, '0x$1 ').replace(/ +$/, '').split(' ')).buffer;
  1238. }
  1239. var LoadStats = function LoadStats() {
  1240. this.aborted = false;
  1241. this.loaded = 0;
  1242. this.retry = 0;
  1243. this.total = 0;
  1244. this.chunkCount = 0;
  1245. this.bwEstimate = 0;
  1246. this.loading = {
  1247. start: 0,
  1248. first: 0,
  1249. end: 0
  1250. };
  1251. this.parsing = {
  1252. start: 0,
  1253. end: 0
  1254. };
  1255. this.buffering = {
  1256. start: 0,
  1257. first: 0,
  1258. end: 0
  1259. };
  1260. };
  1261. var ElementaryStreamTypes = {
  1262. AUDIO: "audio",
  1263. VIDEO: "video",
  1264. AUDIOVIDEO: "audiovideo"
  1265. };
  1266. var BaseSegment = /*#__PURE__*/function () {
  1267. function BaseSegment(base) {
  1268. this._byteRange = null;
  1269. this._url = null;
  1270. this._stats = null;
  1271. this._streams = null;
  1272. // baseurl is the URL to the playlist
  1273. this.base = void 0;
  1274. // relurl is the portion of the URL that comes from inside the playlist.
  1275. this.relurl = void 0;
  1276. if (typeof base === 'string') {
  1277. base = {
  1278. url: base
  1279. };
  1280. }
  1281. this.base = base;
  1282. makeEnumerable(this, 'stats');
  1283. }
  1284. // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array
  1285. var _proto = BaseSegment.prototype;
  1286. _proto.setByteRange = function setByteRange(value, previous) {
  1287. var params = value.split('@', 2);
  1288. var start;
  1289. if (params.length === 1) {
  1290. start = (previous == null ? void 0 : previous.byteRangeEndOffset) || 0;
  1291. } else {
  1292. start = parseInt(params[1]);
  1293. }
  1294. this._byteRange = [start, parseInt(params[0]) + start];
  1295. };
  1296. _proto.clearElementaryStreamInfo = function clearElementaryStreamInfo() {
  1297. var elementaryStreams = this.elementaryStreams;
  1298. elementaryStreams[ElementaryStreamTypes.AUDIO] = null;
  1299. elementaryStreams[ElementaryStreamTypes.VIDEO] = null;
  1300. elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO] = null;
  1301. };
  1302. return _createClass(BaseSegment, [{
  1303. key: "baseurl",
  1304. get: function get() {
  1305. return this.base.url;
  1306. }
  1307. }, {
  1308. key: "byteRange",
  1309. get: function get() {
  1310. if (this._byteRange === null) {
  1311. return [];
  1312. }
  1313. return this._byteRange;
  1314. }
  1315. }, {
  1316. key: "byteRangeStartOffset",
  1317. get: function get() {
  1318. return this.byteRange[0];
  1319. }
  1320. }, {
  1321. key: "byteRangeEndOffset",
  1322. get: function get() {
  1323. return this.byteRange[1];
  1324. }
  1325. }, {
  1326. key: "elementaryStreams",
  1327. get: function get() {
  1328. if (this._streams === null) {
  1329. var _this$_streams;
  1330. this._streams = (_this$_streams = {}, _this$_streams[ElementaryStreamTypes.AUDIO] = null, _this$_streams[ElementaryStreamTypes.VIDEO] = null, _this$_streams[ElementaryStreamTypes.AUDIOVIDEO] = null, _this$_streams);
  1331. }
  1332. return this._streams;
  1333. },
  1334. set: function set(value) {
  1335. this._streams = value;
  1336. }
  1337. }, {
  1338. key: "hasStats",
  1339. get: function get() {
  1340. return this._stats !== null;
  1341. }
  1342. }, {
  1343. key: "hasStreams",
  1344. get: function get() {
  1345. return this._streams !== null;
  1346. }
  1347. }, {
  1348. key: "stats",
  1349. get: function get() {
  1350. if (this._stats === null) {
  1351. this._stats = new LoadStats();
  1352. }
  1353. return this._stats;
  1354. },
  1355. set: function set(value) {
  1356. this._stats = value;
  1357. }
  1358. }, {
  1359. key: "url",
  1360. get: function get() {
  1361. if (!this._url && this.baseurl && this.relurl) {
  1362. this._url = urlToolkitExports.buildAbsoluteURL(this.baseurl, this.relurl, {
  1363. alwaysNormalize: true
  1364. });
  1365. }
  1366. return this._url || '';
  1367. },
  1368. set: function set(value) {
  1369. this._url = value;
  1370. }
  1371. }]);
  1372. }();
  1373. function isMediaFragment(frag) {
  1374. return frag.sn !== 'initSegment';
  1375. }
  1376. /**
  1377. * Object representing parsed data from an HLS Segment. Found in {@link hls.js#LevelDetails.fragments}.
  1378. */
  1379. var Fragment = /*#__PURE__*/function (_BaseSegment2) {
  1380. function Fragment(type, base) {
  1381. var _this;
  1382. _this = _BaseSegment2.call(this, base) || this;
  1383. _this._decryptdata = null;
  1384. _this._programDateTime = null;
  1385. _this._ref = null;
  1386. // Approximate bit rate of the fragment expressed in bits per second (bps) as indicated by the last EXT-X-BITRATE (kbps) tag
  1387. _this._bitrate = void 0;
  1388. _this.rawProgramDateTime = null;
  1389. _this.tagList = [];
  1390. // EXTINF has to be present for a m3u8 to be considered valid
  1391. _this.duration = 0;
  1392. // sn notates the sequence number for a segment, and if set to a string can be 'initSegment'
  1393. _this.sn = 0;
  1394. // levelkeys are the EXT-X-KEY tags that apply to this segment for decryption
  1395. // core difference from the private field _decryptdata is the lack of the initialized IV
  1396. // _decryptdata will set the IV for this segment based on the segment number in the fragment
  1397. _this.levelkeys = void 0;
  1398. // A string representing the fragment type
  1399. _this.type = void 0;
  1400. // A reference to the loader. Set while the fragment is loading, and removed afterwards. Used to abort fragment loading
  1401. _this.loader = null;
  1402. // A reference to the key loader. Set while the key is loading, and removed afterwards. Used to abort key loading
  1403. _this.keyLoader = null;
  1404. // The level/track index to which the fragment belongs
  1405. _this.level = -1;
  1406. // The continuity counter of the fragment
  1407. _this.cc = 0;
  1408. // The starting Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.
  1409. _this.startPTS = void 0;
  1410. // The ending Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.
  1411. _this.endPTS = void 0;
  1412. // The starting Decode Time Stamp (DTS) of the fragment. Set after transmux complete.
  1413. _this.startDTS = void 0;
  1414. // The ending Decode Time Stamp (DTS) of the fragment. Set after transmux complete.
  1415. _this.endDTS = void 0;
  1416. // The start time of the fragment, as listed in the manifest. Updated after transmux complete.
  1417. _this.start = 0;
  1418. // The offset time (seconds) of the fragment from the start of the Playlist
  1419. _this.playlistOffset = 0;
  1420. // Set by `updateFragPTSDTS` in level-helper
  1421. _this.deltaPTS = void 0;
  1422. // The maximum starting Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.
  1423. _this.maxStartPTS = void 0;
  1424. // The minimum ending Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.
  1425. _this.minEndPTS = void 0;
  1426. // Init Segment bytes (unset for media segments)
  1427. _this.data = void 0;
  1428. // A flag indicating whether the segment was downloaded in order to test bitrate, and was not buffered
  1429. _this.bitrateTest = false;
  1430. // #EXTINF segment title
  1431. _this.title = null;
  1432. // The Media Initialization Section for this segment
  1433. _this.initSegment = null;
  1434. // Fragment is the last fragment in the media playlist
  1435. _this.endList = void 0;
  1436. // Fragment is marked by an EXT-X-GAP tag indicating that it does not contain media data and should not be loaded
  1437. _this.gap = void 0;
  1438. // Deprecated
  1439. _this.urlId = 0;
  1440. _this.type = type;
  1441. return _this;
  1442. }
  1443. _inheritsLoose(Fragment, _BaseSegment2);
  1444. var _proto2 = Fragment.prototype;
  1445. _proto2.addStart = function addStart(value) {
  1446. this.setStart(this.start + value);
  1447. };
  1448. _proto2.setStart = function setStart(value) {
  1449. this.start = value;
  1450. if (this._ref) {
  1451. this._ref.start = value;
  1452. }
  1453. };
  1454. _proto2.setDuration = function setDuration(value) {
  1455. this.duration = value;
  1456. if (this._ref) {
  1457. this._ref.duration = value;
  1458. }
  1459. };
  1460. _proto2.setKeyFormat = function setKeyFormat(keyFormat) {
  1461. if (this.levelkeys) {
  1462. var key = this.levelkeys[keyFormat];
  1463. if (key && !this._decryptdata) {
  1464. this._decryptdata = key.getDecryptData(this.sn);
  1465. }
  1466. }
  1467. };
  1468. _proto2.abortRequests = function abortRequests() {
  1469. var _this$loader, _this$keyLoader;
  1470. (_this$loader = this.loader) == null ? void 0 : _this$loader.abort();
  1471. (_this$keyLoader = this.keyLoader) == null ? void 0 : _this$keyLoader.abort();
  1472. };
  1473. _proto2.setElementaryStreamInfo = function setElementaryStreamInfo(type, startPTS, endPTS, startDTS, endDTS, partial) {
  1474. if (partial === void 0) {
  1475. partial = false;
  1476. }
  1477. var elementaryStreams = this.elementaryStreams;
  1478. var info = elementaryStreams[type];
  1479. if (!info) {
  1480. elementaryStreams[type] = {
  1481. startPTS: startPTS,
  1482. endPTS: endPTS,
  1483. startDTS: startDTS,
  1484. endDTS: endDTS,
  1485. partial: partial
  1486. };
  1487. return;
  1488. }
  1489. info.startPTS = Math.min(info.startPTS, startPTS);
  1490. info.endPTS = Math.max(info.endPTS, endPTS);
  1491. info.startDTS = Math.min(info.startDTS, startDTS);
  1492. info.endDTS = Math.max(info.endDTS, endDTS);
  1493. };
  1494. return _createClass(Fragment, [{
  1495. key: "byteLength",
  1496. get: function get() {
  1497. if (this.hasStats) {
  1498. var total = this.stats.total;
  1499. if (total) {
  1500. return total;
  1501. }
  1502. }
  1503. if (this.byteRange) {
  1504. var start = this.byteRange[0];
  1505. var end = this.byteRange[1];
  1506. if (isFiniteNumber(start) && isFiniteNumber(end)) {
  1507. return end - start;
  1508. }
  1509. }
  1510. return null;
  1511. }
  1512. }, {
  1513. key: "bitrate",
  1514. get: function get() {
  1515. if (this.byteLength) {
  1516. return this.byteLength * 8 / this.duration;
  1517. }
  1518. if (this._bitrate) {
  1519. return this._bitrate;
  1520. }
  1521. return null;
  1522. },
  1523. set: function set(value) {
  1524. this._bitrate = value;
  1525. }
  1526. }, {
  1527. key: "decryptdata",
  1528. get: function get() {
  1529. var levelkeys = this.levelkeys;
  1530. if (!levelkeys && !this._decryptdata) {
  1531. return null;
  1532. }
  1533. if (!this._decryptdata && this.levelkeys && !this.levelkeys.NONE) {
  1534. var key = this.levelkeys.identity;
  1535. if (key) {
  1536. this._decryptdata = key.getDecryptData(this.sn);
  1537. } else {
  1538. var keyFormats = Object.keys(this.levelkeys);
  1539. if (keyFormats.length === 1) {
  1540. return this._decryptdata = this.levelkeys[keyFormats[0]].getDecryptData(this.sn);
  1541. }
  1542. }
  1543. }
  1544. return this._decryptdata;
  1545. }
  1546. }, {
  1547. key: "end",
  1548. get: function get() {
  1549. return this.start + this.duration;
  1550. }
  1551. }, {
  1552. key: "endProgramDateTime",
  1553. get: function get() {
  1554. if (this.programDateTime === null) {
  1555. return null;
  1556. }
  1557. var duration = !isFiniteNumber(this.duration) ? 0 : this.duration;
  1558. return this.programDateTime + duration * 1000;
  1559. }
  1560. }, {
  1561. key: "encrypted",
  1562. get: function get() {
  1563. var _this$_decryptdata;
  1564. // At the m3u8-parser level we need to add support for manifest signalled keyformats
  1565. // when we want the fragment to start reporting that it is encrypted.
  1566. // Currently, keyFormat will only be set for identity keys
  1567. if ((_this$_decryptdata = this._decryptdata) != null && _this$_decryptdata.encrypted) {
  1568. return true;
  1569. } else if (this.levelkeys) {
  1570. var keyFormats = Object.keys(this.levelkeys);
  1571. var len = keyFormats.length;
  1572. if (len > 1 || len === 1 && this.levelkeys[keyFormats[0]].encrypted) {
  1573. return true;
  1574. }
  1575. }
  1576. return false;
  1577. }
  1578. }, {
  1579. key: "programDateTime",
  1580. get: function get() {
  1581. if (this._programDateTime === null && this.rawProgramDateTime) {
  1582. this.programDateTime = Date.parse(this.rawProgramDateTime);
  1583. }
  1584. return this._programDateTime;
  1585. },
  1586. set: function set(value) {
  1587. if (!isFiniteNumber(value)) {
  1588. this._programDateTime = this.rawProgramDateTime = null;
  1589. return;
  1590. }
  1591. this._programDateTime = value;
  1592. }
  1593. }, {
  1594. key: "ref",
  1595. get: function get() {
  1596. if (!isMediaFragment(this)) {
  1597. return null;
  1598. }
  1599. if (!this._ref) {
  1600. this._ref = {
  1601. base: this.base,
  1602. start: this.start,
  1603. duration: this.duration,
  1604. sn: this.sn,
  1605. programDateTime: this.programDateTime
  1606. };
  1607. }
  1608. return this._ref;
  1609. }
  1610. }]);
  1611. }(BaseSegment);
  1612. /**
  1613. * Object representing parsed data from an HLS Partial Segment. Found in {@link hls.js#LevelDetails.partList}.
  1614. */
  1615. var Part = /*#__PURE__*/function (_BaseSegment3) {
  1616. function Part(partAttrs, frag, base, index, previous) {
  1617. var _this2;
  1618. _this2 = _BaseSegment3.call(this, base) || this;
  1619. _this2.fragOffset = 0;
  1620. _this2.duration = 0;
  1621. _this2.gap = false;
  1622. _this2.independent = false;
  1623. _this2.relurl = void 0;
  1624. _this2.fragment = void 0;
  1625. _this2.index = void 0;
  1626. _this2.duration = partAttrs.decimalFloatingPoint('DURATION');
  1627. _this2.gap = partAttrs.bool('GAP');
  1628. _this2.independent = partAttrs.bool('INDEPENDENT');
  1629. _this2.relurl = partAttrs.enumeratedString('URI');
  1630. _this2.fragment = frag;
  1631. _this2.index = index;
  1632. var byteRange = partAttrs.enumeratedString('BYTERANGE');
  1633. if (byteRange) {
  1634. _this2.setByteRange(byteRange, previous);
  1635. }
  1636. if (previous) {
  1637. _this2.fragOffset = previous.fragOffset + previous.duration;
  1638. }
  1639. return _this2;
  1640. }
  1641. _inheritsLoose(Part, _BaseSegment3);
  1642. return _createClass(Part, [{
  1643. key: "start",
  1644. get: function get() {
  1645. return this.fragment.start + this.fragOffset;
  1646. }
  1647. }, {
  1648. key: "end",
  1649. get: function get() {
  1650. return this.start + this.duration;
  1651. }
  1652. }, {
  1653. key: "loaded",
  1654. get: function get() {
  1655. var elementaryStreams = this.elementaryStreams;
  1656. return !!(elementaryStreams.audio || elementaryStreams.video || elementaryStreams.audiovideo);
  1657. }
  1658. }]);
  1659. }(BaseSegment);
  1660. function getOwnPropertyDescriptorFromPrototypeChain(object, property) {
  1661. var prototype = Object.getPrototypeOf(object);
  1662. if (prototype) {
  1663. var propertyDescriptor = Object.getOwnPropertyDescriptor(prototype, property);
  1664. if (propertyDescriptor) {
  1665. return propertyDescriptor;
  1666. }
  1667. return getOwnPropertyDescriptorFromPrototypeChain(prototype, property);
  1668. }
  1669. }
  1670. function makeEnumerable(object, property) {
  1671. var d = getOwnPropertyDescriptorFromPrototypeChain(object, property);
  1672. if (d) {
  1673. d.enumerable = true;
  1674. Object.defineProperty(object, property, d);
  1675. }
  1676. }
  1677. var UINT32_MAX$1 = Math.pow(2, 32) - 1;
  1678. var push = [].push;
  1679. // We are using fixed track IDs for driving the MP4 remuxer
  1680. // instead of following the TS PIDs.
  1681. // There is no reason not to do this and some browsers/SourceBuffer-demuxers
  1682. // may not like if there are TrackID "switches"
  1683. // See https://github.com/video-dev/hls.js/issues/1331
  1684. // Here we are mapping our internal track types to constant MP4 track IDs
  1685. // With MSE currently one can only have one track of each, and we are muxing
  1686. // whatever video/audio rendition in them.
  1687. var RemuxerTrackIdConfig = {
  1688. video: 1,
  1689. audio: 2,
  1690. id3: 3,
  1691. text: 4
  1692. };
  1693. function bin2str(data) {
  1694. return String.fromCharCode.apply(null, data);
  1695. }
  1696. function readUint16(buffer, offset) {
  1697. var val = buffer[offset] << 8 | buffer[offset + 1];
  1698. return val < 0 ? 65536 + val : val;
  1699. }
  1700. function readUint32(buffer, offset) {
  1701. var val = readSint32(buffer, offset);
  1702. return val < 0 ? 4294967296 + val : val;
  1703. }
  1704. function readUint64(buffer, offset) {
  1705. var result = readUint32(buffer, offset);
  1706. result *= Math.pow(2, 32);
  1707. result += readUint32(buffer, offset + 4);
  1708. return result;
  1709. }
  1710. function readSint32(buffer, offset) {
  1711. return buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];
  1712. }
  1713. // Find "moof" box
  1714. function hasMoofData(data) {
  1715. var end = data.byteLength;
  1716. for (var i = 0; i < end;) {
  1717. var size = readUint32(data, i);
  1718. if (size > 8 && data[i + 4] === 0x6d && data[i + 5] === 0x6f && data[i + 6] === 0x6f && data[i + 7] === 0x66) {
  1719. return true;
  1720. }
  1721. i = size > 1 ? i + size : end;
  1722. }
  1723. return false;
  1724. }
  1725. // Find the data for a box specified by its path
  1726. function findBox(data, path) {
  1727. var results = [];
  1728. if (!path.length) {
  1729. // short-circuit the search for empty paths
  1730. return results;
  1731. }
  1732. var end = data.byteLength;
  1733. for (var i = 0; i < end;) {
  1734. var size = readUint32(data, i);
  1735. var type = bin2str(data.subarray(i + 4, i + 8));
  1736. var endbox = size > 1 ? i + size : end;
  1737. if (type === path[0]) {
  1738. if (path.length === 1) {
  1739. // this is the end of the path and we've found the box we were
  1740. // looking for
  1741. results.push(data.subarray(i + 8, endbox));
  1742. } else {
  1743. // recursively search for the next box along the path
  1744. var subresults = findBox(data.subarray(i + 8, endbox), path.slice(1));
  1745. if (subresults.length) {
  1746. push.apply(results, subresults);
  1747. }
  1748. }
  1749. }
  1750. i = endbox;
  1751. }
  1752. // we've finished searching all of data
  1753. return results;
  1754. }
  1755. function parseSegmentIndex(sidx) {
  1756. var references = [];
  1757. var version = sidx[0];
  1758. // set initial offset, we skip the reference ID (not needed)
  1759. var index = 8;
  1760. var timescale = readUint32(sidx, index);
  1761. index += 4;
  1762. var earliestPresentationTime = 0;
  1763. var firstOffset = 0;
  1764. if (version === 0) {
  1765. earliestPresentationTime = readUint32(sidx, index);
  1766. firstOffset = readUint32(sidx, index + 4);
  1767. index += 8;
  1768. } else {
  1769. earliestPresentationTime = readUint64(sidx, index);
  1770. firstOffset = readUint64(sidx, index + 8);
  1771. index += 16;
  1772. }
  1773. // skip reserved
  1774. index += 2;
  1775. var startByte = sidx.length + firstOffset;
  1776. var referencesCount = readUint16(sidx, index);
  1777. index += 2;
  1778. for (var i = 0; i < referencesCount; i++) {
  1779. var referenceIndex = index;
  1780. var referenceInfo = readUint32(sidx, referenceIndex);
  1781. referenceIndex += 4;
  1782. var referenceSize = referenceInfo & 0x7fffffff;
  1783. var referenceType = (referenceInfo & 0x80000000) >>> 31;
  1784. if (referenceType === 1) {
  1785. logger.warn('SIDX has hierarchical references (not supported)');
  1786. return null;
  1787. }
  1788. var subsegmentDuration = readUint32(sidx, referenceIndex);
  1789. referenceIndex += 4;
  1790. references.push({
  1791. referenceSize: referenceSize,
  1792. subsegmentDuration: subsegmentDuration,
  1793. // unscaled
  1794. info: {
  1795. duration: subsegmentDuration / timescale,
  1796. start: startByte,
  1797. end: startByte + referenceSize - 1
  1798. }
  1799. });
  1800. startByte += referenceSize;
  1801. // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits
  1802. // for |sapDelta|.
  1803. referenceIndex += 4;
  1804. // skip to next ref
  1805. index = referenceIndex;
  1806. }
  1807. return {
  1808. earliestPresentationTime: earliestPresentationTime,
  1809. timescale: timescale,
  1810. version: version,
  1811. referencesCount: referencesCount,
  1812. references: references
  1813. };
  1814. }
  1815. /**
  1816. * Parses an MP4 initialization segment and extracts stream type and
  1817. * timescale values for any declared tracks. Timescale values indicate the
  1818. * number of clock ticks per second to assume for time-based values
  1819. * elsewhere in the MP4.
  1820. *
  1821. * To determine the start time of an MP4, you need two pieces of
  1822. * information: the timescale unit and the earliest base media decode
  1823. * time. Multiple timescales can be specified within an MP4 but the
  1824. * base media decode time is always expressed in the timescale from
  1825. * the media header box for the track:
  1826. * ```
  1827. * moov > trak > mdia > mdhd.timescale
  1828. * moov > trak > mdia > hdlr
  1829. * ```
  1830. * @param initSegment the bytes of the init segment
  1831. * @returns a hash of track type to timescale values or null if
  1832. * the init segment is malformed.
  1833. */
  1834. function parseInitSegment(initSegment) {
  1835. var result = [];
  1836. var traks = findBox(initSegment, ['moov', 'trak']);
  1837. for (var i = 0; i < traks.length; i++) {
  1838. var trak = traks[i];
  1839. var tkhd = findBox(trak, ['tkhd'])[0];
  1840. if (tkhd) {
  1841. var version = tkhd[0];
  1842. var trackId = readUint32(tkhd, version === 0 ? 12 : 20);
  1843. var mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  1844. if (mdhd) {
  1845. version = mdhd[0];
  1846. var timescale = readUint32(mdhd, version === 0 ? 12 : 20);
  1847. var hdlr = findBox(trak, ['mdia', 'hdlr'])[0];
  1848. if (hdlr) {
  1849. var hdlrType = bin2str(hdlr.subarray(8, 12));
  1850. var type = {
  1851. soun: ElementaryStreamTypes.AUDIO,
  1852. vide: ElementaryStreamTypes.VIDEO
  1853. }[hdlrType];
  1854. // Parse codec details
  1855. var stsdBox = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  1856. var stsd = parseStsd(stsdBox);
  1857. if (type) {
  1858. // Add 'audio', 'video', and 'audiovideo' track records that will map to SourceBuffers
  1859. result[trackId] = {
  1860. timescale: timescale,
  1861. type: type,
  1862. stsd: stsd
  1863. };
  1864. result[type] = _objectSpread2({
  1865. timescale: timescale,
  1866. id: trackId
  1867. }, stsd);
  1868. } else {
  1869. // Add 'meta' and other track records
  1870. result[trackId] = {
  1871. timescale: timescale,
  1872. type: hdlrType,
  1873. stsd: stsd
  1874. };
  1875. }
  1876. }
  1877. }
  1878. }
  1879. }
  1880. var trex = findBox(initSegment, ['moov', 'mvex', 'trex']);
  1881. trex.forEach(function (trex) {
  1882. var trackId = readUint32(trex, 4);
  1883. var track = result[trackId];
  1884. if (track) {
  1885. track.default = {
  1886. duration: readUint32(trex, 12),
  1887. flags: readUint32(trex, 20)
  1888. };
  1889. }
  1890. });
  1891. return result;
  1892. }
  1893. function parseStsd(stsd) {
  1894. var sampleEntries = stsd.subarray(8);
  1895. var sampleEntriesEnd = sampleEntries.subarray(8 + 78);
  1896. var fourCC = bin2str(sampleEntries.subarray(4, 8));
  1897. var codec = fourCC;
  1898. var supplemental;
  1899. var encrypted = fourCC === 'enca' || fourCC === 'encv';
  1900. if (encrypted) {
  1901. var encBox = findBox(sampleEntries, [fourCC])[0];
  1902. var encBoxChildren = encBox.subarray(fourCC === 'enca' ? 28 : 78);
  1903. var sinfs = findBox(encBoxChildren, ['sinf']);
  1904. sinfs.forEach(function (sinf) {
  1905. var schm = findBox(sinf, ['schm'])[0];
  1906. if (schm) {
  1907. var scheme = bin2str(schm.subarray(4, 8));
  1908. if (scheme === 'cbcs' || scheme === 'cenc') {
  1909. var frma = findBox(sinf, ['frma'])[0];
  1910. if (frma) {
  1911. // for encrypted content codec fourCC will be in frma
  1912. codec = bin2str(frma);
  1913. }
  1914. }
  1915. }
  1916. });
  1917. }
  1918. var codecFourCC = codec;
  1919. switch (codec) {
  1920. case 'avc1':
  1921. case 'avc2':
  1922. case 'avc3':
  1923. case 'avc4':
  1924. {
  1925. // extract profile + compatibility + level out of avcC box
  1926. var avcCBox = findBox(sampleEntriesEnd, ['avcC'])[0];
  1927. if (avcCBox && avcCBox.length > 3) {
  1928. codec += '.' + toHex(avcCBox[1]) + toHex(avcCBox[2]) + toHex(avcCBox[3]);
  1929. supplemental = parseSupplementalDoViCodec(codecFourCC === 'avc1' ? 'dva1' : 'dvav', sampleEntriesEnd);
  1930. }
  1931. break;
  1932. }
  1933. case 'mp4a':
  1934. {
  1935. var codecBox = findBox(sampleEntries, [fourCC])[0];
  1936. var esdsBox = findBox(codecBox.subarray(28), ['esds'])[0];
  1937. if (esdsBox && esdsBox.length > 7) {
  1938. var i = 4;
  1939. // ES Descriptor tag
  1940. if (esdsBox[i++] !== 0x03) {
  1941. break;
  1942. }
  1943. i = skipBERInteger(esdsBox, i);
  1944. i += 2; // skip es_id;
  1945. var flags = esdsBox[i++];
  1946. if (flags & 0x80) {
  1947. i += 2; // skip dependency es_id
  1948. }
  1949. if (flags & 0x40) {
  1950. i += esdsBox[i++]; // skip URL
  1951. }
  1952. // Decoder config descriptor
  1953. if (esdsBox[i++] !== 0x04) {
  1954. break;
  1955. }
  1956. i = skipBERInteger(esdsBox, i);
  1957. var objectType = esdsBox[i++];
  1958. if (objectType === 0x40) {
  1959. codec += '.' + toHex(objectType);
  1960. } else {
  1961. break;
  1962. }
  1963. i += 12;
  1964. // Decoder specific info
  1965. if (esdsBox[i++] !== 0x05) {
  1966. break;
  1967. }
  1968. i = skipBERInteger(esdsBox, i);
  1969. var firstByte = esdsBox[i++];
  1970. var audioObjectType = (firstByte & 0xf8) >> 3;
  1971. if (audioObjectType === 31) {
  1972. audioObjectType += 1 + ((firstByte & 0x7) << 3) + ((esdsBox[i] & 0xe0) >> 5);
  1973. }
  1974. codec += '.' + audioObjectType;
  1975. }
  1976. break;
  1977. }
  1978. case 'hvc1':
  1979. case 'hev1':
  1980. {
  1981. var hvcCBox = findBox(sampleEntriesEnd, ['hvcC'])[0];
  1982. if (hvcCBox && hvcCBox.length > 12) {
  1983. var profileByte = hvcCBox[1];
  1984. var profileSpace = ['', 'A', 'B', 'C'][profileByte >> 6];
  1985. var generalProfileIdc = profileByte & 0x1f;
  1986. var profileCompat = readUint32(hvcCBox, 2);
  1987. var tierFlag = (profileByte & 0x20) >> 5 ? 'H' : 'L';
  1988. var levelIDC = hvcCBox[12];
  1989. var constraintIndicator = hvcCBox.subarray(6, 12);
  1990. codec += '.' + profileSpace + generalProfileIdc;
  1991. codec += '.' + reverse32BitInt(profileCompat).toString(16).toUpperCase();
  1992. codec += '.' + tierFlag + levelIDC;
  1993. var constraintString = '';
  1994. for (var _i = constraintIndicator.length; _i--;) {
  1995. var _byte = constraintIndicator[_i];
  1996. if (_byte || constraintString) {
  1997. var encodedByte = _byte.toString(16).toUpperCase();
  1998. constraintString = '.' + encodedByte + constraintString;
  1999. }
  2000. }
  2001. codec += constraintString;
  2002. }
  2003. supplemental = parseSupplementalDoViCodec(codecFourCC == 'hev1' ? 'dvhe' : 'dvh1', sampleEntriesEnd);
  2004. break;
  2005. }
  2006. case 'dvh1':
  2007. case 'dvhe':
  2008. case 'dvav':
  2009. case 'dva1':
  2010. case 'dav1':
  2011. {
  2012. codec = parseSupplementalDoViCodec(codec, sampleEntriesEnd) || codec;
  2013. break;
  2014. }
  2015. case 'vp09':
  2016. {
  2017. var vpcCBox = findBox(sampleEntriesEnd, ['vpcC'])[0];
  2018. if (vpcCBox && vpcCBox.length > 6) {
  2019. var profile = vpcCBox[4];
  2020. var level = vpcCBox[5];
  2021. var bitDepth = vpcCBox[6] >> 4 & 0x0f;
  2022. codec += '.' + addLeadingZero(profile) + '.' + addLeadingZero(level) + '.' + addLeadingZero(bitDepth);
  2023. }
  2024. break;
  2025. }
  2026. case 'av01':
  2027. {
  2028. var av1CBox = findBox(sampleEntriesEnd, ['av1C'])[0];
  2029. if (av1CBox && av1CBox.length > 2) {
  2030. var _profile = av1CBox[1] >>> 5;
  2031. var _level = av1CBox[1] & 0x1f;
  2032. var _tierFlag = av1CBox[2] >>> 7 ? 'H' : 'M';
  2033. var highBitDepth = (av1CBox[2] & 0x40) >> 6;
  2034. var twelveBit = (av1CBox[2] & 0x20) >> 5;
  2035. var _bitDepth = _profile === 2 && highBitDepth ? twelveBit ? 12 : 10 : highBitDepth ? 10 : 8;
  2036. var monochrome = (av1CBox[2] & 0x10) >> 4;
  2037. var chromaSubsamplingX = (av1CBox[2] & 0x08) >> 3;
  2038. var chromaSubsamplingY = (av1CBox[2] & 0x04) >> 2;
  2039. var chromaSamplePosition = av1CBox[2] & 0x03;
  2040. // TODO: parse color_description_present_flag
  2041. // default it to BT.709/limited range for now
  2042. // more info https://aomediacodec.github.io/av1-isobmff/#av1codecconfigurationbox-syntax
  2043. var colorPrimaries = 1;
  2044. var transferCharacteristics = 1;
  2045. var matrixCoefficients = 1;
  2046. var videoFullRangeFlag = 0;
  2047. codec += '.' + _profile + '.' + addLeadingZero(_level) + _tierFlag + '.' + addLeadingZero(_bitDepth) + '.' + monochrome + '.' + chromaSubsamplingX + chromaSubsamplingY + chromaSamplePosition + '.' + addLeadingZero(colorPrimaries) + '.' + addLeadingZero(transferCharacteristics) + '.' + addLeadingZero(matrixCoefficients) + '.' + videoFullRangeFlag;
  2048. supplemental = parseSupplementalDoViCodec('dav1', sampleEntriesEnd);
  2049. }
  2050. break;
  2051. }
  2052. }
  2053. return {
  2054. codec: codec,
  2055. encrypted: encrypted,
  2056. supplemental: supplemental
  2057. };
  2058. }
  2059. function parseSupplementalDoViCodec(fourCC, sampleEntriesEnd) {
  2060. var dvvCResult = findBox(sampleEntriesEnd, ['dvvC']); // used by DoVi Profile 8 to 10
  2061. var dvXCBox = dvvCResult.length ? dvvCResult[0] : findBox(sampleEntriesEnd, ['dvcC'])[0]; // used by DoVi Profiles up to 7 and 20
  2062. if (dvXCBox) {
  2063. var doViProfile = dvXCBox[2] >> 1 & 0x7f;
  2064. var doViLevel = dvXCBox[2] << 5 & 0x20 | dvXCBox[3] >> 3 & 0x1f;
  2065. return fourCC + '.' + addLeadingZero(doViProfile) + '.' + addLeadingZero(doViLevel);
  2066. }
  2067. }
  2068. function reverse32BitInt(val) {
  2069. var result = 0;
  2070. for (var i = 0; i < 32; i++) {
  2071. result |= (val >> i & 1) << 32 - 1 - i;
  2072. }
  2073. return result >>> 0;
  2074. }
  2075. function skipBERInteger(bytes, i) {
  2076. var limit = i + 5;
  2077. while (bytes[i++] & 0x80 && i < limit) {
  2078. /* do nothing */
  2079. }
  2080. return i;
  2081. }
  2082. function toHex(x) {
  2083. return ('0' + x.toString(16).toUpperCase()).slice(-2);
  2084. }
  2085. function addLeadingZero(num) {
  2086. return (num < 10 ? '0' : '') + num;
  2087. }
  2088. function patchEncyptionData(initSegment, decryptdata) {
  2089. if (!initSegment || !decryptdata) {
  2090. return initSegment;
  2091. }
  2092. var keyId = decryptdata.keyId;
  2093. if (keyId && decryptdata.isCommonEncryption) {
  2094. var traks = findBox(initSegment, ['moov', 'trak']);
  2095. traks.forEach(function (trak) {
  2096. var stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  2097. // skip the sample entry count
  2098. var sampleEntries = stsd.subarray(8);
  2099. var encBoxes = findBox(sampleEntries, ['enca']);
  2100. var isAudio = encBoxes.length > 0;
  2101. if (!isAudio) {
  2102. encBoxes = findBox(sampleEntries, ['encv']);
  2103. }
  2104. encBoxes.forEach(function (enc) {
  2105. var encBoxChildren = isAudio ? enc.subarray(28) : enc.subarray(78);
  2106. var sinfBoxes = findBox(encBoxChildren, ['sinf']);
  2107. sinfBoxes.forEach(function (sinf) {
  2108. var tenc = parseSinf(sinf);
  2109. if (tenc) {
  2110. // Look for default key id (keyID offset is always 8 within the tenc box):
  2111. var tencKeyId = tenc.subarray(8, 24);
  2112. if (!tencKeyId.some(function (b) {
  2113. return b !== 0;
  2114. })) {
  2115. logger.log("[eme] Patching keyId in 'enc" + (isAudio ? 'a' : 'v') + ">sinf>>tenc' box: " + Hex.hexDump(tencKeyId) + " -> " + Hex.hexDump(keyId));
  2116. tenc.set(keyId, 8);
  2117. }
  2118. }
  2119. });
  2120. });
  2121. });
  2122. }
  2123. return initSegment;
  2124. }
  2125. function parseSinf(sinf) {
  2126. var schm = findBox(sinf, ['schm'])[0];
  2127. if (schm) {
  2128. var scheme = bin2str(schm.subarray(4, 8));
  2129. if (scheme === 'cbcs' || scheme === 'cenc') {
  2130. return findBox(sinf, ['schi', 'tenc'])[0];
  2131. }
  2132. }
  2133. return null;
  2134. }
  2135. /*
  2136. For Reference:
  2137. aligned(8) class TrackFragmentHeaderBox
  2138. extends FullBox(‘tfhd’, 0, tf_flags){
  2139. unsigned int(32) track_ID;
  2140. // all the following are optional fields
  2141. unsigned int(64) base_data_offset;
  2142. unsigned int(32) sample_description_index;
  2143. unsigned int(32) default_sample_duration;
  2144. unsigned int(32) default_sample_size;
  2145. unsigned int(32) default_sample_flags
  2146. }
  2147. */
  2148. function getSampleData(data, initData, logger) {
  2149. var tracks = {};
  2150. var trafs = findBox(data, ['moof', 'traf']);
  2151. for (var i = 0; i < trafs.length; i++) {
  2152. var traf = trafs[i];
  2153. // There is only one tfhd & trun per traf
  2154. // This is true for CMAF style content, and we should perhaps check the ftyp
  2155. // and only look for a single trun then, but for ISOBMFF we should check
  2156. // for multiple track runs.
  2157. var tfhd = findBox(traf, ['tfhd'])[0];
  2158. // get the track id from the tfhd
  2159. var id = readUint32(tfhd, 4);
  2160. var track = initData[id];
  2161. if (!track) {
  2162. continue;
  2163. }
  2164. var trackTimes = tracks[id] || (tracks[id] = {
  2165. start: NaN,
  2166. duration: 0,
  2167. sampleCount: 0,
  2168. timescale: track.timescale,
  2169. type: track.type
  2170. });
  2171. // get start DTS
  2172. var tfdt = findBox(traf, ['tfdt'])[0];
  2173. if (tfdt) {
  2174. var version = tfdt[0];
  2175. var baseTime = readUint32(tfdt, 4);
  2176. if (version === 1) {
  2177. // If value is too large, assume signed 64-bit. Negative track fragment decode times are invalid, but they exist in the wild.
  2178. // This prevents large values from being used for initPTS, which can cause playlist sync issues.
  2179. // https://github.com/video-dev/hls.js/issues/5303
  2180. if (baseTime === UINT32_MAX$1) {
  2181. logger.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time");
  2182. } else {
  2183. baseTime *= UINT32_MAX$1 + 1;
  2184. baseTime += readUint32(tfdt, 8);
  2185. }
  2186. }
  2187. if (isFiniteNumber(baseTime) && (!isFiniteNumber(trackTimes.start) || baseTime < trackTimes.start)) {
  2188. trackTimes.start = baseTime;
  2189. }
  2190. }
  2191. var trackDefault = track.default;
  2192. var tfhdFlags = readUint32(tfhd, 0) | (trackDefault == null ? void 0 : trackDefault.flags);
  2193. var defaultSampleDuration = (trackDefault == null ? void 0 : trackDefault.duration) || 0;
  2194. if (tfhdFlags & 0x000008) {
  2195. // 0x000008 indicates the presence of the default_sample_duration field
  2196. if (tfhdFlags & 0x000002) {
  2197. // 0x000002 indicates the presence of the sample_description_index field, which precedes default_sample_duration
  2198. // If present, the default_sample_duration exists at byte offset 12
  2199. defaultSampleDuration = readUint32(tfhd, 12);
  2200. } else {
  2201. // Otherwise, the duration is at byte offset 8
  2202. defaultSampleDuration = readUint32(tfhd, 8);
  2203. }
  2204. }
  2205. var truns = findBox(traf, ['trun']);
  2206. var sampleDTS = trackTimes.start || 0;
  2207. var rawDuration = 0;
  2208. var sampleDuration = defaultSampleDuration;
  2209. for (var j = 0; j < truns.length; j++) {
  2210. var trun = truns[j];
  2211. var sampleCount = readUint32(trun, 4);
  2212. var sampleIndex = trackTimes.sampleCount;
  2213. trackTimes.sampleCount += sampleCount;
  2214. // Get duration from samples
  2215. var dataOffsetPresent = trun[3] & 0x01;
  2216. var firstSampleFlagsPresent = trun[3] & 0x04;
  2217. var sampleDurationPresent = trun[2] & 0x01;
  2218. var sampleSizePresent = trun[2] & 0x02;
  2219. var sampleFlagsPresent = trun[2] & 0x04;
  2220. var sampleCompositionTimeOffsetPresent = trun[2] & 0x08;
  2221. var offset = 8;
  2222. var remaining = sampleCount;
  2223. if (dataOffsetPresent) {
  2224. offset += 4;
  2225. }
  2226. if (firstSampleFlagsPresent && sampleCount) {
  2227. var isNonSyncSample = trun[offset + 1] & 0x01;
  2228. if (!isNonSyncSample && trackTimes.keyFrameIndex === undefined) {
  2229. trackTimes.keyFrameIndex = sampleIndex;
  2230. }
  2231. offset += 4;
  2232. if (sampleDurationPresent) {
  2233. sampleDuration = readUint32(trun, offset);
  2234. offset += 4;
  2235. } else {
  2236. sampleDuration = defaultSampleDuration;
  2237. }
  2238. if (sampleSizePresent) {
  2239. offset += 4;
  2240. }
  2241. if (sampleCompositionTimeOffsetPresent) {
  2242. offset += 4;
  2243. }
  2244. sampleDTS += sampleDuration;
  2245. rawDuration += sampleDuration;
  2246. remaining--;
  2247. }
  2248. while (remaining--) {
  2249. if (sampleDurationPresent) {
  2250. sampleDuration = readUint32(trun, offset);
  2251. offset += 4;
  2252. } else {
  2253. sampleDuration = defaultSampleDuration;
  2254. }
  2255. if (sampleSizePresent) {
  2256. offset += 4;
  2257. }
  2258. if (sampleFlagsPresent) {
  2259. var _isNonSyncSample = trun[offset + 1] & 0x01;
  2260. if (!_isNonSyncSample) {
  2261. if (trackTimes.keyFrameIndex === undefined) {
  2262. trackTimes.keyFrameIndex = trackTimes.sampleCount - (remaining + 1);
  2263. trackTimes.keyFrameStart = sampleDTS;
  2264. }
  2265. }
  2266. offset += 4;
  2267. }
  2268. if (sampleCompositionTimeOffsetPresent) {
  2269. offset += 4;
  2270. }
  2271. sampleDTS += sampleDuration;
  2272. rawDuration += sampleDuration;
  2273. }
  2274. if (!rawDuration && defaultSampleDuration) {
  2275. rawDuration += defaultSampleDuration * sampleCount;
  2276. }
  2277. }
  2278. trackTimes.duration += rawDuration;
  2279. }
  2280. if (!Object.keys(tracks).some(function (trackId) {
  2281. return tracks[trackId].duration;
  2282. })) {
  2283. // If duration samples are not available in the traf use sidx subsegment_duration
  2284. var sidxMinStart = Infinity;
  2285. var sidxMaxEnd = 0;
  2286. var sidxs = findBox(data, ['sidx']);
  2287. for (var _i2 = 0; _i2 < sidxs.length; _i2++) {
  2288. var sidx = parseSegmentIndex(sidxs[_i2]);
  2289. if (sidx != null && sidx.references) {
  2290. sidxMinStart = Math.min(sidxMinStart, sidx.earliestPresentationTime / sidx.timescale);
  2291. var subSegmentDuration = sidx.references.reduce(function (dur, ref) {
  2292. return dur + ref.info.duration || 0;
  2293. }, 0);
  2294. sidxMaxEnd = Math.max(sidxMaxEnd, subSegmentDuration + sidx.earliestPresentationTime / sidx.timescale);
  2295. }
  2296. }
  2297. if (sidxMaxEnd && isFiniteNumber(sidxMaxEnd)) {
  2298. Object.keys(tracks).forEach(function (trackId) {
  2299. if (!tracks[trackId].duration) {
  2300. tracks[trackId].duration = sidxMaxEnd * tracks[trackId].timescale - tracks[trackId].start;
  2301. }
  2302. });
  2303. }
  2304. }
  2305. return tracks;
  2306. }
  2307. // TODO: Check if the last moof+mdat pair is part of the valid range
  2308. function segmentValidRange(data) {
  2309. var segmentedRange = {
  2310. valid: null,
  2311. remainder: null
  2312. };
  2313. var moofs = findBox(data, ['moof']);
  2314. if (moofs.length < 2) {
  2315. segmentedRange.remainder = data;
  2316. return segmentedRange;
  2317. }
  2318. var last = moofs[moofs.length - 1];
  2319. // Offset by 8 bytes; findBox offsets the start by as much
  2320. segmentedRange.valid = data.slice(0, last.byteOffset - 8);
  2321. segmentedRange.remainder = data.slice(last.byteOffset - 8);
  2322. return segmentedRange;
  2323. }
  2324. function appendUint8Array(data1, data2) {
  2325. var temp = new Uint8Array(data1.length + data2.length);
  2326. temp.set(data1);
  2327. temp.set(data2, data1.length);
  2328. return temp;
  2329. }
  2330. function parseSamples(timeOffset, track) {
  2331. var seiSamples = [];
  2332. var videoData = track.samples;
  2333. var timescale = track.timescale;
  2334. var trackId = track.id;
  2335. var isHEVCFlavor = false;
  2336. var moofs = findBox(videoData, ['moof']);
  2337. moofs.map(function (moof) {
  2338. var moofOffset = moof.byteOffset - 8;
  2339. var trafs = findBox(moof, ['traf']);
  2340. trafs.map(function (traf) {
  2341. // get the base media decode time from the tfdt
  2342. var baseTime = findBox(traf, ['tfdt']).map(function (tfdt) {
  2343. var version = tfdt[0];
  2344. var result = readUint32(tfdt, 4);
  2345. if (version === 1) {
  2346. result *= Math.pow(2, 32);
  2347. result += readUint32(tfdt, 8);
  2348. }
  2349. return result / timescale;
  2350. })[0];
  2351. if (baseTime !== undefined) {
  2352. timeOffset = baseTime;
  2353. }
  2354. return findBox(traf, ['tfhd']).map(function (tfhd) {
  2355. var id = readUint32(tfhd, 4);
  2356. var tfhdFlags = readUint32(tfhd, 0) & 0xffffff;
  2357. var baseDataOffsetPresent = (tfhdFlags & 0x000001) !== 0;
  2358. var sampleDescriptionIndexPresent = (tfhdFlags & 0x000002) !== 0;
  2359. var defaultSampleDurationPresent = (tfhdFlags & 0x000008) !== 0;
  2360. var defaultSampleDuration = 0;
  2361. var defaultSampleSizePresent = (tfhdFlags & 0x000010) !== 0;
  2362. var defaultSampleSize = 0;
  2363. var defaultSampleFlagsPresent = (tfhdFlags & 0x000020) !== 0;
  2364. var tfhdOffset = 8;
  2365. if (id === trackId) {
  2366. if (baseDataOffsetPresent) {
  2367. tfhdOffset += 8;
  2368. }
  2369. if (sampleDescriptionIndexPresent) {
  2370. tfhdOffset += 4;
  2371. }
  2372. if (defaultSampleDurationPresent) {
  2373. defaultSampleDuration = readUint32(tfhd, tfhdOffset);
  2374. tfhdOffset += 4;
  2375. }
  2376. if (defaultSampleSizePresent) {
  2377. defaultSampleSize = readUint32(tfhd, tfhdOffset);
  2378. tfhdOffset += 4;
  2379. }
  2380. if (defaultSampleFlagsPresent) {
  2381. tfhdOffset += 4;
  2382. }
  2383. if (track.type === 'video') {
  2384. isHEVCFlavor = isHEVC(track.codec);
  2385. }
  2386. findBox(traf, ['trun']).map(function (trun) {
  2387. var version = trun[0];
  2388. var flags = readUint32(trun, 0) & 0xffffff;
  2389. var dataOffsetPresent = (flags & 0x000001) !== 0;
  2390. var dataOffset = 0;
  2391. var firstSampleFlagsPresent = (flags & 0x000004) !== 0;
  2392. var sampleDurationPresent = (flags & 0x000100) !== 0;
  2393. var sampleDuration = 0;
  2394. var sampleSizePresent = (flags & 0x000200) !== 0;
  2395. var sampleSize = 0;
  2396. var sampleFlagsPresent = (flags & 0x000400) !== 0;
  2397. var sampleCompositionOffsetsPresent = (flags & 0x000800) !== 0;
  2398. var compositionOffset = 0;
  2399. var sampleCount = readUint32(trun, 4);
  2400. var trunOffset = 8; // past version, flags, and sample count
  2401. if (dataOffsetPresent) {
  2402. dataOffset = readUint32(trun, trunOffset);
  2403. trunOffset += 4;
  2404. }
  2405. if (firstSampleFlagsPresent) {
  2406. trunOffset += 4;
  2407. }
  2408. var sampleOffset = dataOffset + moofOffset;
  2409. for (var ix = 0; ix < sampleCount; ix++) {
  2410. if (sampleDurationPresent) {
  2411. sampleDuration = readUint32(trun, trunOffset);
  2412. trunOffset += 4;
  2413. } else {
  2414. sampleDuration = defaultSampleDuration;
  2415. }
  2416. if (sampleSizePresent) {
  2417. sampleSize = readUint32(trun, trunOffset);
  2418. trunOffset += 4;
  2419. } else {
  2420. sampleSize = defaultSampleSize;
  2421. }
  2422. if (sampleFlagsPresent) {
  2423. trunOffset += 4;
  2424. }
  2425. if (sampleCompositionOffsetsPresent) {
  2426. if (version === 0) {
  2427. compositionOffset = readUint32(trun, trunOffset);
  2428. } else {
  2429. compositionOffset = readSint32(trun, trunOffset);
  2430. }
  2431. trunOffset += 4;
  2432. }
  2433. if (track.type === ElementaryStreamTypes.VIDEO) {
  2434. var naluTotalSize = 0;
  2435. while (naluTotalSize < sampleSize) {
  2436. var naluSize = readUint32(videoData, sampleOffset);
  2437. sampleOffset += 4;
  2438. if (isSEIMessage(isHEVCFlavor, videoData[sampleOffset])) {
  2439. var data = videoData.subarray(sampleOffset, sampleOffset + naluSize);
  2440. parseSEIMessageFromNALu(data, isHEVCFlavor ? 2 : 1, timeOffset + compositionOffset / timescale, seiSamples);
  2441. }
  2442. sampleOffset += naluSize;
  2443. naluTotalSize += naluSize + 4;
  2444. }
  2445. }
  2446. timeOffset += sampleDuration / timescale;
  2447. }
  2448. });
  2449. }
  2450. });
  2451. });
  2452. });
  2453. return seiSamples;
  2454. }
  2455. function isHEVC(codec) {
  2456. if (!codec) {
  2457. return false;
  2458. }
  2459. var baseCodec = codec.substring(0, 4);
  2460. return baseCodec === 'hvc1' || baseCodec === 'hev1' ||
  2461. // Dolby Vision
  2462. baseCodec === 'dvh1' || baseCodec === 'dvhe';
  2463. }
  2464. function isSEIMessage(isHEVCFlavor, naluHeader) {
  2465. if (isHEVCFlavor) {
  2466. var naluType = naluHeader >> 1 & 0x3f;
  2467. return naluType === 39 || naluType === 40;
  2468. } else {
  2469. var _naluType = naluHeader & 0x1f;
  2470. return _naluType === 6;
  2471. }
  2472. }
  2473. function parseSEIMessageFromNALu(unescapedData, headerSize, pts, samples) {
  2474. var data = discardEPB(unescapedData);
  2475. var seiPtr = 0;
  2476. // skip nal header
  2477. seiPtr += headerSize;
  2478. var payloadType = 0;
  2479. var payloadSize = 0;
  2480. var b = 0;
  2481. while (seiPtr < data.length) {
  2482. payloadType = 0;
  2483. do {
  2484. if (seiPtr >= data.length) {
  2485. break;
  2486. }
  2487. b = data[seiPtr++];
  2488. payloadType += b;
  2489. } while (b === 0xff);
  2490. // Parse payload size.
  2491. payloadSize = 0;
  2492. do {
  2493. if (seiPtr >= data.length) {
  2494. break;
  2495. }
  2496. b = data[seiPtr++];
  2497. payloadSize += b;
  2498. } while (b === 0xff);
  2499. var leftOver = data.length - seiPtr;
  2500. // Create a variable to process the payload
  2501. var payPtr = seiPtr;
  2502. // Increment the seiPtr to the end of the payload
  2503. if (payloadSize < leftOver) {
  2504. seiPtr += payloadSize;
  2505. } else if (payloadSize > leftOver) {
  2506. // Some type of corruption has happened?
  2507. logger.error("Malformed SEI payload. " + payloadSize + " is too small, only " + leftOver + " bytes left to parse.");
  2508. // We might be able to parse some data, but let's be safe and ignore it.
  2509. break;
  2510. }
  2511. if (payloadType === 4) {
  2512. var countryCode = data[payPtr++];
  2513. if (countryCode === 181) {
  2514. var providerCode = readUint16(data, payPtr);
  2515. payPtr += 2;
  2516. if (providerCode === 49) {
  2517. var userStructure = readUint32(data, payPtr);
  2518. payPtr += 4;
  2519. if (userStructure === 0x47413934) {
  2520. var userDataType = data[payPtr++];
  2521. // Raw CEA-608 bytes wrapped in CEA-708 packet
  2522. if (userDataType === 3) {
  2523. var firstByte = data[payPtr++];
  2524. var totalCCs = 0x1f & firstByte;
  2525. var enabled = 0x40 & firstByte;
  2526. var totalBytes = enabled ? 2 + totalCCs * 3 : 0;
  2527. var byteArray = new Uint8Array(totalBytes);
  2528. if (enabled) {
  2529. byteArray[0] = firstByte;
  2530. for (var i = 1; i < totalBytes; i++) {
  2531. byteArray[i] = data[payPtr++];
  2532. }
  2533. }
  2534. samples.push({
  2535. type: userDataType,
  2536. payloadType: payloadType,
  2537. pts: pts,
  2538. bytes: byteArray
  2539. });
  2540. }
  2541. }
  2542. }
  2543. }
  2544. } else if (payloadType === 5) {
  2545. if (payloadSize > 16) {
  2546. var uuidStrArray = [];
  2547. for (var _i3 = 0; _i3 < 16; _i3++) {
  2548. var _b = data[payPtr++].toString(16);
  2549. uuidStrArray.push(_b.length == 1 ? '0' + _b : _b);
  2550. if (_i3 === 3 || _i3 === 5 || _i3 === 7 || _i3 === 9) {
  2551. uuidStrArray.push('-');
  2552. }
  2553. }
  2554. var length = payloadSize - 16;
  2555. var userDataBytes = new Uint8Array(length);
  2556. for (var _i4 = 0; _i4 < length; _i4++) {
  2557. userDataBytes[_i4] = data[payPtr++];
  2558. }
  2559. samples.push({
  2560. payloadType: payloadType,
  2561. pts: pts,
  2562. uuid: uuidStrArray.join(''),
  2563. userData: utf8ArrayToStr(userDataBytes),
  2564. userDataBytes: userDataBytes
  2565. });
  2566. }
  2567. }
  2568. }
  2569. }
  2570. /**
  2571. * remove Emulation Prevention bytes from a RBSP
  2572. */
  2573. function discardEPB(data) {
  2574. var length = data.byteLength;
  2575. var EPBPositions = [];
  2576. var i = 1;
  2577. // Find all `Emulation Prevention Bytes`
  2578. while (i < length - 2) {
  2579. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  2580. EPBPositions.push(i + 2);
  2581. i += 2;
  2582. } else {
  2583. i++;
  2584. }
  2585. }
  2586. // If no Emulation Prevention Bytes were found just return the original
  2587. // array
  2588. if (EPBPositions.length === 0) {
  2589. return data;
  2590. }
  2591. // Create a new array to hold the NAL unit data
  2592. var newLength = length - EPBPositions.length;
  2593. var newData = new Uint8Array(newLength);
  2594. var sourceIndex = 0;
  2595. for (i = 0; i < newLength; sourceIndex++, i++) {
  2596. if (sourceIndex === EPBPositions[0]) {
  2597. // Skip this byte
  2598. sourceIndex++;
  2599. // Remove this position index
  2600. EPBPositions.shift();
  2601. }
  2602. newData[i] = data[sourceIndex];
  2603. }
  2604. return newData;
  2605. }
  2606. function parseEmsg(data) {
  2607. var version = data[0];
  2608. var schemeIdUri = '';
  2609. var value = '';
  2610. var timeScale = 0;
  2611. var presentationTimeDelta = 0;
  2612. var presentationTime = 0;
  2613. var eventDuration = 0;
  2614. var id = 0;
  2615. var offset = 0;
  2616. if (version === 0) {
  2617. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2618. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2619. offset += 1;
  2620. }
  2621. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2622. offset += 1;
  2623. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2624. value += bin2str(data.subarray(offset, offset + 1));
  2625. offset += 1;
  2626. }
  2627. value += bin2str(data.subarray(offset, offset + 1));
  2628. offset += 1;
  2629. timeScale = readUint32(data, 12);
  2630. presentationTimeDelta = readUint32(data, 16);
  2631. eventDuration = readUint32(data, 20);
  2632. id = readUint32(data, 24);
  2633. offset = 28;
  2634. } else if (version === 1) {
  2635. offset += 4;
  2636. timeScale = readUint32(data, offset);
  2637. offset += 4;
  2638. var leftPresentationTime = readUint32(data, offset);
  2639. offset += 4;
  2640. var rightPresentationTime = readUint32(data, offset);
  2641. offset += 4;
  2642. presentationTime = Math.pow(2, 32) * leftPresentationTime + rightPresentationTime;
  2643. if (!isSafeInteger(presentationTime)) {
  2644. presentationTime = Number.MAX_SAFE_INTEGER;
  2645. logger.warn('Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box');
  2646. }
  2647. eventDuration = readUint32(data, offset);
  2648. offset += 4;
  2649. id = readUint32(data, offset);
  2650. offset += 4;
  2651. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2652. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2653. offset += 1;
  2654. }
  2655. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2656. offset += 1;
  2657. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2658. value += bin2str(data.subarray(offset, offset + 1));
  2659. offset += 1;
  2660. }
  2661. value += bin2str(data.subarray(offset, offset + 1));
  2662. offset += 1;
  2663. }
  2664. var payload = data.subarray(offset, data.byteLength);
  2665. return {
  2666. schemeIdUri: schemeIdUri,
  2667. value: value,
  2668. timeScale: timeScale,
  2669. presentationTime: presentationTime,
  2670. presentationTimeDelta: presentationTimeDelta,
  2671. eventDuration: eventDuration,
  2672. id: id,
  2673. payload: payload
  2674. };
  2675. }
  2676. var userAgentHevcSupportIsInaccurate = function userAgentHevcSupportIsInaccurate() {
  2677. return /\(Windows.+Firefox\//i.test(navigator.userAgent);
  2678. };
  2679. // from http://mp4ra.org/codecs.html
  2680. // values indicate codec selection preference (lower is higher priority)
  2681. var sampleEntryCodesISO = {
  2682. audio: {
  2683. a3ds: 1,
  2684. 'ac-3': 0.95,
  2685. 'ac-4': 1,
  2686. alac: 0.9,
  2687. alaw: 1,
  2688. dra1: 1,
  2689. 'dts+': 1,
  2690. 'dts-': 1,
  2691. dtsc: 1,
  2692. dtse: 1,
  2693. dtsh: 1,
  2694. 'ec-3': 0.9,
  2695. enca: 1,
  2696. fLaC: 0.9,
  2697. // MP4-RA listed codec entry for FLAC
  2698. flac: 0.9,
  2699. // legacy browser codec name for FLAC
  2700. FLAC: 0.9,
  2701. // some manifests may list "FLAC" with Apple's tools
  2702. g719: 1,
  2703. g726: 1,
  2704. m4ae: 1,
  2705. mha1: 1,
  2706. mha2: 1,
  2707. mhm1: 1,
  2708. mhm2: 1,
  2709. mlpa: 1,
  2710. mp4a: 1,
  2711. 'raw ': 1,
  2712. Opus: 1,
  2713. opus: 1,
  2714. // browsers expect this to be lowercase despite MP4RA says 'Opus'
  2715. samr: 1,
  2716. sawb: 1,
  2717. sawp: 1,
  2718. sevc: 1,
  2719. sqcp: 1,
  2720. ssmv: 1,
  2721. twos: 1,
  2722. ulaw: 1
  2723. },
  2724. video: {
  2725. avc1: 1,
  2726. avc2: 1,
  2727. avc3: 1,
  2728. avc4: 1,
  2729. avcp: 1,
  2730. av01: 0.8,
  2731. dav1: 0.8,
  2732. drac: 1,
  2733. dva1: 1,
  2734. dvav: 1,
  2735. dvh1: 0.7,
  2736. dvhe: 0.7,
  2737. encv: 1,
  2738. hev1: 0.75,
  2739. hvc1: 0.75,
  2740. mjp2: 1,
  2741. mp4v: 1,
  2742. mvc1: 1,
  2743. mvc2: 1,
  2744. mvc3: 1,
  2745. mvc4: 1,
  2746. resv: 1,
  2747. rv60: 1,
  2748. s263: 1,
  2749. svc1: 1,
  2750. svc2: 1,
  2751. 'vc-1': 1,
  2752. vp08: 1,
  2753. vp09: 0.9
  2754. },
  2755. text: {
  2756. stpp: 1,
  2757. wvtt: 1
  2758. }
  2759. };
  2760. function isCodecType(codec, type) {
  2761. var typeCodes = sampleEntryCodesISO[type];
  2762. return !!typeCodes && !!typeCodes[codec.slice(0, 4)];
  2763. }
  2764. function areCodecsMediaSourceSupported(codecs, type, preferManagedMediaSource) {
  2765. if (preferManagedMediaSource === void 0) {
  2766. preferManagedMediaSource = true;
  2767. }
  2768. return !codecs.split(',').some(function (codec) {
  2769. return !isCodecMediaSourceSupported(codec, type, preferManagedMediaSource);
  2770. });
  2771. }
  2772. function isCodecMediaSourceSupported(codec, type, preferManagedMediaSource) {
  2773. var _MediaSource$isTypeSu;
  2774. if (preferManagedMediaSource === void 0) {
  2775. preferManagedMediaSource = true;
  2776. }
  2777. var MediaSource = getMediaSource(preferManagedMediaSource);
  2778. return (_MediaSource$isTypeSu = MediaSource == null ? void 0 : MediaSource.isTypeSupported(mimeTypeForCodec(codec, type))) != null ? _MediaSource$isTypeSu : false;
  2779. }
  2780. function mimeTypeForCodec(codec, type) {
  2781. return type + "/mp4;codecs=" + codec;
  2782. }
  2783. function videoCodecPreferenceValue(videoCodec) {
  2784. if (videoCodec) {
  2785. var fourCC = videoCodec.substring(0, 4);
  2786. return sampleEntryCodesISO.video[fourCC];
  2787. }
  2788. return 2;
  2789. }
  2790. function codecsSetSelectionPreferenceValue(codecSet) {
  2791. var limitedHevcSupport = userAgentHevcSupportIsInaccurate();
  2792. return codecSet.split(',').reduce(function (num, fourCC) {
  2793. var lowerPriority = limitedHevcSupport && isHEVC(fourCC);
  2794. var preferenceValue = lowerPriority ? 9 : sampleEntryCodesISO.video[fourCC];
  2795. if (preferenceValue) {
  2796. return (preferenceValue * 2 + num) / (num ? 3 : 2);
  2797. }
  2798. return (sampleEntryCodesISO.audio[fourCC] + num) / (num ? 2 : 1);
  2799. }, 0);
  2800. }
  2801. var CODEC_COMPATIBLE_NAMES = {};
  2802. function getCodecCompatibleNameLower(lowerCaseCodec, preferManagedMediaSource) {
  2803. if (preferManagedMediaSource === void 0) {
  2804. preferManagedMediaSource = true;
  2805. }
  2806. if (CODEC_COMPATIBLE_NAMES[lowerCaseCodec]) {
  2807. return CODEC_COMPATIBLE_NAMES[lowerCaseCodec];
  2808. }
  2809. var codecsToCheck = {
  2810. // Idealy fLaC and Opus would be first (spec-compliant) but
  2811. // some browsers will report that fLaC is supported then fail.
  2812. // see: https://bugs.chromium.org/p/chromium/issues/detail?id=1422728
  2813. flac: ['flac', 'fLaC', 'FLAC'],
  2814. opus: ['opus', 'Opus'],
  2815. // Replace audio codec info if browser does not support mp4a.40.34,
  2816. // and demuxer can fallback to 'audio/mpeg' or 'audio/mp4;codecs="mp3"'
  2817. 'mp4a.40.34': ['mp3']
  2818. }[lowerCaseCodec];
  2819. for (var i = 0; i < codecsToCheck.length; i++) {
  2820. var _getMediaSource;
  2821. if (isCodecMediaSourceSupported(codecsToCheck[i], 'audio', preferManagedMediaSource)) {
  2822. CODEC_COMPATIBLE_NAMES[lowerCaseCodec] = codecsToCheck[i];
  2823. return codecsToCheck[i];
  2824. } else if (codecsToCheck[i] === 'mp3' && (_getMediaSource = getMediaSource(preferManagedMediaSource)) != null && _getMediaSource.isTypeSupported('audio/mpeg')) {
  2825. return '';
  2826. }
  2827. }
  2828. return lowerCaseCodec;
  2829. }
  2830. var AUDIO_CODEC_REGEXP = /flac|opus|mp4a\.40\.34/i;
  2831. function getCodecCompatibleName(codec, preferManagedMediaSource) {
  2832. if (preferManagedMediaSource === void 0) {
  2833. preferManagedMediaSource = true;
  2834. }
  2835. return codec.replace(AUDIO_CODEC_REGEXP, function (m) {
  2836. return getCodecCompatibleNameLower(m.toLowerCase(), preferManagedMediaSource);
  2837. });
  2838. }
  2839. function replaceVideoCodec(originalCodecs, newVideoCodec) {
  2840. var codecs = [];
  2841. if (originalCodecs) {
  2842. var allCodecs = originalCodecs.split(',');
  2843. for (var i = 0; i < allCodecs.length; i++) {
  2844. if (!isCodecType(allCodecs[i], 'video')) {
  2845. codecs.push(allCodecs[i]);
  2846. }
  2847. }
  2848. }
  2849. if (newVideoCodec) {
  2850. codecs.push(newVideoCodec);
  2851. }
  2852. return codecs.join(',');
  2853. }
  2854. function pickMostCompleteCodecName(parsedCodec, levelCodec) {
  2855. // Parsing of mp4a codecs strings in mp4-tools from media is incomplete as of d8c6c7a
  2856. // so use level codec is parsed codec is unavailable or incomplete
  2857. if (parsedCodec && (parsedCodec.length > 4 || ['ac-3', 'ec-3', 'alac', 'fLaC', 'Opus'].indexOf(parsedCodec) !== -1)) {
  2858. if (isCodecSupportedAsType(parsedCodec, 'audio') || isCodecSupportedAsType(parsedCodec, 'video')) {
  2859. return parsedCodec;
  2860. }
  2861. }
  2862. if (levelCodec) {
  2863. var levelCodecs = levelCodec.split(',');
  2864. if (levelCodecs.length > 1) {
  2865. if (parsedCodec) {
  2866. for (var i = levelCodecs.length; i--;) {
  2867. if (levelCodecs[i].substring(0, 4) === parsedCodec.substring(0, 4)) {
  2868. return levelCodecs[i];
  2869. }
  2870. }
  2871. }
  2872. return levelCodecs[0];
  2873. }
  2874. }
  2875. return levelCodec || parsedCodec;
  2876. }
  2877. function isCodecSupportedAsType(codec, type) {
  2878. return isCodecType(codec, type) && isCodecMediaSourceSupported(codec, type);
  2879. }
  2880. function convertAVC1ToAVCOTI(videoCodecs) {
  2881. // Convert avc1 codec string from RFC-4281 to RFC-6381 for MediaSource.isTypeSupported
  2882. // Examples: avc1.66.30 to avc1.42001e and avc1.77.30,avc1.66.30 to avc1.4d001e,avc1.42001e.
  2883. var codecs = videoCodecs.split(',');
  2884. for (var i = 0; i < codecs.length; i++) {
  2885. var avcdata = codecs[i].split('.');
  2886. // only convert codec strings starting with avc1 (Examples: avc1.64001f,dvh1.05.07)
  2887. if (avcdata.length > 2 && avcdata[0] === 'avc1') {
  2888. codecs[i] = "avc1." + parseInt(avcdata[1]).toString(16) + ('000' + parseInt(avcdata[2]).toString(16)).slice(-4);
  2889. }
  2890. }
  2891. return codecs.join(',');
  2892. }
  2893. function fillInMissingAV01Params(videoCodec) {
  2894. // Used to fill in incomplete AV1 playlist CODECS strings for mediaCapabilities.decodingInfo queries
  2895. if (videoCodec.startsWith('av01.')) {
  2896. var av1params = videoCodec.split('.');
  2897. var placeholders = ['0', '111', '01', '01', '01', '0'];
  2898. for (var i = av1params.length; i > 4 && i < 10; i++) {
  2899. av1params[i] = placeholders[i - 4];
  2900. }
  2901. return av1params.join('.');
  2902. }
  2903. return videoCodec;
  2904. }
  2905. function getM2TSSupportedAudioTypes(preferManagedMediaSource) {
  2906. var MediaSource = getMediaSource(preferManagedMediaSource) || {
  2907. isTypeSupported: function isTypeSupported() {
  2908. return false;
  2909. }
  2910. };
  2911. return {
  2912. mpeg: MediaSource.isTypeSupported('audio/mpeg'),
  2913. mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"'),
  2914. ac3: false
  2915. };
  2916. }
  2917. function getCodecsForMimeType(mimeType) {
  2918. return mimeType.replace(/^.+codecs=["']?([^"']+).*$/, '$1');
  2919. }
  2920. var HdcpLevels = ['NONE', 'TYPE-0', 'TYPE-1', null];
  2921. function isHdcpLevel(value) {
  2922. return HdcpLevels.indexOf(value) > -1;
  2923. }
  2924. var VideoRangeValues = ['SDR', 'PQ', 'HLG'];
  2925. function isVideoRange(value) {
  2926. return !!value && VideoRangeValues.indexOf(value) > -1;
  2927. }
  2928. var HlsSkip = {
  2929. No: "",
  2930. Yes: "YES",
  2931. v2: "v2"
  2932. };
  2933. function getSkipValue(details) {
  2934. var canSkipUntil = details.canSkipUntil,
  2935. canSkipDateRanges = details.canSkipDateRanges,
  2936. age = details.age;
  2937. // A Client SHOULD NOT request a Playlist Delta Update unless it already
  2938. // has a version of the Playlist that is no older than one-half of the Skip Boundary.
  2939. // @see: https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis#section-6.3.7
  2940. var playlistRecentEnough = age < canSkipUntil / 2;
  2941. if (canSkipUntil && playlistRecentEnough) {
  2942. if (canSkipDateRanges) {
  2943. return HlsSkip.v2;
  2944. }
  2945. return HlsSkip.Yes;
  2946. }
  2947. return HlsSkip.No;
  2948. }
  2949. var HlsUrlParameters = /*#__PURE__*/function () {
  2950. function HlsUrlParameters(msn, part, skip) {
  2951. this.msn = void 0;
  2952. this.part = void 0;
  2953. this.skip = void 0;
  2954. this.msn = msn;
  2955. this.part = part;
  2956. this.skip = skip;
  2957. }
  2958. var _proto = HlsUrlParameters.prototype;
  2959. _proto.addDirectives = function addDirectives(uri) {
  2960. var url = new self.URL(uri);
  2961. if (this.msn !== undefined) {
  2962. url.searchParams.set('_HLS_msn', this.msn.toString());
  2963. }
  2964. if (this.part !== undefined) {
  2965. url.searchParams.set('_HLS_part', this.part.toString());
  2966. }
  2967. if (this.skip) {
  2968. url.searchParams.set('_HLS_skip', this.skip);
  2969. }
  2970. return url.href;
  2971. };
  2972. return HlsUrlParameters;
  2973. }();
  2974. var Level = /*#__PURE__*/function () {
  2975. function Level(data) {
  2976. this._attrs = void 0;
  2977. this.audioCodec = void 0;
  2978. this.bitrate = void 0;
  2979. this.codecSet = void 0;
  2980. this.url = void 0;
  2981. this.frameRate = void 0;
  2982. this.height = void 0;
  2983. this.id = void 0;
  2984. this.name = void 0;
  2985. this.supplemental = void 0;
  2986. this.videoCodec = void 0;
  2987. this.width = void 0;
  2988. this.details = void 0;
  2989. this.fragmentError = 0;
  2990. this.loadError = 0;
  2991. this.loaded = void 0;
  2992. this.realBitrate = 0;
  2993. this.supportedPromise = void 0;
  2994. this.supportedResult = void 0;
  2995. this._avgBitrate = 0;
  2996. this._audioGroups = void 0;
  2997. this._subtitleGroups = void 0;
  2998. // Deprecated (retained for backwards compatibility)
  2999. this._urlId = 0;
  3000. this.url = [data.url];
  3001. this._attrs = [data.attrs];
  3002. this.bitrate = data.bitrate;
  3003. if (data.details) {
  3004. this.details = data.details;
  3005. }
  3006. this.id = data.id || 0;
  3007. this.name = data.name;
  3008. this.width = data.width || 0;
  3009. this.height = data.height || 0;
  3010. this.frameRate = data.attrs.optionalFloat('FRAME-RATE', 0);
  3011. this._avgBitrate = data.attrs.decimalInteger('AVERAGE-BANDWIDTH');
  3012. this.audioCodec = data.audioCodec;
  3013. this.videoCodec = data.videoCodec;
  3014. this.codecSet = [data.videoCodec, data.audioCodec].filter(function (c) {
  3015. return !!c;
  3016. }).map(function (s) {
  3017. return s.substring(0, 4);
  3018. }).join(',');
  3019. if ('supplemental' in data) {
  3020. var _data$supplemental;
  3021. this.supplemental = data.supplemental;
  3022. var supplementalVideo = (_data$supplemental = data.supplemental) == null ? void 0 : _data$supplemental.videoCodec;
  3023. if (supplementalVideo && supplementalVideo !== data.videoCodec) {
  3024. this.codecSet += "," + supplementalVideo.substring(0, 4);
  3025. }
  3026. }
  3027. this.addGroupId('audio', data.attrs.AUDIO);
  3028. this.addGroupId('text', data.attrs.SUBTITLES);
  3029. }
  3030. var _proto2 = Level.prototype;
  3031. _proto2.hasAudioGroup = function hasAudioGroup(groupId) {
  3032. return hasGroup(this._audioGroups, groupId);
  3033. };
  3034. _proto2.hasSubtitleGroup = function hasSubtitleGroup(groupId) {
  3035. return hasGroup(this._subtitleGroups, groupId);
  3036. };
  3037. _proto2.addGroupId = function addGroupId(type, groupId) {
  3038. if (!groupId) {
  3039. return;
  3040. }
  3041. if (type === 'audio') {
  3042. var audioGroups = this._audioGroups;
  3043. if (!audioGroups) {
  3044. audioGroups = this._audioGroups = [];
  3045. }
  3046. if (audioGroups.indexOf(groupId) === -1) {
  3047. audioGroups.push(groupId);
  3048. }
  3049. } else if (type === 'text') {
  3050. var subtitleGroups = this._subtitleGroups;
  3051. if (!subtitleGroups) {
  3052. subtitleGroups = this._subtitleGroups = [];
  3053. }
  3054. if (subtitleGroups.indexOf(groupId) === -1) {
  3055. subtitleGroups.push(groupId);
  3056. }
  3057. }
  3058. }
  3059. // Deprecated methods (retained for backwards compatibility)
  3060. ;
  3061. _proto2.addFallback = function addFallback() {};
  3062. return _createClass(Level, [{
  3063. key: "maxBitrate",
  3064. get: function get() {
  3065. return Math.max(this.realBitrate, this.bitrate);
  3066. }
  3067. }, {
  3068. key: "averageBitrate",
  3069. get: function get() {
  3070. return this._avgBitrate || this.realBitrate || this.bitrate;
  3071. }
  3072. }, {
  3073. key: "attrs",
  3074. get: function get() {
  3075. return this._attrs[0];
  3076. }
  3077. }, {
  3078. key: "codecs",
  3079. get: function get() {
  3080. return this.attrs.CODECS || '';
  3081. }
  3082. }, {
  3083. key: "pathwayId",
  3084. get: function get() {
  3085. return this.attrs['PATHWAY-ID'] || '.';
  3086. }
  3087. }, {
  3088. key: "videoRange",
  3089. get: function get() {
  3090. return this.attrs['VIDEO-RANGE'] || 'SDR';
  3091. }
  3092. }, {
  3093. key: "score",
  3094. get: function get() {
  3095. return this.attrs.optionalFloat('SCORE', 0);
  3096. }
  3097. }, {
  3098. key: "uri",
  3099. get: function get() {
  3100. return this.url[0] || '';
  3101. }
  3102. }, {
  3103. key: "audioGroups",
  3104. get: function get() {
  3105. return this._audioGroups;
  3106. }
  3107. }, {
  3108. key: "subtitleGroups",
  3109. get: function get() {
  3110. return this._subtitleGroups;
  3111. }
  3112. }, {
  3113. key: "urlId",
  3114. get: function get() {
  3115. return 0;
  3116. },
  3117. set: function set(value) {}
  3118. }, {
  3119. key: "audioGroupIds",
  3120. get: function get() {
  3121. return this.audioGroups ? [this.audioGroupId] : undefined;
  3122. }
  3123. }, {
  3124. key: "textGroupIds",
  3125. get: function get() {
  3126. return this.subtitleGroups ? [this.textGroupId] : undefined;
  3127. }
  3128. }, {
  3129. key: "audioGroupId",
  3130. get: function get() {
  3131. var _this$audioGroups;
  3132. return (_this$audioGroups = this.audioGroups) == null ? void 0 : _this$audioGroups[0];
  3133. }
  3134. }, {
  3135. key: "textGroupId",
  3136. get: function get() {
  3137. var _this$subtitleGroups;
  3138. return (_this$subtitleGroups = this.subtitleGroups) == null ? void 0 : _this$subtitleGroups[0];
  3139. }
  3140. }]);
  3141. }();
  3142. function hasGroup(groups, groupId) {
  3143. if (!groupId || !groups) {
  3144. return false;
  3145. }
  3146. return groups.indexOf(groupId) !== -1;
  3147. }
  3148. /**
  3149. * @returns Whether we can detect and validate HDR capability within the window context
  3150. */
  3151. function isHdrSupported() {
  3152. if (typeof matchMedia === 'function') {
  3153. var mediaQueryList = matchMedia('(dynamic-range: high)');
  3154. var badQuery = matchMedia('bad query');
  3155. if (mediaQueryList.media !== badQuery.media) {
  3156. return mediaQueryList.matches === true;
  3157. }
  3158. }
  3159. return false;
  3160. }
  3161. /**
  3162. * Sanitizes inputs to return the active video selection options for HDR/SDR.
  3163. * When both inputs are null:
  3164. *
  3165. * `{ preferHDR: false, allowedVideoRanges: [] }`
  3166. *
  3167. * When `currentVideoRange` non-null, maintain the active range:
  3168. *
  3169. * `{ preferHDR: currentVideoRange !== 'SDR', allowedVideoRanges: [currentVideoRange] }`
  3170. *
  3171. * When VideoSelectionOption non-null:
  3172. *
  3173. * - Allow all video ranges if `allowedVideoRanges` unspecified.
  3174. * - If `preferHDR` is non-null use the value to filter `allowedVideoRanges`.
  3175. * - Else check window for HDR support and set `preferHDR` to the result.
  3176. *
  3177. * @param currentVideoRange
  3178. * @param videoPreference
  3179. */
  3180. function getVideoSelectionOptions(currentVideoRange, videoPreference) {
  3181. var preferHDR = false;
  3182. var allowedVideoRanges = [];
  3183. if (currentVideoRange) {
  3184. preferHDR = currentVideoRange !== 'SDR';
  3185. allowedVideoRanges = [currentVideoRange];
  3186. }
  3187. if (videoPreference) {
  3188. allowedVideoRanges = videoPreference.allowedVideoRanges || VideoRangeValues.slice(0);
  3189. var allowAutoPreferHDR = allowedVideoRanges.join('') !== 'SDR' && !videoPreference.videoCodec;
  3190. preferHDR = videoPreference.preferHDR !== undefined ? videoPreference.preferHDR : allowAutoPreferHDR && isHdrSupported();
  3191. if (!preferHDR) {
  3192. allowedVideoRanges = ['SDR'];
  3193. }
  3194. }
  3195. return {
  3196. preferHDR: preferHDR,
  3197. allowedVideoRanges: allowedVideoRanges
  3198. };
  3199. }
  3200. var omitCircularRefsReplacer = function omitCircularRefsReplacer(replacer) {
  3201. var known = new WeakSet();
  3202. return function (_, value) {
  3203. if (replacer) {
  3204. value = replacer(_, value);
  3205. }
  3206. if (typeof value === 'object' && value !== null) {
  3207. if (known.has(value)) {
  3208. return;
  3209. }
  3210. known.add(value);
  3211. }
  3212. return value;
  3213. };
  3214. };
  3215. var stringify = function stringify(object, replacer) {
  3216. return JSON.stringify(object, omitCircularRefsReplacer(replacer));
  3217. };
  3218. function getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference) {
  3219. var codecSets = Object.keys(codecTiers);
  3220. var channelsPreference = audioPreference == null ? void 0 : audioPreference.channels;
  3221. var audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec;
  3222. var videoCodecPreference = videoPreference == null ? void 0 : videoPreference.videoCodec;
  3223. var preferStereo = channelsPreference && parseInt(channelsPreference) === 2;
  3224. // Use first level set to determine stereo, and minimum resolution and framerate
  3225. var hasStereo = false;
  3226. var hasCurrentVideoRange = false;
  3227. var minHeight = Infinity;
  3228. var minFramerate = Infinity;
  3229. var minBitrate = Infinity;
  3230. var minIndex = Infinity;
  3231. var selectedScore = 0;
  3232. var videoRanges = [];
  3233. var _getVideoSelectionOpt = getVideoSelectionOptions(currentVideoRange, videoPreference),
  3234. preferHDR = _getVideoSelectionOpt.preferHDR,
  3235. allowedVideoRanges = _getVideoSelectionOpt.allowedVideoRanges;
  3236. var _loop = function _loop() {
  3237. var tier = codecTiers[codecSets[i]];
  3238. hasStereo || (hasStereo = tier.channels[2] > 0);
  3239. minHeight = Math.min(minHeight, tier.minHeight);
  3240. minFramerate = Math.min(minFramerate, tier.minFramerate);
  3241. minBitrate = Math.min(minBitrate, tier.minBitrate);
  3242. var matchingVideoRanges = allowedVideoRanges.filter(function (range) {
  3243. return tier.videoRanges[range] > 0;
  3244. });
  3245. if (matchingVideoRanges.length > 0) {
  3246. hasCurrentVideoRange = true;
  3247. }
  3248. };
  3249. for (var i = codecSets.length; i--;) {
  3250. _loop();
  3251. }
  3252. minHeight = isFiniteNumber(minHeight) ? minHeight : 0;
  3253. minFramerate = isFiniteNumber(minFramerate) ? minFramerate : 0;
  3254. var maxHeight = Math.max(1080, minHeight);
  3255. var maxFramerate = Math.max(30, minFramerate);
  3256. minBitrate = isFiniteNumber(minBitrate) ? minBitrate : currentBw;
  3257. currentBw = Math.max(minBitrate, currentBw);
  3258. // If there are no variants with matching preference, set currentVideoRange to undefined
  3259. if (!hasCurrentVideoRange) {
  3260. currentVideoRange = undefined;
  3261. }
  3262. var hasMultipleSets = codecSets.length > 1;
  3263. var codecSet = codecSets.reduce(function (selected, candidate) {
  3264. // Remove candiates which do not meet bitrate, default audio, stereo or channels preference, 1080p or lower, 30fps or lower, or SDR/HDR selection if present
  3265. var candidateTier = codecTiers[candidate];
  3266. if (candidate === selected) {
  3267. return selected;
  3268. }
  3269. videoRanges = hasCurrentVideoRange ? allowedVideoRanges.filter(function (range) {
  3270. return candidateTier.videoRanges[range] > 0;
  3271. }) : [];
  3272. if (hasMultipleSets) {
  3273. if (candidateTier.minBitrate > currentBw) {
  3274. logStartCodecCandidateIgnored(candidate, "min bitrate of " + candidateTier.minBitrate + " > current estimate of " + currentBw);
  3275. return selected;
  3276. }
  3277. if (!candidateTier.hasDefaultAudio) {
  3278. logStartCodecCandidateIgnored(candidate, "no renditions with default or auto-select sound found");
  3279. return selected;
  3280. }
  3281. if (audioCodecPreference && candidate.indexOf(audioCodecPreference.substring(0, 4)) % 5 !== 0) {
  3282. logStartCodecCandidateIgnored(candidate, "audio codec preference \"" + audioCodecPreference + "\" not found");
  3283. return selected;
  3284. }
  3285. if (channelsPreference && !preferStereo) {
  3286. if (!candidateTier.channels[channelsPreference]) {
  3287. logStartCodecCandidateIgnored(candidate, "no renditions with " + channelsPreference + " channel sound found (channels options: " + Object.keys(candidateTier.channels) + ")");
  3288. return selected;
  3289. }
  3290. } else if ((!audioCodecPreference || preferStereo) && hasStereo && candidateTier.channels['2'] === 0) {
  3291. logStartCodecCandidateIgnored(candidate, "no renditions with stereo sound found");
  3292. return selected;
  3293. }
  3294. if (candidateTier.minHeight > maxHeight) {
  3295. logStartCodecCandidateIgnored(candidate, "min resolution of " + candidateTier.minHeight + " > maximum of " + maxHeight);
  3296. return selected;
  3297. }
  3298. if (candidateTier.minFramerate > maxFramerate) {
  3299. logStartCodecCandidateIgnored(candidate, "min framerate of " + candidateTier.minFramerate + " > maximum of " + maxFramerate);
  3300. return selected;
  3301. }
  3302. if (!videoRanges.some(function (range) {
  3303. return candidateTier.videoRanges[range] > 0;
  3304. })) {
  3305. logStartCodecCandidateIgnored(candidate, "no variants with VIDEO-RANGE of " + stringify(videoRanges) + " found");
  3306. return selected;
  3307. }
  3308. if (videoCodecPreference && candidate.indexOf(videoCodecPreference.substring(0, 4)) % 5 !== 0) {
  3309. logStartCodecCandidateIgnored(candidate, "video codec preference \"" + videoCodecPreference + "\" not found");
  3310. return selected;
  3311. }
  3312. if (candidateTier.maxScore < selectedScore) {
  3313. logStartCodecCandidateIgnored(candidate, "max score of " + candidateTier.maxScore + " < selected max of " + selectedScore);
  3314. return selected;
  3315. }
  3316. }
  3317. // Remove candiates with less preferred codecs or more errors
  3318. if (selected && (codecsSetSelectionPreferenceValue(candidate) >= codecsSetSelectionPreferenceValue(selected) || candidateTier.fragmentError > codecTiers[selected].fragmentError)) {
  3319. return selected;
  3320. }
  3321. minIndex = candidateTier.minIndex;
  3322. selectedScore = candidateTier.maxScore;
  3323. return candidate;
  3324. }, undefined);
  3325. return {
  3326. codecSet: codecSet,
  3327. videoRanges: videoRanges,
  3328. preferHDR: preferHDR,
  3329. minFramerate: minFramerate,
  3330. minBitrate: minBitrate,
  3331. minIndex: minIndex
  3332. };
  3333. }
  3334. function logStartCodecCandidateIgnored(codeSet, reason) {
  3335. logger.log("[abr] start candidates with \"" + codeSet + "\" ignored because " + reason);
  3336. }
  3337. function getAudioTracksByGroup(allAudioTracks) {
  3338. return allAudioTracks.reduce(function (audioTracksByGroup, track) {
  3339. var trackGroup = audioTracksByGroup.groups[track.groupId];
  3340. if (!trackGroup) {
  3341. trackGroup = audioTracksByGroup.groups[track.groupId] = {
  3342. tracks: [],
  3343. channels: {
  3344. 2: 0
  3345. },
  3346. hasDefault: false,
  3347. hasAutoSelect: false
  3348. };
  3349. }
  3350. trackGroup.tracks.push(track);
  3351. var channelsKey = track.channels || '2';
  3352. trackGroup.channels[channelsKey] = (trackGroup.channels[channelsKey] || 0) + 1;
  3353. trackGroup.hasDefault = trackGroup.hasDefault || track.default;
  3354. trackGroup.hasAutoSelect = trackGroup.hasAutoSelect || track.autoselect;
  3355. if (trackGroup.hasDefault) {
  3356. audioTracksByGroup.hasDefaultAudio = true;
  3357. }
  3358. if (trackGroup.hasAutoSelect) {
  3359. audioTracksByGroup.hasAutoSelectAudio = true;
  3360. }
  3361. return audioTracksByGroup;
  3362. }, {
  3363. hasDefaultAudio: false,
  3364. hasAutoSelectAudio: false,
  3365. groups: {}
  3366. });
  3367. }
  3368. function getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel) {
  3369. return levels.slice(minAutoLevel, maxAutoLevel + 1).reduce(function (tiers, level, index) {
  3370. if (!level.codecSet) {
  3371. return tiers;
  3372. }
  3373. var audioGroups = level.audioGroups;
  3374. var tier = tiers[level.codecSet];
  3375. if (!tier) {
  3376. tiers[level.codecSet] = tier = {
  3377. minBitrate: Infinity,
  3378. minHeight: Infinity,
  3379. minFramerate: Infinity,
  3380. minIndex: index,
  3381. maxScore: 0,
  3382. videoRanges: {
  3383. SDR: 0
  3384. },
  3385. channels: {
  3386. '2': 0
  3387. },
  3388. hasDefaultAudio: !audioGroups,
  3389. fragmentError: 0
  3390. };
  3391. }
  3392. tier.minBitrate = Math.min(tier.minBitrate, level.bitrate);
  3393. var lesserWidthOrHeight = Math.min(level.height, level.width);
  3394. tier.minHeight = Math.min(tier.minHeight, lesserWidthOrHeight);
  3395. tier.minFramerate = Math.min(tier.minFramerate, level.frameRate);
  3396. tier.minIndex = Math.min(tier.minIndex, index);
  3397. tier.maxScore = Math.max(tier.maxScore, level.score);
  3398. tier.fragmentError += level.fragmentError;
  3399. tier.videoRanges[level.videoRange] = (tier.videoRanges[level.videoRange] || 0) + 1;
  3400. return tiers;
  3401. }, {});
  3402. }
  3403. function useAlternateAudio(audioTrackUrl, hls) {
  3404. var _hls$loadLevelObj;
  3405. return !!audioTrackUrl && audioTrackUrl !== ((_hls$loadLevelObj = hls.loadLevelObj) == null ? void 0 : _hls$loadLevelObj.uri);
  3406. }
  3407. var AbrController = /*#__PURE__*/function (_Logger) {
  3408. function AbrController(_hls) {
  3409. var _this;
  3410. _this = _Logger.call(this, 'abr', _hls.logger) || this;
  3411. _this.hls = void 0;
  3412. _this.lastLevelLoadSec = 0;
  3413. _this.lastLoadedFragLevel = -1;
  3414. _this.firstSelection = -1;
  3415. _this._nextAutoLevel = -1;
  3416. _this.nextAutoLevelKey = '';
  3417. _this.audioTracksByGroup = null;
  3418. _this.codecTiers = null;
  3419. _this.timer = -1;
  3420. _this.fragCurrent = null;
  3421. _this.partCurrent = null;
  3422. _this.bitrateTestDelay = 0;
  3423. _this.rebufferNotice = -1;
  3424. _this.supportedCache = {};
  3425. _this.bwEstimator = void 0;
  3426. /*
  3427. This method monitors the download rate of the current fragment, and will downswitch if that fragment will not load
  3428. quickly enough to prevent underbuffering
  3429. */
  3430. _this._abandonRulesCheck = function (levelLoaded) {
  3431. var _ref;
  3432. var _this2 = _this,
  3433. frag = _this2.fragCurrent,
  3434. part = _this2.partCurrent,
  3435. hls = _this2.hls;
  3436. var autoLevelEnabled = hls.autoLevelEnabled,
  3437. media = hls.media;
  3438. if (!frag || !media) {
  3439. return;
  3440. }
  3441. var now = performance.now();
  3442. var stats = part ? part.stats : frag.stats;
  3443. var duration = part ? part.duration : frag.duration;
  3444. var timeLoading = now - stats.loading.start;
  3445. var minAutoLevel = hls.minAutoLevel;
  3446. var loadingFragForLevel = frag.level;
  3447. var currentAutoLevel = _this._nextAutoLevel;
  3448. // If frag loading is aborted, complete, or from lowest level, stop timer and return
  3449. if (stats.aborted || stats.loaded && stats.loaded === stats.total || loadingFragForLevel <= minAutoLevel) {
  3450. _this.clearTimer();
  3451. // reset forced auto level value so that next level will be selected
  3452. _this._nextAutoLevel = -1;
  3453. return;
  3454. }
  3455. // This check only runs if we're in ABR mode
  3456. if (!autoLevelEnabled) {
  3457. return;
  3458. }
  3459. // Must be loading/loaded a new level or be in a playing state
  3460. var fragBlockingSwitch = currentAutoLevel > -1 && currentAutoLevel !== loadingFragForLevel;
  3461. var levelChange = !!levelLoaded || fragBlockingSwitch;
  3462. if (!levelChange && (media.paused || !media.playbackRate || !media.readyState)) {
  3463. return;
  3464. }
  3465. var bufferInfo = hls.mainForwardBufferInfo;
  3466. if (!levelChange && bufferInfo === null) {
  3467. return;
  3468. }
  3469. var ttfbEstimate = _this.bwEstimator.getEstimateTTFB();
  3470. var playbackRate = Math.abs(media.playbackRate);
  3471. // To maintain stable adaptive playback, only begin monitoring frag loading after half or more of its playback duration has passed
  3472. if (timeLoading <= Math.max(ttfbEstimate, 1000 * (duration / (playbackRate * 2)))) {
  3473. return;
  3474. }
  3475. // bufferStarvationDelay is an estimate of the amount time (in seconds) it will take to exhaust the buffer
  3476. var bufferStarvationDelay = bufferInfo ? bufferInfo.len / playbackRate : 0;
  3477. var ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  3478. var loadedFirstByte = stats.loaded && ttfb > -1;
  3479. var bwEstimate = _this.getBwEstimate();
  3480. var levels = hls.levels;
  3481. var level = levels[loadingFragForLevel];
  3482. var expectedLen = Math.max(stats.loaded, Math.round(duration * (frag.bitrate || level.averageBitrate) / 8));
  3483. var timeStreaming = loadedFirstByte ? timeLoading - ttfb : timeLoading;
  3484. if (timeStreaming < 1 && loadedFirstByte) {
  3485. timeStreaming = Math.min(timeLoading, stats.loaded * 8 / bwEstimate);
  3486. }
  3487. var loadRate = loadedFirstByte ? stats.loaded * 1000 / timeStreaming : 0;
  3488. // fragLoadDelay is an estimate of the time (in seconds) it will take to buffer the remainder of the fragment
  3489. var ttfbSeconds = ttfbEstimate / 1000;
  3490. var fragLoadedDelay = loadRate ? (expectedLen - stats.loaded) / loadRate : expectedLen * 8 / bwEstimate + ttfbSeconds;
  3491. // Only downswitch if the time to finish loading the current fragment is greater than the amount of buffer left
  3492. if (fragLoadedDelay <= bufferStarvationDelay) {
  3493. return;
  3494. }
  3495. var bwe = loadRate ? loadRate * 8 : bwEstimate;
  3496. var live = ((_ref = (levelLoaded == null ? void 0 : levelLoaded.details) || _this.hls.latestLevelDetails) == null ? void 0 : _ref.live) === true;
  3497. var abrBandWidthUpFactor = _this.hls.config.abrBandWidthUpFactor;
  3498. var fragLevelNextLoadedDelay = Number.POSITIVE_INFINITY;
  3499. var nextLoadLevel;
  3500. // Iterate through lower level and try to find the largest one that avoids rebuffering
  3501. for (nextLoadLevel = loadingFragForLevel - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
  3502. // compute time to load next fragment at lower level
  3503. // 8 = bits per byte (bps/Bps)
  3504. var levelNextBitrate = levels[nextLoadLevel].maxBitrate;
  3505. var requiresLevelLoad = !levels[nextLoadLevel].details || live;
  3506. fragLevelNextLoadedDelay = _this.getTimeToLoadFrag(ttfbSeconds, bwe, duration * levelNextBitrate, requiresLevelLoad);
  3507. if (fragLevelNextLoadedDelay < Math.min(bufferStarvationDelay, duration + ttfbSeconds)) {
  3508. break;
  3509. }
  3510. }
  3511. // Only emergency switch down if it takes less time to load a new fragment at lowest level instead of continuing
  3512. // to load the current one
  3513. if (fragLevelNextLoadedDelay >= fragLoadedDelay) {
  3514. return;
  3515. }
  3516. // if estimated load time of new segment is completely unreasonable, ignore and do not emergency switch down
  3517. if (fragLevelNextLoadedDelay > duration * 10) {
  3518. return;
  3519. }
  3520. if (loadedFirstByte) {
  3521. // If there has been loading progress, sample bandwidth using loading time offset by minimum TTFB time
  3522. _this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  3523. } else {
  3524. // If there has been no loading progress, sample TTFB
  3525. _this.bwEstimator.sampleTTFB(timeLoading);
  3526. }
  3527. var nextLoadLevelBitrate = levels[nextLoadLevel].maxBitrate;
  3528. if (_this.getBwEstimate() * abrBandWidthUpFactor > nextLoadLevelBitrate) {
  3529. _this.resetEstimator(nextLoadLevelBitrate);
  3530. }
  3531. var bestSwitchLevel = _this.findBestLevel(nextLoadLevelBitrate, minAutoLevel, nextLoadLevel, 0, bufferStarvationDelay, 1, 1);
  3532. if (bestSwitchLevel > -1) {
  3533. nextLoadLevel = bestSwitchLevel;
  3534. }
  3535. _this.warn("Fragment " + frag.sn + (part ? ' part ' + part.index : '') + " of level " + loadingFragForLevel + " is loading too slowly;\n Fragment duration: " + frag.duration.toFixed(3) + "\n Time to underbuffer: " + bufferStarvationDelay.toFixed(3) + " s\n Estimated load time for current fragment: " + fragLoadedDelay.toFixed(3) + " s\n Estimated load time for down switch fragment: " + fragLevelNextLoadedDelay.toFixed(3) + " s\n TTFB estimate: " + (ttfb | 0) + " ms\n Current BW estimate: " + (isFiniteNumber(bwEstimate) ? bwEstimate | 0 : 'Unknown') + " bps\n New BW estimate: " + (_this.getBwEstimate() | 0) + " bps\n Switching to level " + nextLoadLevel + " @ " + (nextLoadLevelBitrate | 0) + " bps");
  3536. hls.nextLoadLevel = hls.nextAutoLevel = nextLoadLevel;
  3537. _this.clearTimer();
  3538. var abortAndSwitch = function abortAndSwitch() {
  3539. // Are nextLoadLevel details available or is stream-controller still in "WAITING_LEVEL" state?
  3540. _this.clearTimer();
  3541. if (_this.fragCurrent === frag && _this.hls.loadLevel === nextLoadLevel && nextLoadLevel > 0) {
  3542. var _bufferStarvationDelay = _this.getStarvationDelay();
  3543. _this.warn("Aborting inflight request " + (nextLoadLevel > 0 ? 'and switching down' : '') + "\n Fragment duration: " + frag.duration.toFixed(3) + " s\n Time to underbuffer: " + _bufferStarvationDelay.toFixed(3) + " s");
  3544. frag.abortRequests();
  3545. _this.fragCurrent = _this.partCurrent = null;
  3546. if (nextLoadLevel > minAutoLevel) {
  3547. var lowestSwitchLevel = _this.findBestLevel(_this.hls.levels[minAutoLevel].bitrate, minAutoLevel, nextLoadLevel, 0, _bufferStarvationDelay, 1, 1);
  3548. if (lowestSwitchLevel === -1) {
  3549. lowestSwitchLevel = minAutoLevel;
  3550. }
  3551. _this.hls.nextLoadLevel = _this.hls.nextAutoLevel = lowestSwitchLevel;
  3552. _this.resetEstimator(_this.hls.levels[lowestSwitchLevel].bitrate);
  3553. }
  3554. }
  3555. };
  3556. if (fragBlockingSwitch || fragLoadedDelay > fragLevelNextLoadedDelay * 2) {
  3557. abortAndSwitch();
  3558. } else {
  3559. _this.timer = self.setInterval(abortAndSwitch, fragLevelNextLoadedDelay * 1000);
  3560. }
  3561. hls.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED, {
  3562. frag: frag,
  3563. part: part,
  3564. stats: stats
  3565. });
  3566. };
  3567. _this.hls = _hls;
  3568. _this.bwEstimator = _this.initEstimator();
  3569. _this.registerListeners();
  3570. return _this;
  3571. }
  3572. _inheritsLoose(AbrController, _Logger);
  3573. var _proto = AbrController.prototype;
  3574. _proto.resetEstimator = function resetEstimator(abrEwmaDefaultEstimate) {
  3575. if (abrEwmaDefaultEstimate) {
  3576. this.log("setting initial bwe to " + abrEwmaDefaultEstimate);
  3577. this.hls.config.abrEwmaDefaultEstimate = abrEwmaDefaultEstimate;
  3578. }
  3579. this.firstSelection = -1;
  3580. this.bwEstimator = this.initEstimator();
  3581. };
  3582. _proto.initEstimator = function initEstimator() {
  3583. var config = this.hls.config;
  3584. return new EwmaBandWidthEstimator(config.abrEwmaSlowVoD, config.abrEwmaFastVoD, config.abrEwmaDefaultEstimate);
  3585. };
  3586. _proto.registerListeners = function registerListeners() {
  3587. var hls = this.hls;
  3588. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3589. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  3590. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  3591. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  3592. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  3593. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  3594. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  3595. hls.on(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  3596. hls.on(Events.ERROR, this.onError, this);
  3597. };
  3598. _proto.unregisterListeners = function unregisterListeners() {
  3599. var hls = this.hls;
  3600. if (!hls) {
  3601. return;
  3602. }
  3603. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3604. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  3605. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  3606. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  3607. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  3608. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  3609. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  3610. hls.off(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  3611. hls.off(Events.ERROR, this.onError, this);
  3612. };
  3613. _proto.destroy = function destroy() {
  3614. this.unregisterListeners();
  3615. this.clearTimer();
  3616. // @ts-ignore
  3617. this.hls = this._abandonRulesCheck = this.supportedCache = null;
  3618. this.fragCurrent = this.partCurrent = null;
  3619. };
  3620. _proto.onManifestLoading = function onManifestLoading(event, data) {
  3621. this.lastLoadedFragLevel = -1;
  3622. this.firstSelection = -1;
  3623. this.lastLevelLoadSec = 0;
  3624. this.supportedCache = {};
  3625. this.fragCurrent = this.partCurrent = null;
  3626. this.onLevelsUpdated();
  3627. this.clearTimer();
  3628. };
  3629. _proto.onLevelsUpdated = function onLevelsUpdated() {
  3630. if (this.lastLoadedFragLevel > -1 && this.fragCurrent) {
  3631. this.lastLoadedFragLevel = this.fragCurrent.level;
  3632. }
  3633. this._nextAutoLevel = -1;
  3634. this.onMaxAutoLevelUpdated();
  3635. this.codecTiers = null;
  3636. this.audioTracksByGroup = null;
  3637. };
  3638. _proto.onMaxAutoLevelUpdated = function onMaxAutoLevelUpdated() {
  3639. this.firstSelection = -1;
  3640. this.nextAutoLevelKey = '';
  3641. };
  3642. _proto.onFragLoading = function onFragLoading(event, data) {
  3643. var frag = data.frag;
  3644. if (this.ignoreFragment(frag)) {
  3645. return;
  3646. }
  3647. if (!frag.bitrateTest) {
  3648. var _data$part;
  3649. this.fragCurrent = frag;
  3650. this.partCurrent = (_data$part = data.part) != null ? _data$part : null;
  3651. }
  3652. this.clearTimer();
  3653. this.timer = self.setInterval(this._abandonRulesCheck, 100);
  3654. };
  3655. _proto.onLevelSwitching = function onLevelSwitching(event, data) {
  3656. this.clearTimer();
  3657. };
  3658. _proto.onError = function onError(event, data) {
  3659. if (data.fatal) {
  3660. return;
  3661. }
  3662. switch (data.details) {
  3663. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  3664. case ErrorDetails.BUFFER_APPEND_ERROR:
  3665. // Reset last loaded level so that a new selection can be made after calling recoverMediaError
  3666. this.lastLoadedFragLevel = -1;
  3667. this.firstSelection = -1;
  3668. break;
  3669. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  3670. {
  3671. var frag = data.frag;
  3672. var fragCurrent = this.fragCurrent,
  3673. part = this.partCurrent;
  3674. if (frag && fragCurrent && frag.sn === fragCurrent.sn && frag.level === fragCurrent.level) {
  3675. var now = performance.now();
  3676. var stats = part ? part.stats : frag.stats;
  3677. var timeLoading = now - stats.loading.start;
  3678. var ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  3679. var loadedFirstByte = stats.loaded && ttfb > -1;
  3680. if (loadedFirstByte) {
  3681. var ttfbEstimate = this.bwEstimator.getEstimateTTFB();
  3682. this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  3683. } else {
  3684. this.bwEstimator.sampleTTFB(timeLoading);
  3685. }
  3686. }
  3687. break;
  3688. }
  3689. }
  3690. };
  3691. _proto.getTimeToLoadFrag = function getTimeToLoadFrag(timeToFirstByteSec, bandwidth, fragSizeBits, isSwitch) {
  3692. var fragLoadSec = timeToFirstByteSec + fragSizeBits / bandwidth;
  3693. var playlistLoadSec = isSwitch ? timeToFirstByteSec + this.lastLevelLoadSec : 0;
  3694. return fragLoadSec + playlistLoadSec;
  3695. };
  3696. _proto.onLevelLoaded = function onLevelLoaded(event, data) {
  3697. var config = this.hls.config;
  3698. var loading = data.stats.loading;
  3699. var timeLoadingMs = loading.end - loading.first;
  3700. if (isFiniteNumber(timeLoadingMs)) {
  3701. this.lastLevelLoadSec = timeLoadingMs / 1000;
  3702. }
  3703. if (data.details.live) {
  3704. this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive);
  3705. } else {
  3706. this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD);
  3707. }
  3708. if (this.timer > -1) {
  3709. this._abandonRulesCheck(data.levelInfo);
  3710. }
  3711. };
  3712. _proto.onFragLoaded = function onFragLoaded(event, _ref2) {
  3713. var frag = _ref2.frag,
  3714. part = _ref2.part;
  3715. var stats = part ? part.stats : frag.stats;
  3716. if (frag.type === PlaylistLevelType.MAIN) {
  3717. this.bwEstimator.sampleTTFB(stats.loading.first - stats.loading.start);
  3718. }
  3719. if (this.ignoreFragment(frag)) {
  3720. return;
  3721. }
  3722. // stop monitoring bw once frag loaded
  3723. this.clearTimer();
  3724. // reset forced auto level value so that next level will be selected
  3725. if (frag.level === this._nextAutoLevel) {
  3726. this._nextAutoLevel = -1;
  3727. }
  3728. this.firstSelection = -1;
  3729. // compute level average bitrate
  3730. if (this.hls.config.abrMaxWithRealBitrate) {
  3731. var duration = part ? part.duration : frag.duration;
  3732. var level = this.hls.levels[frag.level];
  3733. var loadedBytes = (level.loaded ? level.loaded.bytes : 0) + stats.loaded;
  3734. var loadedDuration = (level.loaded ? level.loaded.duration : 0) + duration;
  3735. level.loaded = {
  3736. bytes: loadedBytes,
  3737. duration: loadedDuration
  3738. };
  3739. level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
  3740. }
  3741. if (frag.bitrateTest) {
  3742. var fragBufferedData = {
  3743. stats: stats,
  3744. frag: frag,
  3745. part: part,
  3746. id: frag.type
  3747. };
  3748. this.onFragBuffered(Events.FRAG_BUFFERED, fragBufferedData);
  3749. frag.bitrateTest = false;
  3750. } else {
  3751. // store level id after successful fragment load for playback
  3752. this.lastLoadedFragLevel = frag.level;
  3753. }
  3754. };
  3755. _proto.onFragBuffered = function onFragBuffered(event, data) {
  3756. var frag = data.frag,
  3757. part = data.part;
  3758. var stats = part != null && part.stats.loaded ? part.stats : frag.stats;
  3759. if (stats.aborted) {
  3760. return;
  3761. }
  3762. if (this.ignoreFragment(frag)) {
  3763. return;
  3764. }
  3765. // Use the difference between parsing and request instead of buffering and request to compute fragLoadingProcessing;
  3766. // rationale is that buffer appending only happens once media is attached. This can happen when config.startFragPrefetch
  3767. // is used. If we used buffering in that case, our BW estimate sample will be very large.
  3768. var processingMs = stats.parsing.end - stats.loading.start - Math.min(stats.loading.first - stats.loading.start, this.bwEstimator.getEstimateTTFB());
  3769. this.bwEstimator.sample(processingMs, stats.loaded);
  3770. stats.bwEstimate = this.getBwEstimate();
  3771. if (frag.bitrateTest) {
  3772. this.bitrateTestDelay = processingMs / 1000;
  3773. } else {
  3774. this.bitrateTestDelay = 0;
  3775. }
  3776. };
  3777. _proto.ignoreFragment = function ignoreFragment(frag) {
  3778. // Only count non-alt-audio frags which were actually buffered in our BW calculations
  3779. return frag.type !== PlaylistLevelType.MAIN || frag.sn === 'initSegment';
  3780. };
  3781. _proto.clearTimer = function clearTimer() {
  3782. if (this.timer > -1) {
  3783. self.clearInterval(this.timer);
  3784. this.timer = -1;
  3785. }
  3786. };
  3787. _proto.getAutoLevelKey = function getAutoLevelKey() {
  3788. return this.getBwEstimate() + "_" + this.getStarvationDelay().toFixed(2);
  3789. };
  3790. _proto.getNextABRAutoLevel = function getNextABRAutoLevel() {
  3791. var fragCurrent = this.fragCurrent,
  3792. partCurrent = this.partCurrent,
  3793. hls = this.hls;
  3794. if (hls.levels.length <= 1) {
  3795. return hls.loadLevel;
  3796. }
  3797. var maxAutoLevel = hls.maxAutoLevel,
  3798. config = hls.config,
  3799. minAutoLevel = hls.minAutoLevel;
  3800. var currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  3801. var avgbw = this.getBwEstimate();
  3802. // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.
  3803. var bufferStarvationDelay = this.getStarvationDelay();
  3804. var bwFactor = config.abrBandWidthFactor;
  3805. var bwUpFactor = config.abrBandWidthUpFactor;
  3806. // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all
  3807. if (bufferStarvationDelay) {
  3808. var _bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, 0, bwFactor, bwUpFactor);
  3809. if (_bestLevel >= 0) {
  3810. this.rebufferNotice = -1;
  3811. return _bestLevel;
  3812. }
  3813. }
  3814. // not possible to get rid of rebuffering... try to find level that will guarantee less than maxStarvationDelay of rebuffering
  3815. var maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay;
  3816. if (!bufferStarvationDelay) {
  3817. // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test
  3818. var bitrateTestDelay = this.bitrateTestDelay;
  3819. if (bitrateTestDelay) {
  3820. // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value
  3821. // max video loading delay used in automatic start level selection :
  3822. // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +
  3823. // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )
  3824. // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration
  3825. var maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
  3826. maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
  3827. this.info("bitrate test took " + Math.round(1000 * bitrateTestDelay) + "ms, set first fragment max fetchDuration to " + Math.round(1000 * maxStarvationDelay) + " ms");
  3828. // don't use conservative factor on bitrate test
  3829. bwFactor = bwUpFactor = 1;
  3830. }
  3831. }
  3832. var bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor);
  3833. if (this.rebufferNotice !== bestLevel) {
  3834. this.rebufferNotice = bestLevel;
  3835. this.info((bufferStarvationDelay ? 'rebuffering expected' : 'buffer is empty') + ", optimal quality level " + bestLevel);
  3836. }
  3837. if (bestLevel > -1) {
  3838. return bestLevel;
  3839. }
  3840. // If no matching level found, see if min auto level would be a better option
  3841. var minLevel = hls.levels[minAutoLevel];
  3842. var autoLevel = hls.loadLevelObj;
  3843. if (autoLevel && (minLevel == null ? void 0 : minLevel.bitrate) < autoLevel.bitrate) {
  3844. return minAutoLevel;
  3845. }
  3846. // or if bitrate is not lower, continue to use loadLevel
  3847. return hls.loadLevel;
  3848. };
  3849. _proto.getStarvationDelay = function getStarvationDelay() {
  3850. var hls = this.hls;
  3851. var media = hls.media;
  3852. if (!media) {
  3853. return Infinity;
  3854. }
  3855. // playbackRate is the absolute value of the playback rate; if media.playbackRate is 0, we use 1 to load as
  3856. // if we're playing back at the normal rate.
  3857. var playbackRate = media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1.0;
  3858. var bufferInfo = hls.mainForwardBufferInfo;
  3859. return (bufferInfo ? bufferInfo.len : 0) / playbackRate;
  3860. };
  3861. _proto.getBwEstimate = function getBwEstimate() {
  3862. return this.bwEstimator.canEstimate() ? this.bwEstimator.getEstimate() : this.hls.config.abrEwmaDefaultEstimate;
  3863. };
  3864. _proto.findBestLevel = function findBestLevel(currentBw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor) {
  3865. var _this$hls$latestLevel,
  3866. _this3 = this;
  3867. var maxFetchDuration = bufferStarvationDelay + maxStarvationDelay;
  3868. var lastLoadedFragLevel = this.lastLoadedFragLevel;
  3869. var selectionBaseLevel = lastLoadedFragLevel === -1 ? this.hls.firstLevel : lastLoadedFragLevel;
  3870. var fragCurrent = this.fragCurrent,
  3871. partCurrent = this.partCurrent;
  3872. var _this$hls = this.hls,
  3873. levels = _this$hls.levels,
  3874. allAudioTracks = _this$hls.allAudioTracks,
  3875. loadLevel = _this$hls.loadLevel,
  3876. config = _this$hls.config;
  3877. if (levels.length === 1) {
  3878. return 0;
  3879. }
  3880. var level = levels[selectionBaseLevel];
  3881. var live = !!((_this$hls$latestLevel = this.hls.latestLevelDetails) != null && _this$hls$latestLevel.live);
  3882. var firstSelection = loadLevel === -1 || lastLoadedFragLevel === -1;
  3883. var currentCodecSet;
  3884. var currentVideoRange = 'SDR';
  3885. var currentFrameRate = (level == null ? void 0 : level.frameRate) || 0;
  3886. var audioPreference = config.audioPreference,
  3887. videoPreference = config.videoPreference;
  3888. var audioTracksByGroup = this.audioTracksByGroup || (this.audioTracksByGroup = getAudioTracksByGroup(allAudioTracks));
  3889. var minStartIndex = -1;
  3890. if (firstSelection) {
  3891. if (this.firstSelection !== -1) {
  3892. return this.firstSelection;
  3893. }
  3894. var codecTiers = this.codecTiers || (this.codecTiers = getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel));
  3895. var startTier = getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference);
  3896. var codecSet = startTier.codecSet,
  3897. videoRanges = startTier.videoRanges,
  3898. minFramerate = startTier.minFramerate,
  3899. minBitrate = startTier.minBitrate,
  3900. minIndex = startTier.minIndex,
  3901. preferHDR = startTier.preferHDR;
  3902. minStartIndex = minIndex;
  3903. currentCodecSet = codecSet;
  3904. currentVideoRange = preferHDR ? videoRanges[videoRanges.length - 1] : videoRanges[0];
  3905. currentFrameRate = minFramerate;
  3906. currentBw = Math.max(currentBw, minBitrate);
  3907. this.log("picked start tier " + stringify(startTier));
  3908. } else {
  3909. currentCodecSet = level == null ? void 0 : level.codecSet;
  3910. currentVideoRange = level == null ? void 0 : level.videoRange;
  3911. }
  3912. var currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  3913. var ttfbEstimateSec = this.bwEstimator.getEstimateTTFB() / 1000;
  3914. var levelsSkipped = [];
  3915. var _loop = function _loop() {
  3916. var _levelInfo$supportedR, _levelInfo$supportedR2;
  3917. var levelInfo = levels[i];
  3918. var upSwitch = i > selectionBaseLevel;
  3919. if (!levelInfo) {
  3920. return 0; // continue
  3921. }
  3922. // skip candidates which change codec-family or video-range,
  3923. // and which decrease or increase frame-rate for up and down-switch respectfully
  3924. if (currentCodecSet && levelInfo.codecSet !== currentCodecSet || currentVideoRange && levelInfo.videoRange !== currentVideoRange || upSwitch && currentFrameRate > levelInfo.frameRate || !upSwitch && currentFrameRate > 0 && currentFrameRate < levelInfo.frameRate || (_levelInfo$supportedR = levelInfo.supportedResult) != null && (_levelInfo$supportedR2 = _levelInfo$supportedR.decodingInfoResults) != null && _levelInfo$supportedR2.some(function (info) {
  3925. return info.smooth === false;
  3926. })) {
  3927. if (!firstSelection || i !== minStartIndex) {
  3928. levelsSkipped.push(i);
  3929. return 0; // continue
  3930. }
  3931. }
  3932. var levelDetails = levelInfo.details;
  3933. var avgDuration = (partCurrent ? levelDetails == null ? void 0 : levelDetails.partTarget : levelDetails == null ? void 0 : levelDetails.averagetargetduration) || currentFragDuration;
  3934. var adjustedbw;
  3935. // follow algorithm captured from stagefright :
  3936. // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
  3937. // Pick the highest bandwidth stream below or equal to estimated bandwidth.
  3938. // consider only 80% of the available bandwidth, but if we are switching up,
  3939. // be even more conservative (70%) to avoid overestimating and immediately
  3940. // switching back.
  3941. if (!upSwitch) {
  3942. adjustedbw = bwFactor * currentBw;
  3943. } else {
  3944. adjustedbw = bwUpFactor * currentBw;
  3945. }
  3946. // Use average bitrate when starvation delay (buffer length) is gt or eq two segment durations and rebuffering is not expected (maxStarvationDelay > 0)
  3947. var bitrate = currentFragDuration && bufferStarvationDelay >= currentFragDuration * 2 && maxStarvationDelay === 0 ? levelInfo.averageBitrate : levelInfo.maxBitrate;
  3948. var fetchDuration = _this3.getTimeToLoadFrag(ttfbEstimateSec, adjustedbw, bitrate * avgDuration, levelDetails === undefined);
  3949. var canSwitchWithinTolerance =
  3950. // if adjusted bw is greater than level bitrate AND
  3951. adjustedbw >= bitrate && (
  3952. // no level change, or new level has no error history
  3953. i === lastLoadedFragLevel || levelInfo.loadError === 0 && levelInfo.fragmentError === 0) && (
  3954. // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
  3955. // 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 ...
  3956. // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1
  3957. fetchDuration <= ttfbEstimateSec || !isFiniteNumber(fetchDuration) || live && !_this3.bitrateTestDelay || fetchDuration < maxFetchDuration);
  3958. if (canSwitchWithinTolerance) {
  3959. var forcedAutoLevel = _this3.forcedAutoLevel;
  3960. if (i !== loadLevel && (forcedAutoLevel === -1 || forcedAutoLevel !== loadLevel)) {
  3961. if (levelsSkipped.length) {
  3962. _this3.trace("Skipped level(s) " + levelsSkipped.join(',') + " of " + maxAutoLevel + " max with CODECS and VIDEO-RANGE:\"" + levels[levelsSkipped[0]].codecs + "\" " + levels[levelsSkipped[0]].videoRange + "; not compatible with \"" + currentCodecSet + "\" " + currentVideoRange);
  3963. }
  3964. _this3.info("switch candidate:" + selectionBaseLevel + "->" + i + " adjustedbw(" + Math.round(adjustedbw) + ")-bitrate=" + Math.round(adjustedbw - bitrate) + " ttfb:" + ttfbEstimateSec.toFixed(1) + " avgDuration:" + avgDuration.toFixed(1) + " maxFetchDuration:" + maxFetchDuration.toFixed(1) + " fetchDuration:" + fetchDuration.toFixed(1) + " firstSelection:" + firstSelection + " codecSet:" + levelInfo.codecSet + " videoRange:" + levelInfo.videoRange + " hls.loadLevel:" + loadLevel);
  3965. }
  3966. if (firstSelection) {
  3967. _this3.firstSelection = i;
  3968. }
  3969. // as we are looping from highest to lowest, this will return the best achievable quality level
  3970. return {
  3971. v: i
  3972. };
  3973. }
  3974. },
  3975. _ret;
  3976. for (var i = maxAutoLevel; i >= minAutoLevel; i--) {
  3977. _ret = _loop();
  3978. if (_ret === 0) continue;
  3979. if (_ret) return _ret.v;
  3980. }
  3981. // not enough time budget even with quality level 0 ... rebuffering might happen
  3982. return -1;
  3983. };
  3984. _proto.deriveNextAutoLevel = function deriveNextAutoLevel(nextLevel) {
  3985. var _this$hls2 = this.hls,
  3986. maxAutoLevel = _this$hls2.maxAutoLevel,
  3987. minAutoLevel = _this$hls2.minAutoLevel;
  3988. return Math.min(Math.max(nextLevel, minAutoLevel), maxAutoLevel);
  3989. };
  3990. return _createClass(AbrController, [{
  3991. key: "firstAutoLevel",
  3992. get: function get() {
  3993. var _this$hls3 = this.hls,
  3994. maxAutoLevel = _this$hls3.maxAutoLevel,
  3995. minAutoLevel = _this$hls3.minAutoLevel;
  3996. var bwEstimate = this.getBwEstimate();
  3997. var maxStartDelay = this.hls.config.maxStarvationDelay;
  3998. var abrAutoLevel = this.findBestLevel(bwEstimate, minAutoLevel, maxAutoLevel, 0, maxStartDelay, 1, 1);
  3999. if (abrAutoLevel > -1) {
  4000. return abrAutoLevel;
  4001. }
  4002. var firstLevel = this.hls.firstLevel;
  4003. var clamped = Math.min(Math.max(firstLevel, minAutoLevel), maxAutoLevel);
  4004. this.warn("Could not find best starting auto level. Defaulting to first in playlist " + firstLevel + " clamped to " + clamped);
  4005. return clamped;
  4006. }
  4007. }, {
  4008. key: "forcedAutoLevel",
  4009. get: function get() {
  4010. if (this.nextAutoLevelKey) {
  4011. return -1;
  4012. }
  4013. return this._nextAutoLevel;
  4014. }
  4015. // return next auto level
  4016. }, {
  4017. key: "nextAutoLevel",
  4018. get: function get() {
  4019. var forcedAutoLevel = this.forcedAutoLevel;
  4020. var bwEstimator = this.bwEstimator;
  4021. var useEstimate = bwEstimator.canEstimate();
  4022. var loadedFirstFrag = this.lastLoadedFragLevel > -1;
  4023. // in case next auto level has been forced, and bw not available or not reliable, return forced value
  4024. if (forcedAutoLevel !== -1 && (!useEstimate || !loadedFirstFrag || this.nextAutoLevelKey === this.getAutoLevelKey())) {
  4025. return forcedAutoLevel;
  4026. }
  4027. // compute next level using ABR logic
  4028. var nextABRAutoLevel = useEstimate && loadedFirstFrag ? this.getNextABRAutoLevel() : this.firstAutoLevel;
  4029. // use forced auto level while it hasn't errored more than ABR selection
  4030. if (forcedAutoLevel !== -1) {
  4031. var levels = this.hls.levels;
  4032. if (levels.length > Math.max(forcedAutoLevel, nextABRAutoLevel) && levels[forcedAutoLevel].loadError <= levels[nextABRAutoLevel].loadError) {
  4033. return forcedAutoLevel;
  4034. }
  4035. }
  4036. // save result until state has changed
  4037. this._nextAutoLevel = nextABRAutoLevel;
  4038. this.nextAutoLevelKey = this.getAutoLevelKey();
  4039. return nextABRAutoLevel;
  4040. },
  4041. set: function set(nextLevel) {
  4042. var value = this.deriveNextAutoLevel(nextLevel);
  4043. if (this._nextAutoLevel !== value) {
  4044. this.nextAutoLevelKey = '';
  4045. this._nextAutoLevel = value;
  4046. }
  4047. }
  4048. }]);
  4049. }(Logger);
  4050. var BufferOperationQueue = /*#__PURE__*/function () {
  4051. function BufferOperationQueue(sourceBufferReference) {
  4052. this.tracks = void 0;
  4053. this.queues = {
  4054. video: [],
  4055. audio: [],
  4056. audiovideo: []
  4057. };
  4058. this.tracks = sourceBufferReference;
  4059. }
  4060. var _proto = BufferOperationQueue.prototype;
  4061. _proto.destroy = function destroy() {
  4062. this.tracks = this.queues = null;
  4063. };
  4064. _proto.append = function append(operation, type, pending) {
  4065. if (this.queues === null || this.tracks === null) {
  4066. return;
  4067. }
  4068. var queue = this.queues[type];
  4069. queue.push(operation);
  4070. if (queue.length === 1 && !pending) {
  4071. this.executeNext(type);
  4072. }
  4073. };
  4074. _proto.appendBlocker = function appendBlocker(type) {
  4075. var _this = this;
  4076. return new Promise(function (resolve) {
  4077. var operation = {
  4078. label: 'async-blocker',
  4079. execute: resolve,
  4080. onStart: function onStart() {},
  4081. onComplete: function onComplete() {},
  4082. onError: function onError() {}
  4083. };
  4084. _this.append(operation, type);
  4085. });
  4086. };
  4087. _proto.prependBlocker = function prependBlocker(type) {
  4088. var _this2 = this;
  4089. return new Promise(function (resolve) {
  4090. if (_this2.queues) {
  4091. var operation = {
  4092. label: 'async-blocker-prepend',
  4093. execute: resolve,
  4094. onStart: function onStart() {},
  4095. onComplete: function onComplete() {},
  4096. onError: function onError() {}
  4097. };
  4098. _this2.queues[type].unshift(operation);
  4099. }
  4100. });
  4101. };
  4102. _proto.removeBlockers = function removeBlockers() {
  4103. if (this.queues === null) {
  4104. return;
  4105. }
  4106. [this.queues.video, this.queues.audio, this.queues.audiovideo].forEach(function (queue) {
  4107. var _queue$;
  4108. var label = (_queue$ = queue[0]) == null ? void 0 : _queue$.label;
  4109. if (label === 'async-blocker' || label === 'async-blocker-prepend') {
  4110. queue[0].execute();
  4111. queue.splice(0, 1);
  4112. }
  4113. });
  4114. };
  4115. _proto.unblockAudio = function unblockAudio(op) {
  4116. if (this.queues === null) {
  4117. return;
  4118. }
  4119. var queue = this.queues.audio;
  4120. if (queue[0] === op) {
  4121. this.shiftAndExecuteNext('audio');
  4122. }
  4123. };
  4124. _proto.executeNext = function executeNext(type) {
  4125. if (this.queues === null || this.tracks === null) {
  4126. return;
  4127. }
  4128. var queue = this.queues[type];
  4129. if (queue.length) {
  4130. var operation = queue[0];
  4131. try {
  4132. // Operations are expected to result in an 'updateend' event being fired. If not, the queue will lock. Operations
  4133. // which do not end with this event must call _onSBUpdateEnd manually
  4134. operation.execute();
  4135. } catch (error) {
  4136. var _this$tracks$type;
  4137. operation.onError(error);
  4138. if (this.queues === null || this.tracks === null) {
  4139. return;
  4140. }
  4141. // Only shift the current operation off, otherwise the updateend handler will do this for us
  4142. var sb = (_this$tracks$type = this.tracks[type]) == null ? void 0 : _this$tracks$type.buffer;
  4143. if (!(sb != null && sb.updating)) {
  4144. this.shiftAndExecuteNext(type);
  4145. }
  4146. }
  4147. }
  4148. };
  4149. _proto.shiftAndExecuteNext = function shiftAndExecuteNext(type) {
  4150. if (this.queues === null) {
  4151. return;
  4152. }
  4153. this.queues[type].shift();
  4154. this.executeNext(type);
  4155. };
  4156. _proto.current = function current(type) {
  4157. var _this$queues;
  4158. return ((_this$queues = this.queues) == null ? void 0 : _this$queues[type][0]) || null;
  4159. };
  4160. _proto.toString = function toString() {
  4161. var queues = this.queues,
  4162. tracks = this.tracks;
  4163. if (queues === null || tracks === null) {
  4164. return "<destroyed>";
  4165. }
  4166. return "\n" + this.list('video') + "\n" + this.list('audio') + "\n" + this.list('audiovideo') + "}";
  4167. };
  4168. _proto.list = function list(type) {
  4169. var _this$queues2, _this$tracks;
  4170. return (_this$queues2 = this.queues) != null && _this$queues2[type] || (_this$tracks = this.tracks) != null && _this$tracks[type] ? type + ": (" + this.listSbInfo(type) + ") " + this.listOps(type) : '';
  4171. };
  4172. _proto.listSbInfo = function listSbInfo(type) {
  4173. var _this$tracks2;
  4174. var track = (_this$tracks2 = this.tracks) == null ? void 0 : _this$tracks2[type];
  4175. var sb = track == null ? void 0 : track.buffer;
  4176. if (!sb) {
  4177. return 'none';
  4178. }
  4179. return "SourceBuffer" + (sb.updating ? ' updating' : '') + (track.ended ? ' ended' : '') + (track.ending ? ' ending' : '');
  4180. };
  4181. _proto.listOps = function listOps(type) {
  4182. var _this$queues3;
  4183. return ((_this$queues3 = this.queues) == null ? void 0 : _this$queues3[type].map(function (op) {
  4184. return op.label;
  4185. }).join(', ')) || '';
  4186. };
  4187. return BufferOperationQueue;
  4188. }();
  4189. var BinarySearch = {
  4190. /**
  4191. * Searches for an item in an array which matches a certain condition.
  4192. * This requires the condition to only match one item in the array,
  4193. * and for the array to be ordered.
  4194. *
  4195. * @param list The array to search.
  4196. * @param comparisonFn
  4197. * Called and provided a candidate item as the first argument.
  4198. * Should return:
  4199. * > -1 if the item should be located at a lower index than the provided item.
  4200. * > 1 if the item should be located at a higher index than the provided item.
  4201. * > 0 if the item is the item you're looking for.
  4202. *
  4203. * @returns the object if found, otherwise returns null
  4204. */
  4205. search: function search(list, comparisonFn) {
  4206. var minIndex = 0;
  4207. var maxIndex = list.length - 1;
  4208. var currentIndex = null;
  4209. var currentElement = null;
  4210. while (minIndex <= maxIndex) {
  4211. currentIndex = (minIndex + maxIndex) / 2 | 0;
  4212. currentElement = list[currentIndex];
  4213. var comparisonResult = comparisonFn(currentElement);
  4214. if (comparisonResult > 0) {
  4215. minIndex = currentIndex + 1;
  4216. } else if (comparisonResult < 0) {
  4217. maxIndex = currentIndex - 1;
  4218. } else {
  4219. return currentElement;
  4220. }
  4221. }
  4222. return null;
  4223. }
  4224. };
  4225. /**
  4226. * Returns first fragment whose endPdt value exceeds the given PDT, or null.
  4227. * @param fragments - The array of candidate fragments
  4228. * @param PDTValue - The PDT value which must be exceeded
  4229. * @param maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  4230. */
  4231. function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
  4232. if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !isFiniteNumber(PDTValue)) {
  4233. return null;
  4234. }
  4235. // if less than start
  4236. var startPDT = fragments[0].programDateTime;
  4237. if (PDTValue < (startPDT || 0)) {
  4238. return null;
  4239. }
  4240. var endPDT = fragments[fragments.length - 1].endProgramDateTime;
  4241. if (PDTValue >= (endPDT || 0)) {
  4242. return null;
  4243. }
  4244. for (var seg = 0; seg < fragments.length; ++seg) {
  4245. var frag = fragments[seg];
  4246. if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
  4247. return frag;
  4248. }
  4249. }
  4250. return null;
  4251. }
  4252. /**
  4253. * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.
  4254. * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus
  4255. * breaking any traps which would cause the same fragment to be continuously selected within a small range.
  4256. * @param fragPrevious - The last frag successfully appended
  4257. * @param fragments - The array of candidate fragments
  4258. * @param bufferEnd - The end of the contiguous buffered range the playhead is currently within
  4259. * @param maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  4260. * @returns a matching fragment or null
  4261. */
  4262. function findFragmentByPTS(fragPrevious, fragments, bufferEnd, maxFragLookUpTolerance, nextFragLookupTolerance) {
  4263. if (bufferEnd === void 0) {
  4264. bufferEnd = 0;
  4265. }
  4266. if (maxFragLookUpTolerance === void 0) {
  4267. maxFragLookUpTolerance = 0;
  4268. }
  4269. if (nextFragLookupTolerance === void 0) {
  4270. nextFragLookupTolerance = 0.005;
  4271. }
  4272. var fragNext = null;
  4273. if (fragPrevious) {
  4274. fragNext = fragments[1 + fragPrevious.sn - fragments[0].sn] || null;
  4275. // check for buffer-end rounding error
  4276. var bufferEdgeError = fragPrevious.endDTS - bufferEnd;
  4277. if (bufferEdgeError > 0 && bufferEdgeError < 0.0000015) {
  4278. bufferEnd += 0.0000015;
  4279. }
  4280. if (fragNext && fragPrevious.level !== fragNext.level && fragNext.end <= fragPrevious.end) {
  4281. fragNext = fragments[2 + fragPrevious.sn - fragments[0].sn] || null;
  4282. }
  4283. } else if (bufferEnd === 0 && fragments[0].start === 0) {
  4284. fragNext = fragments[0];
  4285. }
  4286. // Prefer the next fragment if it's within tolerance
  4287. if (fragNext && ((!fragPrevious || fragPrevious.level === fragNext.level) && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0 || fragmentWithinFastStartSwitch(fragNext, fragPrevious, Math.min(nextFragLookupTolerance, maxFragLookUpTolerance)))) {
  4288. return fragNext;
  4289. }
  4290. // We might be seeking past the tolerance so find the best match
  4291. var foundFragment = BinarySearch.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
  4292. if (foundFragment && (foundFragment !== fragPrevious || !fragNext)) {
  4293. return foundFragment;
  4294. }
  4295. // If no match was found return the next fragment after fragPrevious, or null
  4296. return fragNext;
  4297. }
  4298. function fragmentWithinFastStartSwitch(fragNext, fragPrevious, nextFragLookupTolerance) {
  4299. if (fragPrevious && fragPrevious.start === 0 && fragPrevious.level < fragNext.level && (fragPrevious.endPTS || 0) > 0) {
  4300. var firstDuration = fragPrevious.tagList.reduce(function (duration, tag) {
  4301. if (tag[0] === 'INF') {
  4302. duration += parseFloat(tag[1]);
  4303. }
  4304. return duration;
  4305. }, nextFragLookupTolerance);
  4306. return fragNext.start <= firstDuration;
  4307. }
  4308. return false;
  4309. }
  4310. /**
  4311. * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.
  4312. * @param candidate - The fragment to test
  4313. * @param bufferEnd - The end of the current buffered range the playhead is currently within
  4314. * @param maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous
  4315. * @returns 0 if it matches, 1 if too low, -1 if too high
  4316. */
  4317. function fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, candidate) {
  4318. if (bufferEnd === void 0) {
  4319. bufferEnd = 0;
  4320. }
  4321. if (maxFragLookUpTolerance === void 0) {
  4322. maxFragLookUpTolerance = 0;
  4323. }
  4324. // eagerly accept an accurate match (no tolerance)
  4325. if (candidate.start <= bufferEnd && candidate.start + candidate.duration > bufferEnd) {
  4326. return 0;
  4327. }
  4328. // offset should be within fragment boundary - config.maxFragLookUpTolerance
  4329. // this is to cope with situations like
  4330. // bufferEnd = 9.991
  4331. // frag[Ø] : [0,10]
  4332. // frag[1] : [10,20]
  4333. // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
  4334. // frag start frag start+duration
  4335. // |-----------------------------|
  4336. // <---> <--->
  4337. // ...--------><-----------------------------><---------....
  4338. // previous frag matching fragment next frag
  4339. // return -1 return 0 return 1
  4340. // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
  4341. // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
  4342. var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
  4343. if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
  4344. return 1;
  4345. } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
  4346. // if maxFragLookUpTolerance will have negative value then don't return -1 for first element
  4347. return -1;
  4348. }
  4349. return 0;
  4350. }
  4351. /**
  4352. * The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.
  4353. * This function tests the candidate's program date time values, as represented in Unix time
  4354. * @param candidate - The fragment to test
  4355. * @param pdtBufferEnd - The Unix time representing the end of the current buffered range
  4356. * @param maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous
  4357. * @returns true if contiguous, false otherwise
  4358. */
  4359. function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
  4360. var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000;
  4361. // endProgramDateTime can be null, default to zero
  4362. var endProgramDateTime = candidate.endProgramDateTime || 0;
  4363. return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
  4364. }
  4365. function findNearestWithCC(details, cc, pos) {
  4366. if (details) {
  4367. if (details.startCC <= cc && details.endCC >= cc) {
  4368. var fragments = details.fragments;
  4369. var fragmentHint = details.fragmentHint;
  4370. if (fragmentHint) {
  4371. fragments = fragments.concat(fragmentHint);
  4372. }
  4373. var closest;
  4374. BinarySearch.search(fragments, function (candidate) {
  4375. if (candidate.cc < cc) {
  4376. return 1;
  4377. }
  4378. if (candidate.cc > cc) {
  4379. return -1;
  4380. }
  4381. closest = candidate;
  4382. if (candidate.end <= pos) {
  4383. return 1;
  4384. }
  4385. if (candidate.start > pos) {
  4386. return -1;
  4387. }
  4388. return 0;
  4389. });
  4390. return closest || null;
  4391. }
  4392. }
  4393. return null;
  4394. }
  4395. function isTimeoutError(error) {
  4396. switch (error.details) {
  4397. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  4398. case ErrorDetails.KEY_LOAD_TIMEOUT:
  4399. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  4400. case ErrorDetails.MANIFEST_LOAD_TIMEOUT:
  4401. return true;
  4402. }
  4403. return false;
  4404. }
  4405. function getRetryConfig(loadPolicy, error) {
  4406. var isTimeout = isTimeoutError(error);
  4407. return loadPolicy.default[(isTimeout ? 'timeout' : 'error') + "Retry"];
  4408. }
  4409. function getRetryDelay(retryConfig, retryCount) {
  4410. // exponential backoff capped to max retry delay
  4411. var backoffFactor = retryConfig.backoff === 'linear' ? 1 : Math.pow(2, retryCount);
  4412. return Math.min(backoffFactor * retryConfig.retryDelayMs, retryConfig.maxRetryDelayMs);
  4413. }
  4414. function getLoaderConfigWithoutReties(loderConfig) {
  4415. return _objectSpread2(_objectSpread2({}, loderConfig), {
  4416. errorRetry: null,
  4417. timeoutRetry: null
  4418. });
  4419. }
  4420. function shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse) {
  4421. if (!retryConfig) {
  4422. return false;
  4423. }
  4424. var httpStatus = loaderResponse == null ? void 0 : loaderResponse.code;
  4425. var retry = retryCount < retryConfig.maxNumRetry && (retryForHttpStatus(httpStatus) || !!isTimeout);
  4426. return retryConfig.shouldRetry ? retryConfig.shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse, retry) : retry;
  4427. }
  4428. function retryForHttpStatus(httpStatus) {
  4429. // Do not retry on status 4xx, status 0 (CORS error), or undefined (decrypt/gap/parse error)
  4430. return httpStatus === 0 && navigator.onLine === false || !!httpStatus && (httpStatus < 400 || httpStatus > 499);
  4431. }
  4432. var NetworkErrorAction = {
  4433. DoNothing: 0,
  4434. SendAlternateToPenaltyBox: 2,
  4435. RemoveAlternatePermanently: 3,
  4436. RetryRequest: 5
  4437. };
  4438. var ErrorActionFlags = {
  4439. None: 0,
  4440. MoveAllAlternatesMatchingHost: 1,
  4441. MoveAllAlternatesMatchingHDCP: 2};
  4442. var ErrorController = /*#__PURE__*/function (_Logger) {
  4443. function ErrorController(hls) {
  4444. var _this;
  4445. _this = _Logger.call(this, 'error-controller', hls.logger) || this;
  4446. _this.hls = void 0;
  4447. _this.playlistError = 0;
  4448. _this.penalizedRenditions = {};
  4449. _this.hls = hls;
  4450. _this.registerListeners();
  4451. return _this;
  4452. }
  4453. _inheritsLoose(ErrorController, _Logger);
  4454. var _proto = ErrorController.prototype;
  4455. _proto.registerListeners = function registerListeners() {
  4456. var hls = this.hls;
  4457. hls.on(Events.ERROR, this.onError, this);
  4458. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4459. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  4460. };
  4461. _proto.unregisterListeners = function unregisterListeners() {
  4462. var hls = this.hls;
  4463. if (!hls) {
  4464. return;
  4465. }
  4466. hls.off(Events.ERROR, this.onError, this);
  4467. hls.off(Events.ERROR, this.onErrorOut, this);
  4468. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4469. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  4470. };
  4471. _proto.destroy = function destroy() {
  4472. this.unregisterListeners();
  4473. // @ts-ignore
  4474. this.hls = null;
  4475. this.penalizedRenditions = {};
  4476. };
  4477. _proto.startLoad = function startLoad(startPosition) {};
  4478. _proto.stopLoad = function stopLoad() {
  4479. this.playlistError = 0;
  4480. };
  4481. _proto.getVariantLevelIndex = function getVariantLevelIndex(frag) {
  4482. return (frag == null ? void 0 : frag.type) === PlaylistLevelType.MAIN ? frag.level : this.hls.loadLevel;
  4483. };
  4484. _proto.onManifestLoading = function onManifestLoading() {
  4485. this.playlistError = 0;
  4486. this.penalizedRenditions = {};
  4487. };
  4488. _proto.onLevelUpdated = function onLevelUpdated() {
  4489. this.playlistError = 0;
  4490. };
  4491. _proto.onError = function onError(event, data) {
  4492. var _data$frag;
  4493. if (data.fatal) {
  4494. return;
  4495. }
  4496. var hls = this.hls;
  4497. var context = data.context;
  4498. switch (data.details) {
  4499. case ErrorDetails.FRAG_LOAD_ERROR:
  4500. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  4501. case ErrorDetails.KEY_LOAD_ERROR:
  4502. case ErrorDetails.KEY_LOAD_TIMEOUT:
  4503. data.errorAction = this.getFragRetryOrSwitchAction(data);
  4504. return;
  4505. case ErrorDetails.FRAG_PARSING_ERROR:
  4506. // ignore empty segment errors marked as gap
  4507. if ((_data$frag = data.frag) != null && _data$frag.gap) {
  4508. data.errorAction = createDoNothingErrorAction();
  4509. return;
  4510. }
  4511. // falls through
  4512. case ErrorDetails.FRAG_GAP:
  4513. case ErrorDetails.FRAG_DECRYPT_ERROR:
  4514. {
  4515. // Switch level if possible, otherwise allow retry count to reach max error retries
  4516. data.errorAction = this.getFragRetryOrSwitchAction(data);
  4517. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  4518. return;
  4519. }
  4520. case ErrorDetails.LEVEL_EMPTY_ERROR:
  4521. case ErrorDetails.LEVEL_PARSING_ERROR:
  4522. {
  4523. var _data$context, _data$context$levelDe;
  4524. // Only retry when empty and live
  4525. var levelIndex = data.parent === PlaylistLevelType.MAIN ? data.level : hls.loadLevel;
  4526. if (data.details === ErrorDetails.LEVEL_EMPTY_ERROR && !!((_data$context = data.context) != null && (_data$context$levelDe = _data$context.levelDetails) != null && _data$context$levelDe.live)) {
  4527. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, levelIndex);
  4528. } else {
  4529. // Escalate to fatal if not retrying or switching
  4530. data.levelRetry = false;
  4531. data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  4532. }
  4533. }
  4534. return;
  4535. case ErrorDetails.LEVEL_LOAD_ERROR:
  4536. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  4537. if (typeof (context == null ? void 0 : context.level) === 'number') {
  4538. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, context.level);
  4539. }
  4540. return;
  4541. case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
  4542. case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
  4543. case ErrorDetails.SUBTITLE_LOAD_ERROR:
  4544. case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:
  4545. if (context) {
  4546. var level = hls.loadLevelObj;
  4547. if (level && (context.type === PlaylistContextType.AUDIO_TRACK && level.hasAudioGroup(context.groupId) || context.type === PlaylistContextType.SUBTITLE_TRACK && level.hasSubtitleGroup(context.groupId))) {
  4548. // Perform Pathway switch or Redundant failover if possible for fastest recovery
  4549. // otherwise allow playlist retry count to reach max error retries
  4550. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, hls.loadLevel);
  4551. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  4552. data.errorAction.flags = ErrorActionFlags.MoveAllAlternatesMatchingHost;
  4553. return;
  4554. }
  4555. }
  4556. return;
  4557. case ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:
  4558. {
  4559. var _level = hls.loadLevelObj;
  4560. var restrictedHdcpLevel = _level == null ? void 0 : _level.attrs['HDCP-LEVEL'];
  4561. if (restrictedHdcpLevel) {
  4562. data.errorAction = {
  4563. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  4564. flags: ErrorActionFlags.MoveAllAlternatesMatchingHDCP,
  4565. hdcpLevel: restrictedHdcpLevel
  4566. };
  4567. } else {
  4568. this.keySystemError(data);
  4569. }
  4570. }
  4571. return;
  4572. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  4573. case ErrorDetails.REMUX_ALLOC_ERROR:
  4574. case ErrorDetails.BUFFER_APPEND_ERROR:
  4575. // Buffer-controller can set errorAction when append errors can be ignored or resolved locally
  4576. if (!data.errorAction) {
  4577. var _data$level;
  4578. data.errorAction = this.getLevelSwitchAction(data, (_data$level = data.level) != null ? _data$level : hls.loadLevel);
  4579. }
  4580. return;
  4581. case ErrorDetails.INTERNAL_EXCEPTION:
  4582. case ErrorDetails.BUFFER_APPENDING_ERROR:
  4583. case ErrorDetails.BUFFER_FULL_ERROR:
  4584. case ErrorDetails.LEVEL_SWITCH_ERROR:
  4585. case ErrorDetails.BUFFER_STALLED_ERROR:
  4586. case ErrorDetails.BUFFER_SEEK_OVER_HOLE:
  4587. case ErrorDetails.BUFFER_NUDGE_ON_STALL:
  4588. data.errorAction = createDoNothingErrorAction();
  4589. return;
  4590. }
  4591. if (data.type === ErrorTypes.KEY_SYSTEM_ERROR) {
  4592. this.keySystemError(data);
  4593. }
  4594. };
  4595. _proto.keySystemError = function keySystemError(data) {
  4596. var levelIndex = this.getVariantLevelIndex(data.frag);
  4597. // Do not retry level. Escalate to fatal if switching levels fails.
  4598. data.levelRetry = false;
  4599. data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  4600. };
  4601. _proto.getPlaylistRetryOrSwitchAction = function getPlaylistRetryOrSwitchAction(data, levelIndex) {
  4602. var hls = this.hls;
  4603. var retryConfig = getRetryConfig(hls.config.playlistLoadPolicy, data);
  4604. var retryCount = this.playlistError++;
  4605. var retry = shouldRetry(retryConfig, retryCount, isTimeoutError(data), data.response);
  4606. if (retry) {
  4607. return {
  4608. action: NetworkErrorAction.RetryRequest,
  4609. flags: ErrorActionFlags.None,
  4610. retryConfig: retryConfig,
  4611. retryCount: retryCount
  4612. };
  4613. }
  4614. var errorAction = this.getLevelSwitchAction(data, levelIndex);
  4615. if (retryConfig) {
  4616. errorAction.retryConfig = retryConfig;
  4617. errorAction.retryCount = retryCount;
  4618. }
  4619. return errorAction;
  4620. };
  4621. _proto.getFragRetryOrSwitchAction = function getFragRetryOrSwitchAction(data) {
  4622. var hls = this.hls;
  4623. // Share fragment error count accross media options (main, audio, subs)
  4624. // This allows for level based rendition switching when media option assets fail
  4625. var variantLevelIndex = this.getVariantLevelIndex(data.frag);
  4626. var level = hls.levels[variantLevelIndex];
  4627. var _hls$config = hls.config,
  4628. fragLoadPolicy = _hls$config.fragLoadPolicy,
  4629. keyLoadPolicy = _hls$config.keyLoadPolicy;
  4630. var retryConfig = getRetryConfig(data.details.startsWith('key') ? keyLoadPolicy : fragLoadPolicy, data);
  4631. var fragmentErrors = hls.levels.reduce(function (acc, level) {
  4632. return acc + level.fragmentError;
  4633. }, 0);
  4634. // Switch levels when out of retried or level index out of bounds
  4635. if (level) {
  4636. if (data.details !== ErrorDetails.FRAG_GAP) {
  4637. level.fragmentError++;
  4638. }
  4639. var retry = shouldRetry(retryConfig, fragmentErrors, isTimeoutError(data), data.response);
  4640. if (retry) {
  4641. return {
  4642. action: NetworkErrorAction.RetryRequest,
  4643. flags: ErrorActionFlags.None,
  4644. retryConfig: retryConfig,
  4645. retryCount: fragmentErrors
  4646. };
  4647. }
  4648. }
  4649. // Reach max retry count, or Missing level reference
  4650. // Switch to valid index
  4651. var errorAction = this.getLevelSwitchAction(data, variantLevelIndex);
  4652. // Add retry details to allow skipping of FRAG_PARSING_ERROR
  4653. if (retryConfig) {
  4654. errorAction.retryConfig = retryConfig;
  4655. errorAction.retryCount = fragmentErrors;
  4656. }
  4657. return errorAction;
  4658. };
  4659. _proto.getLevelSwitchAction = function getLevelSwitchAction(data, levelIndex) {
  4660. var hls = this.hls;
  4661. if (levelIndex === null || levelIndex === undefined) {
  4662. levelIndex = hls.loadLevel;
  4663. }
  4664. var level = this.hls.levels[levelIndex];
  4665. if (level) {
  4666. var _data$frag2, _data$context2;
  4667. var errorDetails = data.details;
  4668. level.loadError++;
  4669. if (errorDetails === ErrorDetails.BUFFER_APPEND_ERROR) {
  4670. level.fragmentError++;
  4671. }
  4672. // Search for next level to retry
  4673. var nextLevel = -1;
  4674. var levels = hls.levels,
  4675. loadLevel = hls.loadLevel,
  4676. minAutoLevel = hls.minAutoLevel,
  4677. maxAutoLevel = hls.maxAutoLevel;
  4678. if (!hls.autoLevelEnabled && !hls.config.preserveManualLevelOnError) {
  4679. hls.loadLevel = -1;
  4680. }
  4681. var fragErrorType = (_data$frag2 = data.frag) == null ? void 0 : _data$frag2.type;
  4682. // Find alternate audio codec if available on audio codec error
  4683. var isAudioCodecError = fragErrorType === PlaylistLevelType.AUDIO && errorDetails === ErrorDetails.FRAG_PARSING_ERROR || data.sourceBufferName === 'audio' && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  4684. var findAudioCodecAlternate = isAudioCodecError && levels.some(function (_ref) {
  4685. var audioCodec = _ref.audioCodec;
  4686. return level.audioCodec !== audioCodec;
  4687. });
  4688. // Find alternate video codec if available on video codec error
  4689. var isVideoCodecError = data.sourceBufferName === 'video' && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  4690. var findVideoCodecAlternate = isVideoCodecError && levels.some(function (_ref2) {
  4691. var codecSet = _ref2.codecSet,
  4692. audioCodec = _ref2.audioCodec;
  4693. return level.codecSet !== codecSet && level.audioCodec === audioCodec;
  4694. });
  4695. var _ref3 = (_data$context2 = data.context) != null ? _data$context2 : {},
  4696. playlistErrorType = _ref3.type,
  4697. playlistErrorGroupId = _ref3.groupId;
  4698. var _loop = function _loop() {
  4699. var candidate = (i + loadLevel) % levels.length;
  4700. if (candidate !== loadLevel && candidate >= minAutoLevel && candidate <= maxAutoLevel && levels[candidate].loadError === 0) {
  4701. var _level$audioGroups, _level$subtitleGroups;
  4702. var levelCandidate = levels[candidate];
  4703. // Skip level switch if GAP tag is found in next level at same position
  4704. if (errorDetails === ErrorDetails.FRAG_GAP && fragErrorType === PlaylistLevelType.MAIN && data.frag) {
  4705. var levelDetails = levels[candidate].details;
  4706. if (levelDetails) {
  4707. var fragCandidate = findFragmentByPTS(data.frag, levelDetails.fragments, data.frag.start);
  4708. if (fragCandidate != null && fragCandidate.gap) {
  4709. return 0; // continue
  4710. }
  4711. }
  4712. } else if (playlistErrorType === PlaylistContextType.AUDIO_TRACK && levelCandidate.hasAudioGroup(playlistErrorGroupId) || playlistErrorType === PlaylistContextType.SUBTITLE_TRACK && levelCandidate.hasSubtitleGroup(playlistErrorGroupId)) {
  4713. // For audio/subs playlist errors find another group ID or fallthrough to redundant fail-over
  4714. return 0; // continue
  4715. } else if (fragErrorType === PlaylistLevelType.AUDIO && (_level$audioGroups = level.audioGroups) != null && _level$audioGroups.some(function (groupId) {
  4716. return levelCandidate.hasAudioGroup(groupId);
  4717. }) || fragErrorType === PlaylistLevelType.SUBTITLE && (_level$subtitleGroups = level.subtitleGroups) != null && _level$subtitleGroups.some(function (groupId) {
  4718. return levelCandidate.hasSubtitleGroup(groupId);
  4719. }) || findAudioCodecAlternate && level.audioCodec === levelCandidate.audioCodec || !findAudioCodecAlternate && level.audioCodec !== levelCandidate.audioCodec || findVideoCodecAlternate && level.codecSet === levelCandidate.codecSet) {
  4720. // For video/audio/subs frag errors find another group ID or fallthrough to redundant fail-over
  4721. return 0; // continue
  4722. }
  4723. nextLevel = candidate;
  4724. return 1; // break
  4725. }
  4726. },
  4727. _ret;
  4728. for (var i = levels.length; i--;) {
  4729. _ret = _loop();
  4730. if (_ret === 0) continue;
  4731. if (_ret === 1) break;
  4732. }
  4733. if (nextLevel > -1 && hls.loadLevel !== nextLevel) {
  4734. data.levelRetry = true;
  4735. this.playlistError = 0;
  4736. return {
  4737. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  4738. flags: ErrorActionFlags.None,
  4739. nextAutoLevel: nextLevel
  4740. };
  4741. }
  4742. }
  4743. // No levels to switch / Manual level selection / Level not found
  4744. // Resolve with Pathway switch, Redundant fail-over, or stay on lowest Level
  4745. return {
  4746. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  4747. flags: ErrorActionFlags.MoveAllAlternatesMatchingHost
  4748. };
  4749. };
  4750. _proto.onErrorOut = function onErrorOut(event, data) {
  4751. var _data$errorAction;
  4752. switch ((_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.action) {
  4753. case NetworkErrorAction.DoNothing:
  4754. break;
  4755. case NetworkErrorAction.SendAlternateToPenaltyBox:
  4756. this.sendAlternateToPenaltyBox(data);
  4757. if (!data.errorAction.resolved && data.details !== ErrorDetails.FRAG_GAP) {
  4758. data.fatal = true;
  4759. } else if (/MediaSource readyState: ended/.test(data.error.message)) {
  4760. this.warn("MediaSource ended after \"" + data.sourceBufferName + "\" sourceBuffer append error. Attempting to recover from media error.");
  4761. this.hls.recoverMediaError();
  4762. }
  4763. break;
  4764. }
  4765. if (data.fatal) {
  4766. this.hls.stopLoad();
  4767. return;
  4768. }
  4769. };
  4770. _proto.sendAlternateToPenaltyBox = function sendAlternateToPenaltyBox(data) {
  4771. var hls = this.hls;
  4772. var errorAction = data.errorAction;
  4773. if (!errorAction) {
  4774. return;
  4775. }
  4776. var flags = errorAction.flags,
  4777. hdcpLevel = errorAction.hdcpLevel,
  4778. nextAutoLevel = errorAction.nextAutoLevel;
  4779. switch (flags) {
  4780. case ErrorActionFlags.None:
  4781. this.switchLevel(data, nextAutoLevel);
  4782. break;
  4783. case ErrorActionFlags.MoveAllAlternatesMatchingHDCP:
  4784. if (hdcpLevel) {
  4785. hls.maxHdcpLevel = HdcpLevels[HdcpLevels.indexOf(hdcpLevel) - 1];
  4786. errorAction.resolved = true;
  4787. }
  4788. this.warn("Restricting playback to HDCP-LEVEL of \"" + hls.maxHdcpLevel + "\" or lower");
  4789. break;
  4790. }
  4791. // If not resolved by previous actions try to switch to next level
  4792. if (!errorAction.resolved) {
  4793. this.switchLevel(data, nextAutoLevel);
  4794. }
  4795. };
  4796. _proto.switchLevel = function switchLevel(data, levelIndex) {
  4797. if (levelIndex !== undefined && data.errorAction) {
  4798. this.warn("switching to level " + levelIndex + " after " + data.details);
  4799. this.hls.nextAutoLevel = levelIndex;
  4800. data.errorAction.resolved = true;
  4801. // Stream controller is responsible for this but won't switch on false start
  4802. this.hls.nextLoadLevel = this.hls.nextAutoLevel;
  4803. if (data.details === ErrorDetails.BUFFER_ADD_CODEC_ERROR && data.mimeType && data.sourceBufferName !== 'audiovideo') {
  4804. var codec = getCodecsForMimeType(data.mimeType);
  4805. var levels = this.hls.levels;
  4806. for (var i = levels.length; i--;) {
  4807. if (levels[i][data.sourceBufferName + "Codec"] === codec) {
  4808. this.hls.removeLevel(i);
  4809. }
  4810. }
  4811. }
  4812. }
  4813. };
  4814. return ErrorController;
  4815. }(Logger);
  4816. function createDoNothingErrorAction(resolved) {
  4817. var errorAction = {
  4818. action: NetworkErrorAction.DoNothing,
  4819. flags: ErrorActionFlags.None
  4820. };
  4821. if (resolved) {
  4822. errorAction.resolved = true;
  4823. }
  4824. return errorAction;
  4825. }
  4826. /**
  4827. * Provides methods dealing with buffer length retrieval for example.
  4828. *
  4829. * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.
  4830. *
  4831. * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered
  4832. */
  4833. var noopBuffered = {
  4834. length: 0,
  4835. start: function start() {
  4836. return 0;
  4837. },
  4838. end: function end() {
  4839. return 0;
  4840. }
  4841. };
  4842. var BufferHelper = /*#__PURE__*/function () {
  4843. function BufferHelper() {}
  4844. /**
  4845. * Return true if `media`'s buffered include `position`
  4846. */
  4847. BufferHelper.isBuffered = function isBuffered(media, position) {
  4848. if (media) {
  4849. var buffered = BufferHelper.getBuffered(media);
  4850. for (var i = buffered.length; i--;) {
  4851. if (position >= buffered.start(i) && position <= buffered.end(i)) {
  4852. return true;
  4853. }
  4854. }
  4855. }
  4856. return false;
  4857. };
  4858. BufferHelper.bufferedRanges = function bufferedRanges(media) {
  4859. if (media) {
  4860. var timeRanges = BufferHelper.getBuffered(media);
  4861. return BufferHelper.timeRangesToArray(timeRanges);
  4862. }
  4863. return [];
  4864. };
  4865. BufferHelper.timeRangesToArray = function timeRangesToArray(timeRanges) {
  4866. var buffered = [];
  4867. for (var i = 0; i < timeRanges.length; i++) {
  4868. buffered.push({
  4869. start: timeRanges.start(i),
  4870. end: timeRanges.end(i)
  4871. });
  4872. }
  4873. return buffered;
  4874. };
  4875. BufferHelper.bufferInfo = function bufferInfo(media, pos, maxHoleDuration) {
  4876. if (media) {
  4877. var buffered = BufferHelper.bufferedRanges(media);
  4878. if (buffered.length) {
  4879. return BufferHelper.bufferedInfo(buffered, pos, maxHoleDuration);
  4880. }
  4881. }
  4882. return {
  4883. len: 0,
  4884. start: pos,
  4885. end: pos,
  4886. bufferedIndex: -1
  4887. };
  4888. };
  4889. BufferHelper.bufferedInfo = function bufferedInfo(buffered, pos, maxHoleDuration) {
  4890. pos = Math.max(0, pos);
  4891. // sort on buffer.start/smaller end (IE does not always return sorted buffered range)
  4892. if (buffered.length > 1) {
  4893. buffered.sort(function (a, b) {
  4894. return a.start - b.start || b.end - a.end;
  4895. });
  4896. }
  4897. var bufferedIndex = -1;
  4898. var buffered2 = [];
  4899. if (maxHoleDuration) {
  4900. // there might be some small holes between buffer time range
  4901. // consider that holes smaller than maxHoleDuration are irrelevant and build another
  4902. // buffer time range representations that discards those holes
  4903. for (var i = 0; i < buffered.length; i++) {
  4904. if (pos >= buffered[i].start && pos <= buffered[i].end) {
  4905. bufferedIndex = i;
  4906. }
  4907. var buf2len = buffered2.length;
  4908. if (buf2len) {
  4909. var buf2end = buffered2[buf2len - 1].end;
  4910. // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)
  4911. if (buffered[i].start - buf2end < maxHoleDuration) {
  4912. // merge overlapping time ranges
  4913. // update lastRange.end only if smaller than item.end
  4914. // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)
  4915. // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])
  4916. if (buffered[i].end > buf2end) {
  4917. buffered2[buf2len - 1].end = buffered[i].end;
  4918. }
  4919. } else {
  4920. // big hole
  4921. buffered2.push(buffered[i]);
  4922. }
  4923. } else {
  4924. // first value
  4925. buffered2.push(buffered[i]);
  4926. }
  4927. }
  4928. } else {
  4929. buffered2 = buffered;
  4930. }
  4931. var bufferLen = 0;
  4932. var nextStart;
  4933. // bufferStart and bufferEnd are buffer boundaries around current playback position (pos)
  4934. var bufferStart = pos;
  4935. var bufferEnd = pos;
  4936. for (var _i = 0; _i < buffered2.length; _i++) {
  4937. var start = buffered2[_i].start;
  4938. var end = buffered2[_i].end;
  4939. // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));
  4940. if (bufferedIndex === -1 && pos >= start && pos <= end) {
  4941. bufferedIndex = _i;
  4942. }
  4943. if (pos + maxHoleDuration >= start && pos < end) {
  4944. // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
  4945. bufferStart = start;
  4946. bufferEnd = end;
  4947. bufferLen = bufferEnd - pos;
  4948. } else if (pos + maxHoleDuration < start) {
  4949. nextStart = start;
  4950. break;
  4951. }
  4952. }
  4953. return {
  4954. len: bufferLen,
  4955. start: bufferStart || 0,
  4956. end: bufferEnd || 0,
  4957. nextStart: nextStart,
  4958. buffered: buffered,
  4959. bufferedIndex: bufferedIndex
  4960. };
  4961. }
  4962. /**
  4963. * Safe method to get buffered property.
  4964. * SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource
  4965. */;
  4966. BufferHelper.getBuffered = function getBuffered(media) {
  4967. try {
  4968. return media.buffered || noopBuffered;
  4969. } catch (e) {
  4970. logger.log('failed to get media.buffered', e);
  4971. return noopBuffered;
  4972. }
  4973. };
  4974. return BufferHelper;
  4975. }();
  4976. var VIDEO_CODEC_PROFILE_REPLACE = /(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;
  4977. var TRACK_REMOVED_ERROR_NAME = 'HlsJsTrackRemovedError';
  4978. var HlsJsTrackRemovedError = /*#__PURE__*/function (_Error) {
  4979. function HlsJsTrackRemovedError(message) {
  4980. var _this;
  4981. _this = _Error.call(this, message) || this;
  4982. _this.name = TRACK_REMOVED_ERROR_NAME;
  4983. return _this;
  4984. }
  4985. _inheritsLoose(HlsJsTrackRemovedError, _Error);
  4986. return HlsJsTrackRemovedError;
  4987. }(/*#__PURE__*/_wrapNativeSuper(Error));
  4988. var BufferController = /*#__PURE__*/function (_Logger) {
  4989. function BufferController(hls, fragmentTracker) {
  4990. var _this2;
  4991. _this2 = _Logger.call(this, 'buffer-controller', hls.logger) || this;
  4992. _this2.hls = void 0;
  4993. _this2.fragmentTracker = void 0;
  4994. // The level details used to determine duration, target-duration and live
  4995. _this2.details = null;
  4996. // cache the self generated object url to detect hijack of video tag
  4997. _this2._objectUrl = null;
  4998. // A queue of buffer operations which require the SourceBuffer to not be updating upon execution
  4999. _this2.operationQueue = null;
  5000. // The total number track codecs expected before any sourceBuffers are created (2: audio and video or 1: audiovideo | audio | video)
  5001. _this2.bufferCodecEventsTotal = 0;
  5002. // A reference to the attached media element
  5003. _this2.media = null;
  5004. // A reference to the active media source
  5005. _this2.mediaSource = null;
  5006. // Last MP3 audio chunk appended
  5007. _this2.lastMpegAudioChunk = null;
  5008. // Audio fragment blocked from appending until corresponding video appends or context changes
  5009. _this2.blockedAudioAppend = null;
  5010. // Keep track of video append position for unblocking audio
  5011. _this2.lastVideoAppendEnd = 0;
  5012. // Whether or not to use ManagedMediaSource API and append source element to media element.
  5013. _this2.appendSource = void 0;
  5014. // Transferred MediaSource information used to detmerine if duration end endstream may be appended
  5015. _this2.transferData = void 0;
  5016. // Directives used to override default MediaSource handling
  5017. _this2.overrides = void 0;
  5018. // Error counters
  5019. _this2.appendErrors = {
  5020. audio: 0,
  5021. video: 0,
  5022. audiovideo: 0
  5023. };
  5024. // Record of required or created buffers by type. SourceBuffer is stored in Track.buffer once created.
  5025. _this2.tracks = {};
  5026. // Array of SourceBuffer type and SourceBuffer (or null). One entry per TrackSet in this.tracks.
  5027. _this2.sourceBuffers = [[null, null], [null, null]];
  5028. _this2._onEndStreaming = function (event) {
  5029. var _this2$mediaSource;
  5030. if (!_this2.hls) {
  5031. return;
  5032. }
  5033. if (((_this2$mediaSource = _this2.mediaSource) == null ? void 0 : _this2$mediaSource.readyState) !== 'open') {
  5034. return;
  5035. }
  5036. _this2.hls.pauseBuffering();
  5037. };
  5038. _this2._onStartStreaming = function (event) {
  5039. if (!_this2.hls) {
  5040. return;
  5041. }
  5042. _this2.hls.resumeBuffering();
  5043. };
  5044. // Keep as arrow functions so that we can directly reference these functions directly as event listeners
  5045. _this2._onMediaSourceOpen = function (e) {
  5046. var _this3 = _this2,
  5047. media = _this3.media,
  5048. mediaSource = _this3.mediaSource;
  5049. if (e) {
  5050. _this2.log('Media source opened');
  5051. }
  5052. if (!media || !mediaSource) {
  5053. return;
  5054. }
  5055. // once received, don't listen anymore to sourceopen event
  5056. mediaSource.removeEventListener('sourceopen', _this2._onMediaSourceOpen);
  5057. media.removeEventListener('emptied', _this2._onMediaEmptied);
  5058. _this2.updateDuration();
  5059. _this2.hls.trigger(Events.MEDIA_ATTACHED, {
  5060. media: media,
  5061. mediaSource: mediaSource
  5062. });
  5063. if (_this2.mediaSource !== null) {
  5064. _this2.checkPendingTracks();
  5065. }
  5066. };
  5067. _this2._onMediaSourceClose = function () {
  5068. _this2.log('Media source closed');
  5069. };
  5070. _this2._onMediaSourceEnded = function () {
  5071. _this2.log('Media source ended');
  5072. };
  5073. _this2._onMediaEmptied = function () {
  5074. var _this4 = _this2,
  5075. mediaSrc = _this4.mediaSrc,
  5076. _objectUrl = _this4._objectUrl;
  5077. if (mediaSrc !== _objectUrl) {
  5078. _this2.error("Media element src was set while attaching MediaSource (" + _objectUrl + " > " + mediaSrc + ")");
  5079. }
  5080. };
  5081. _this2.hls = hls;
  5082. _this2.fragmentTracker = fragmentTracker;
  5083. _this2.appendSource = isManagedMediaSource(getMediaSource(hls.config.preferManagedMediaSource));
  5084. _this2.initTracks();
  5085. _this2.registerListeners();
  5086. return _this2;
  5087. }
  5088. _inheritsLoose(BufferController, _Logger);
  5089. var _proto = BufferController.prototype;
  5090. _proto.hasSourceTypes = function hasSourceTypes() {
  5091. return Object.keys(this.tracks).length > 0;
  5092. };
  5093. _proto.destroy = function destroy() {
  5094. this.unregisterListeners();
  5095. this.details = null;
  5096. this.lastMpegAudioChunk = this.blockedAudioAppend = null;
  5097. this.transferData = this.overrides = undefined;
  5098. if (this.operationQueue) {
  5099. this.operationQueue.destroy();
  5100. this.operationQueue = null;
  5101. }
  5102. // @ts-ignore
  5103. this.hls = this.fragmentTracker = null;
  5104. // @ts-ignore
  5105. this._onMediaSourceOpen = this._onMediaSourceClose = null;
  5106. // @ts-ignore
  5107. this._onMediaSourceEnded = null;
  5108. // @ts-ignore
  5109. this._onStartStreaming = this._onEndStreaming = null;
  5110. };
  5111. _proto.registerListeners = function registerListeners() {
  5112. var hls = this.hls;
  5113. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  5114. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  5115. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  5116. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  5117. hls.on(Events.BUFFER_RESET, this.onBufferReset, this);
  5118. hls.on(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  5119. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  5120. hls.on(Events.BUFFER_EOS, this.onBufferEos, this);
  5121. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  5122. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  5123. hls.on(Events.FRAG_PARSED, this.onFragParsed, this);
  5124. hls.on(Events.FRAG_CHANGED, this.onFragChanged, this);
  5125. hls.on(Events.ERROR, this.onError, this);
  5126. };
  5127. _proto.unregisterListeners = function unregisterListeners() {
  5128. var hls = this.hls;
  5129. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  5130. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  5131. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  5132. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  5133. hls.off(Events.BUFFER_RESET, this.onBufferReset, this);
  5134. hls.off(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  5135. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  5136. hls.off(Events.BUFFER_EOS, this.onBufferEos, this);
  5137. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  5138. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  5139. hls.off(Events.FRAG_PARSED, this.onFragParsed, this);
  5140. hls.off(Events.FRAG_CHANGED, this.onFragChanged, this);
  5141. hls.off(Events.ERROR, this.onError, this);
  5142. };
  5143. _proto.transferMedia = function transferMedia() {
  5144. var _this5 = this;
  5145. var media = this.media,
  5146. mediaSource = this.mediaSource;
  5147. if (!media) {
  5148. return null;
  5149. }
  5150. var tracks = {};
  5151. if (this.operationQueue) {
  5152. var updating = this.isUpdating();
  5153. if (!updating) {
  5154. this.operationQueue.removeBlockers();
  5155. }
  5156. var queued = this.isQueued();
  5157. if (updating || queued) {
  5158. this.warn("Transfering MediaSource with" + (queued ? ' operations in queue' : '') + (updating ? ' updating SourceBuffer(s)' : '') + " " + this.operationQueue);
  5159. }
  5160. this.operationQueue.destroy();
  5161. }
  5162. var transferData = this.transferData;
  5163. if (!this.sourceBufferCount && transferData && transferData.mediaSource === mediaSource) {
  5164. _extends(tracks, transferData.tracks);
  5165. } else {
  5166. this.sourceBuffers.forEach(function (tuple) {
  5167. var type = tuple[0];
  5168. if (type) {
  5169. tracks[type] = _extends({}, _this5.tracks[type]);
  5170. _this5.removeBuffer(type);
  5171. }
  5172. tuple[0] = tuple[1] = null;
  5173. });
  5174. }
  5175. return {
  5176. media: media,
  5177. mediaSource: mediaSource,
  5178. tracks: tracks
  5179. };
  5180. };
  5181. _proto.initTracks = function initTracks() {
  5182. var tracks = {};
  5183. this.sourceBuffers = [[null, null], [null, null]];
  5184. this.tracks = tracks;
  5185. this.resetQueue();
  5186. this.resetAppendErrors();
  5187. this.lastMpegAudioChunk = this.blockedAudioAppend = null;
  5188. this.lastVideoAppendEnd = 0;
  5189. };
  5190. _proto.onManifestLoading = function onManifestLoading() {
  5191. this.bufferCodecEventsTotal = 0;
  5192. this.details = null;
  5193. };
  5194. _proto.onManifestParsed = function onManifestParsed(event, data) {
  5195. var _this$transferData;
  5196. // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller
  5197. // sourcebuffers will be created all at once when the expected nb of tracks will be reached
  5198. // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller
  5199. // it will contain the expected nb of source buffers, no need to compute it
  5200. var codecEvents = 2;
  5201. if (data.audio && !data.video || !data.altAudio) {
  5202. codecEvents = 1;
  5203. }
  5204. this.bufferCodecEventsTotal = codecEvents;
  5205. this.log(codecEvents + " bufferCodec event(s) expected.");
  5206. if ((_this$transferData = this.transferData) != null && _this$transferData.mediaSource && this.sourceBufferCount && codecEvents) {
  5207. this.bufferCreated();
  5208. }
  5209. };
  5210. _proto.onMediaAttaching = function onMediaAttaching(event, data) {
  5211. var media = this.media = data.media;
  5212. var MediaSource = getMediaSource(this.appendSource);
  5213. this.transferData = this.overrides = undefined;
  5214. if (media && MediaSource) {
  5215. var transferringMedia = !!data.mediaSource;
  5216. if (transferringMedia || data.overrides) {
  5217. this.transferData = data;
  5218. this.overrides = data.overrides;
  5219. }
  5220. var ms = this.mediaSource = data.mediaSource || new MediaSource();
  5221. this.assignMediaSource(ms);
  5222. if (transferringMedia) {
  5223. this._objectUrl = media.src;
  5224. this.attachTransferred();
  5225. } else {
  5226. // cache the locally generated object url
  5227. var objectUrl = this._objectUrl = self.URL.createObjectURL(ms);
  5228. // link video and media Source
  5229. if (this.appendSource) {
  5230. try {
  5231. media.removeAttribute('src');
  5232. // ManagedMediaSource will not open without disableRemotePlayback set to false or source alternatives
  5233. var MMS = self.ManagedMediaSource;
  5234. media.disableRemotePlayback = media.disableRemotePlayback || MMS && ms instanceof MMS;
  5235. removeSourceChildren(media);
  5236. addSource(media, objectUrl);
  5237. media.load();
  5238. } catch (error) {
  5239. media.src = objectUrl;
  5240. }
  5241. } else {
  5242. media.src = objectUrl;
  5243. }
  5244. }
  5245. media.addEventListener('emptied', this._onMediaEmptied);
  5246. }
  5247. };
  5248. _proto.assignMediaSource = function assignMediaSource(ms) {
  5249. var _this$transferData2, _ms$constructor;
  5250. this.log((((_this$transferData2 = this.transferData) == null ? void 0 : _this$transferData2.mediaSource) === ms ? 'transferred' : 'created') + " media source: " + ((_ms$constructor = ms.constructor) == null ? void 0 : _ms$constructor.name));
  5251. // MediaSource listeners are arrow functions with a lexical scope, and do not need to be bound
  5252. ms.addEventListener('sourceopen', this._onMediaSourceOpen);
  5253. ms.addEventListener('sourceended', this._onMediaSourceEnded);
  5254. ms.addEventListener('sourceclose', this._onMediaSourceClose);
  5255. if (this.appendSource) {
  5256. ms.addEventListener('startstreaming', this._onStartStreaming);
  5257. ms.addEventListener('endstreaming', this._onEndStreaming);
  5258. }
  5259. };
  5260. _proto.attachTransferred = function attachTransferred() {
  5261. var _this6 = this;
  5262. var media = this.media;
  5263. var data = this.transferData;
  5264. if (!data || !media) {
  5265. return;
  5266. }
  5267. var requiredTracks = this.tracks;
  5268. var transferredTracks = data.tracks;
  5269. var trackNames = transferredTracks ? Object.keys(transferredTracks) : null;
  5270. var trackCount = trackNames ? trackNames.length : 0;
  5271. var mediaSourceOpenCallback = function mediaSourceOpenCallback() {
  5272. if (_this6.media && _this6.mediaSourceOpenOrEnded) {
  5273. _this6._onMediaSourceOpen();
  5274. }
  5275. };
  5276. if (transferredTracks && trackNames && trackCount) {
  5277. if (!this.tracksReady) {
  5278. // Wait for CODECS event(s)
  5279. this.hls.config.startFragPrefetch = true;
  5280. this.log("attachTransferred: waiting for SourceBuffer track info");
  5281. return;
  5282. }
  5283. this.log("attachTransferred: (bufferCodecEventsTotal " + this.bufferCodecEventsTotal + ")\nrequired tracks: " + stringify(requiredTracks, function (key, value) {
  5284. return key === 'initSegment' ? undefined : value;
  5285. }) + ";\ntransfer tracks: " + stringify(transferredTracks, function (key, value) {
  5286. return key === 'initSegment' ? undefined : value;
  5287. }) + "}");
  5288. if (!isCompatibleTrackChange(transferredTracks, requiredTracks)) {
  5289. // destroy attaching media source
  5290. data.mediaSource = null;
  5291. data.tracks = undefined;
  5292. var currentTime = media.currentTime;
  5293. var details = this.details;
  5294. var startTime = Math.max(currentTime, (details == null ? void 0 : details.fragments[0].start) || 0);
  5295. if (startTime - currentTime > 1) {
  5296. this.log("attachTransferred: waiting for playback to reach new tracks start time " + currentTime + " -> " + startTime);
  5297. return;
  5298. }
  5299. this.warn("attachTransferred: resetting MediaSource for incompatible tracks (\"" + Object.keys(transferredTracks) + "\"->\"" + Object.keys(requiredTracks) + "\") start time: " + startTime + " currentTime: " + currentTime);
  5300. this.onMediaDetaching(Events.MEDIA_DETACHING, {});
  5301. this.onMediaAttaching(Events.MEDIA_ATTACHING, data);
  5302. media.currentTime = startTime;
  5303. return;
  5304. }
  5305. this.transferData = undefined;
  5306. trackNames.forEach(function (trackName) {
  5307. var type = trackName;
  5308. var track = transferredTracks[type];
  5309. if (track) {
  5310. var sb = track.buffer;
  5311. if (sb) {
  5312. // Purge fragment tracker of ejected segments for existing buffer
  5313. var fragmentTracker = _this6.fragmentTracker;
  5314. var playlistType = track.id;
  5315. if (fragmentTracker.hasFragments(playlistType) || fragmentTracker.hasParts(playlistType)) {
  5316. var bufferedTimeRanges = BufferHelper.getBuffered(sb);
  5317. fragmentTracker.detectEvictedFragments(type, bufferedTimeRanges, playlistType, null, true);
  5318. }
  5319. // Transfer SourceBuffer
  5320. var sbIndex = sourceBufferNameToIndex(type);
  5321. var sbTuple = [type, sb];
  5322. _this6.sourceBuffers[sbIndex] = sbTuple;
  5323. if (sb.updating && _this6.operationQueue) {
  5324. _this6.operationQueue.prependBlocker(type);
  5325. }
  5326. _this6.trackSourceBuffer(type, track);
  5327. }
  5328. }
  5329. });
  5330. mediaSourceOpenCallback();
  5331. this.bufferCreated();
  5332. } else {
  5333. this.log("attachTransferred: MediaSource w/o SourceBuffers");
  5334. mediaSourceOpenCallback();
  5335. }
  5336. };
  5337. _proto.onMediaDetaching = function onMediaDetaching(event, data) {
  5338. var _this7 = this;
  5339. var transferringMedia = !!data.transferMedia;
  5340. this.transferData = this.overrides = undefined;
  5341. var media = this.media,
  5342. mediaSource = this.mediaSource,
  5343. _objectUrl = this._objectUrl;
  5344. if (mediaSource) {
  5345. this.log("media source " + (transferringMedia ? 'transferring' : 'detaching'));
  5346. if (transferringMedia) {
  5347. // Detach SourceBuffers without removing from MediaSource
  5348. // and leave `tracks` (required SourceBuffers configuration)
  5349. this.sourceBuffers.forEach(function (_ref) {
  5350. var type = _ref[0];
  5351. if (type) {
  5352. _this7.removeBuffer(type);
  5353. }
  5354. });
  5355. this.resetQueue();
  5356. } else {
  5357. if (this.mediaSourceOpenOrEnded) {
  5358. var open = mediaSource.readyState === 'open';
  5359. try {
  5360. var sourceBuffers = mediaSource.sourceBuffers;
  5361. for (var i = sourceBuffers.length; i--;) {
  5362. if (open) {
  5363. sourceBuffers[i].abort();
  5364. }
  5365. mediaSource.removeSourceBuffer(sourceBuffers[i]);
  5366. }
  5367. if (open) {
  5368. // endOfStream could trigger exception if any sourcebuffer is in updating state
  5369. // we don't really care about checking sourcebuffer state here,
  5370. // as we are anyway detaching the MediaSource
  5371. // let's just avoid this exception to propagate
  5372. mediaSource.endOfStream();
  5373. }
  5374. } catch (err) {
  5375. this.warn("onMediaDetaching: " + err.message + " while calling endOfStream");
  5376. }
  5377. }
  5378. // Clean up the SourceBuffers by invoking onBufferReset
  5379. if (this.sourceBufferCount) {
  5380. this.onBufferReset();
  5381. }
  5382. }
  5383. mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);
  5384. mediaSource.removeEventListener('sourceended', this._onMediaSourceEnded);
  5385. mediaSource.removeEventListener('sourceclose', this._onMediaSourceClose);
  5386. if (this.appendSource) {
  5387. mediaSource.removeEventListener('startstreaming', this._onStartStreaming);
  5388. mediaSource.removeEventListener('endstreaming', this._onEndStreaming);
  5389. }
  5390. this.mediaSource = null;
  5391. this._objectUrl = null;
  5392. }
  5393. // Detach properly the MediaSource from the HTMLMediaElement as
  5394. // suggested in https://github.com/w3c/media-source/issues/53.
  5395. if (media) {
  5396. media.removeEventListener('emptied', this._onMediaEmptied);
  5397. if (!transferringMedia) {
  5398. if (_objectUrl) {
  5399. self.URL.revokeObjectURL(_objectUrl);
  5400. }
  5401. // clean up video tag src only if it's our own url. some external libraries might
  5402. // hijack the video tag and change its 'src' without destroying the Hls instance first
  5403. if (this.mediaSrc === _objectUrl) {
  5404. media.removeAttribute('src');
  5405. if (this.appendSource) {
  5406. removeSourceChildren(media);
  5407. }
  5408. media.load();
  5409. } else {
  5410. this.warn('media|source.src was changed by a third party - skip cleanup');
  5411. }
  5412. }
  5413. this.media = null;
  5414. }
  5415. this.hls.trigger(Events.MEDIA_DETACHED, data);
  5416. };
  5417. _proto.onBufferReset = function onBufferReset() {
  5418. var _this8 = this;
  5419. this.sourceBuffers.forEach(function (_ref2) {
  5420. var type = _ref2[0];
  5421. if (type) {
  5422. _this8.resetBuffer(type);
  5423. }
  5424. });
  5425. this.initTracks();
  5426. };
  5427. _proto.resetBuffer = function resetBuffer(type) {
  5428. var _this$tracks$type;
  5429. var sb = (_this$tracks$type = this.tracks[type]) == null ? void 0 : _this$tracks$type.buffer;
  5430. this.removeBuffer(type);
  5431. if (sb) {
  5432. try {
  5433. var _this$mediaSource;
  5434. if ((_this$mediaSource = this.mediaSource) != null && _this$mediaSource.sourceBuffers.length) {
  5435. this.mediaSource.removeSourceBuffer(sb);
  5436. }
  5437. } catch (err) {
  5438. this.warn("onBufferReset " + type, err);
  5439. }
  5440. }
  5441. delete this.tracks[type];
  5442. };
  5443. _proto.removeBuffer = function removeBuffer(type) {
  5444. this.removeBufferListeners(type);
  5445. this.sourceBuffers[sourceBufferNameToIndex(type)] = [null, null];
  5446. var track = this.tracks[type];
  5447. if (track) {
  5448. track.buffer = undefined;
  5449. }
  5450. };
  5451. _proto.resetQueue = function resetQueue() {
  5452. if (this.operationQueue) {
  5453. this.operationQueue.destroy();
  5454. }
  5455. this.operationQueue = new BufferOperationQueue(this.tracks);
  5456. };
  5457. _proto.onBufferCodecs = function onBufferCodecs(event, data) {
  5458. var _this9 = this;
  5459. var tracks = this.tracks;
  5460. var trackNames = Object.keys(data);
  5461. this.log("BUFFER_CODECS: \"" + trackNames + "\" (current SB count " + this.sourceBufferCount + ")");
  5462. var unmuxedToMuxed = 'audiovideo' in data && (tracks.audio || tracks.video) || tracks.audiovideo && ('audio' in data || 'video' in data);
  5463. var muxedToUnmuxed = !unmuxedToMuxed && this.sourceBufferCount && this.media && trackNames.some(function (sbName) {
  5464. return !tracks[sbName];
  5465. });
  5466. if (unmuxedToMuxed || muxedToUnmuxed) {
  5467. this.warn("Unsupported transition between \"" + Object.keys(tracks) + "\" and \"" + trackNames + "\" SourceBuffers");
  5468. // Do not add incompatible track ('audiovideo' <-> 'video'/'audio').
  5469. // Allow following onBufferAppending handle to trigger BUFFER_APPEND_ERROR.
  5470. // This will either be resolved by level switch or could be handled with recoverMediaError().
  5471. return;
  5472. }
  5473. trackNames.forEach(function (trackName) {
  5474. var _this9$transferData, _this9$transferData$t, _trackCodec;
  5475. var parsedTrack = data[trackName];
  5476. var id = parsedTrack.id,
  5477. codec = parsedTrack.codec,
  5478. levelCodec = parsedTrack.levelCodec,
  5479. container = parsedTrack.container,
  5480. metadata = parsedTrack.metadata,
  5481. supplemental = parsedTrack.supplemental;
  5482. var track = tracks[trackName];
  5483. var transferredTrack = (_this9$transferData = _this9.transferData) == null ? void 0 : (_this9$transferData$t = _this9$transferData.tracks) == null ? void 0 : _this9$transferData$t[trackName];
  5484. var sbTrack = transferredTrack != null && transferredTrack.buffer ? transferredTrack : track;
  5485. var sbCodec = (sbTrack == null ? void 0 : sbTrack.pendingCodec) || (sbTrack == null ? void 0 : sbTrack.codec);
  5486. var trackLevelCodec = sbTrack == null ? void 0 : sbTrack.levelCodec;
  5487. if (!track) {
  5488. track = tracks[trackName] = {
  5489. buffer: undefined,
  5490. listeners: [],
  5491. codec: codec,
  5492. supplemental: supplemental,
  5493. container: container,
  5494. levelCodec: levelCodec,
  5495. metadata: metadata,
  5496. id: id
  5497. };
  5498. }
  5499. // check if SourceBuffer codec needs to change
  5500. var currentCodecFull = pickMostCompleteCodecName(sbCodec, trackLevelCodec);
  5501. var currentCodec = currentCodecFull == null ? void 0 : currentCodecFull.replace(VIDEO_CODEC_PROFILE_REPLACE, '$1');
  5502. var trackCodec = pickMostCompleteCodecName(codec, levelCodec);
  5503. var nextCodec = (_trackCodec = trackCodec) == null ? void 0 : _trackCodec.replace(VIDEO_CODEC_PROFILE_REPLACE, '$1');
  5504. if (trackCodec && currentCodecFull && currentCodec !== nextCodec) {
  5505. if (trackName.slice(0, 5) === 'audio') {
  5506. trackCodec = getCodecCompatibleName(trackCodec, _this9.appendSource);
  5507. }
  5508. _this9.log("switching codec " + sbCodec + " to " + trackCodec);
  5509. if (trackCodec !== (track.pendingCodec || track.codec)) {
  5510. track.pendingCodec = trackCodec;
  5511. }
  5512. track.container = container;
  5513. _this9.appendChangeType(trackName, container, trackCodec);
  5514. }
  5515. });
  5516. if (this.tracksReady || this.sourceBufferCount) {
  5517. data.tracks = this.sourceBufferTracks;
  5518. }
  5519. // if sourcebuffers already created, do nothing ...
  5520. if (this.sourceBufferCount) {
  5521. return;
  5522. }
  5523. if (this.mediaSourceOpenOrEnded) {
  5524. this.checkPendingTracks();
  5525. }
  5526. };
  5527. _proto.appendChangeType = function appendChangeType(type, container, codec) {
  5528. var _this0 = this;
  5529. var mimeType = container + ";codecs=" + codec;
  5530. var operation = {
  5531. label: "change-type=" + mimeType,
  5532. execute: function execute() {
  5533. var track = _this0.tracks[type];
  5534. if (track) {
  5535. var sb = track.buffer;
  5536. if (sb != null && sb.changeType) {
  5537. _this0.log("changing " + type + " sourceBuffer type to " + mimeType);
  5538. sb.changeType(mimeType);
  5539. track.codec = codec;
  5540. track.container = container;
  5541. }
  5542. }
  5543. _this0.shiftAndExecuteNext(type);
  5544. },
  5545. onStart: function onStart() {},
  5546. onComplete: function onComplete() {},
  5547. onError: function onError(error) {
  5548. _this0.warn("Failed to change " + type + " SourceBuffer type", error);
  5549. }
  5550. };
  5551. this.append(operation, type, this.isPending(this.tracks[type]));
  5552. };
  5553. _proto.blockAudio = function blockAudio(partOrFrag) {
  5554. var _this$fragmentTracker,
  5555. _this1 = this;
  5556. var pStart = partOrFrag.start;
  5557. var pTime = pStart + partOrFrag.duration * 0.05;
  5558. var atGap = ((_this$fragmentTracker = this.fragmentTracker.getAppendedFrag(pStart, PlaylistLevelType.MAIN)) == null ? void 0 : _this$fragmentTracker.gap) === true;
  5559. if (atGap) {
  5560. return;
  5561. }
  5562. var op = {
  5563. label: 'block-audio',
  5564. execute: function execute() {
  5565. var _this1$fragmentTracke;
  5566. var videoTrack = _this1.tracks.video;
  5567. if (_this1.lastVideoAppendEnd > pTime || videoTrack != null && videoTrack.buffer && BufferHelper.isBuffered(videoTrack.buffer, pTime) || ((_this1$fragmentTracke = _this1.fragmentTracker.getAppendedFrag(pTime, PlaylistLevelType.MAIN)) == null ? void 0 : _this1$fragmentTracke.gap) === true) {
  5568. _this1.blockedAudioAppend = null;
  5569. _this1.shiftAndExecuteNext('audio');
  5570. }
  5571. },
  5572. onStart: function onStart() {},
  5573. onComplete: function onComplete() {},
  5574. onError: function onError(error) {
  5575. _this1.warn('Error executing block-audio operation', error);
  5576. }
  5577. };
  5578. this.blockedAudioAppend = {
  5579. op: op,
  5580. frag: partOrFrag
  5581. };
  5582. this.append(op, 'audio', true);
  5583. };
  5584. _proto.unblockAudio = function unblockAudio() {
  5585. var blockedAudioAppend = this.blockedAudioAppend,
  5586. operationQueue = this.operationQueue;
  5587. if (blockedAudioAppend && operationQueue) {
  5588. this.blockedAudioAppend = null;
  5589. operationQueue.unblockAudio(blockedAudioAppend.op);
  5590. }
  5591. };
  5592. _proto.onBufferAppending = function onBufferAppending(event, eventData) {
  5593. var _this10 = this;
  5594. var tracks = this.tracks;
  5595. var data = eventData.data,
  5596. type = eventData.type,
  5597. parent = eventData.parent,
  5598. frag = eventData.frag,
  5599. part = eventData.part,
  5600. chunkMeta = eventData.chunkMeta,
  5601. offset = eventData.offset;
  5602. var chunkStats = chunkMeta.buffering[type];
  5603. var sn = frag.sn,
  5604. cc = frag.cc;
  5605. var bufferAppendingStart = self.performance.now();
  5606. chunkStats.start = bufferAppendingStart;
  5607. var fragBuffering = frag.stats.buffering;
  5608. var partBuffering = part ? part.stats.buffering : null;
  5609. if (fragBuffering.start === 0) {
  5610. fragBuffering.start = bufferAppendingStart;
  5611. }
  5612. if (partBuffering && partBuffering.start === 0) {
  5613. partBuffering.start = bufferAppendingStart;
  5614. }
  5615. // TODO: Only update timestampOffset when audio/mpeg fragment or part is not contiguous with previously appended
  5616. // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)
  5617. // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`
  5618. // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos).
  5619. // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486
  5620. var audioTrack = tracks.audio;
  5621. var checkTimestampOffset = false;
  5622. if (type === 'audio' && (audioTrack == null ? void 0 : audioTrack.container) === 'audio/mpeg') {
  5623. checkTimestampOffset = !this.lastMpegAudioChunk || chunkMeta.id === 1 || this.lastMpegAudioChunk.sn !== chunkMeta.sn;
  5624. this.lastMpegAudioChunk = chunkMeta;
  5625. }
  5626. // Block audio append until overlapping video append
  5627. var videoTrack = tracks.video;
  5628. var videoSb = videoTrack == null ? void 0 : videoTrack.buffer;
  5629. if (videoSb && sn !== 'initSegment') {
  5630. var partOrFrag = part || frag;
  5631. var blockedAudioAppend = this.blockedAudioAppend;
  5632. if (type === 'audio' && parent !== 'main' && !this.blockedAudioAppend) {
  5633. var pStart = partOrFrag.start;
  5634. var pTime = pStart + partOrFrag.duration * 0.05;
  5635. var vbuffered = videoSb.buffered;
  5636. var vappending = this.currentOp('video');
  5637. if (!vbuffered.length && !vappending) {
  5638. // wait for video before appending audio
  5639. this.blockAudio(partOrFrag);
  5640. } else if (!vappending && !BufferHelper.isBuffered(videoSb, pTime) && this.lastVideoAppendEnd < pTime) {
  5641. // audio is ahead of video
  5642. this.blockAudio(partOrFrag);
  5643. }
  5644. } else if (type === 'video') {
  5645. var videoAppendEnd = partOrFrag.end;
  5646. if (blockedAudioAppend) {
  5647. var audioStart = blockedAudioAppend.frag.start;
  5648. if (videoAppendEnd > audioStart || videoAppendEnd < this.lastVideoAppendEnd || BufferHelper.isBuffered(videoSb, audioStart)) {
  5649. this.unblockAudio();
  5650. }
  5651. }
  5652. this.lastVideoAppendEnd = videoAppendEnd;
  5653. }
  5654. }
  5655. var fragStart = (part || frag).start;
  5656. var operation = {
  5657. label: "append-" + type,
  5658. execute: function execute() {
  5659. var _this10$tracks$type;
  5660. chunkStats.executeStart = self.performance.now();
  5661. var sb = (_this10$tracks$type = _this10.tracks[type]) == null ? void 0 : _this10$tracks$type.buffer;
  5662. if (sb) {
  5663. if (checkTimestampOffset) {
  5664. _this10.updateTimestampOffset(sb, fragStart, 0.1, type, sn, cc);
  5665. } else if (offset !== undefined && isFiniteNumber(offset)) {
  5666. _this10.updateTimestampOffset(sb, offset, 0.000001, type, sn, cc);
  5667. }
  5668. }
  5669. _this10.appendExecutor(data, type);
  5670. },
  5671. onStart: function onStart() {
  5672. // logger.debug(`[buffer-controller]: ${type} SourceBuffer updatestart`);
  5673. },
  5674. onComplete: function onComplete() {
  5675. // logger.debug(`[buffer-controller]: ${type} SourceBuffer updateend`);
  5676. var end = self.performance.now();
  5677. chunkStats.executeEnd = chunkStats.end = end;
  5678. if (fragBuffering.first === 0) {
  5679. fragBuffering.first = end;
  5680. }
  5681. if (partBuffering && partBuffering.first === 0) {
  5682. partBuffering.first = end;
  5683. }
  5684. var timeRanges = {};
  5685. _this10.sourceBuffers.forEach(function (_ref3) {
  5686. var type = _ref3[0],
  5687. sb = _ref3[1];
  5688. if (type) {
  5689. timeRanges[type] = BufferHelper.getBuffered(sb);
  5690. }
  5691. });
  5692. _this10.appendErrors[type] = 0;
  5693. if (type === 'audio' || type === 'video') {
  5694. _this10.appendErrors.audiovideo = 0;
  5695. } else {
  5696. _this10.appendErrors.audio = 0;
  5697. _this10.appendErrors.video = 0;
  5698. }
  5699. _this10.hls.trigger(Events.BUFFER_APPENDED, {
  5700. type: type,
  5701. frag: frag,
  5702. part: part,
  5703. chunkMeta: chunkMeta,
  5704. parent: frag.type,
  5705. timeRanges: timeRanges
  5706. });
  5707. },
  5708. onError: function onError(error) {
  5709. var _this10$media;
  5710. // in case any error occured while appending, put back segment in segments table
  5711. var event = {
  5712. type: ErrorTypes.MEDIA_ERROR,
  5713. parent: frag.type,
  5714. details: ErrorDetails.BUFFER_APPEND_ERROR,
  5715. sourceBufferName: type,
  5716. frag: frag,
  5717. part: part,
  5718. chunkMeta: chunkMeta,
  5719. error: error,
  5720. err: error,
  5721. fatal: false
  5722. };
  5723. var mediaError = (_this10$media = _this10.media) == null ? void 0 : _this10$media.error;
  5724. if (error.code === DOMException.QUOTA_EXCEEDED_ERR || error.name == 'QuotaExceededError' || "quota" in error) {
  5725. // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
  5726. // let's stop appending any segments, and report BUFFER_FULL_ERROR error
  5727. event.details = ErrorDetails.BUFFER_FULL_ERROR;
  5728. } else if (error.code === DOMException.INVALID_STATE_ERR && _this10.mediaSourceOpenOrEnded && !mediaError) {
  5729. // Allow retry for "Failed to execute 'appendBuffer' on 'SourceBuffer': This SourceBuffer is still processing" errors
  5730. event.errorAction = createDoNothingErrorAction(true);
  5731. } else if (error.name === TRACK_REMOVED_ERROR_NAME && _this10.sourceBufferCount === 0) {
  5732. // Do nothing if sourceBuffers were removed (media is detached and append was not aborted)
  5733. event.errorAction = createDoNothingErrorAction(true);
  5734. } else {
  5735. var appendErrorCount = ++_this10.appendErrors[type];
  5736. /* with UHD content, we could get loop of quota exceeded error until
  5737. browser is able to evict some data from sourcebuffer. Retrying can help recover.
  5738. */
  5739. _this10.warn("Failed " + appendErrorCount + "/" + _this10.hls.config.appendErrorMaxRetry + " times to append segment in \"" + type + "\" sourceBuffer (" + (mediaError ? mediaError : 'no media error') + ")");
  5740. if (appendErrorCount >= _this10.hls.config.appendErrorMaxRetry || !!mediaError) {
  5741. event.fatal = true;
  5742. }
  5743. }
  5744. _this10.hls.trigger(Events.ERROR, event);
  5745. }
  5746. };
  5747. this.append(operation, type, this.isPending(this.tracks[type]));
  5748. };
  5749. _proto.getFlushOp = function getFlushOp(type, start, end) {
  5750. var _this11 = this;
  5751. this.log("queuing \"" + type + "\" remove " + start + "-" + end);
  5752. return {
  5753. label: 'remove',
  5754. execute: function execute() {
  5755. _this11.removeExecutor(type, start, end);
  5756. },
  5757. onStart: function onStart() {
  5758. // logger.debug(`[buffer-controller]: Started flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
  5759. },
  5760. onComplete: function onComplete() {
  5761. // logger.debug(`[buffer-controller]: Finished flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
  5762. _this11.hls.trigger(Events.BUFFER_FLUSHED, {
  5763. type: type
  5764. });
  5765. },
  5766. onError: function onError(error) {
  5767. _this11.warn("Failed to remove " + start + "-" + end + " from \"" + type + "\" SourceBuffer", error);
  5768. }
  5769. };
  5770. };
  5771. _proto.onBufferFlushing = function onBufferFlushing(event, data) {
  5772. var _this12 = this;
  5773. var type = data.type,
  5774. startOffset = data.startOffset,
  5775. endOffset = data.endOffset;
  5776. if (type) {
  5777. this.append(this.getFlushOp(type, startOffset, endOffset), type);
  5778. } else {
  5779. this.sourceBuffers.forEach(function (_ref4) {
  5780. var type = _ref4[0];
  5781. if (type) {
  5782. _this12.append(_this12.getFlushOp(type, startOffset, endOffset), type);
  5783. }
  5784. });
  5785. }
  5786. };
  5787. _proto.onFragParsed = function onFragParsed(event, data) {
  5788. var _this13 = this;
  5789. var frag = data.frag,
  5790. part = data.part;
  5791. var buffersAppendedTo = [];
  5792. var elementaryStreams = part ? part.elementaryStreams : frag.elementaryStreams;
  5793. if (elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO]) {
  5794. buffersAppendedTo.push('audiovideo');
  5795. } else {
  5796. if (elementaryStreams[ElementaryStreamTypes.AUDIO]) {
  5797. buffersAppendedTo.push('audio');
  5798. }
  5799. if (elementaryStreams[ElementaryStreamTypes.VIDEO]) {
  5800. buffersAppendedTo.push('video');
  5801. }
  5802. }
  5803. var onUnblocked = function onUnblocked() {
  5804. var now = self.performance.now();
  5805. frag.stats.buffering.end = now;
  5806. if (part) {
  5807. part.stats.buffering.end = now;
  5808. }
  5809. var stats = part ? part.stats : frag.stats;
  5810. _this13.hls.trigger(Events.FRAG_BUFFERED, {
  5811. frag: frag,
  5812. part: part,
  5813. stats: stats,
  5814. id: frag.type
  5815. });
  5816. };
  5817. if (buffersAppendedTo.length === 0) {
  5818. this.warn("Fragments must have at least one ElementaryStreamType set. type: " + frag.type + " level: " + frag.level + " sn: " + frag.sn);
  5819. }
  5820. this.blockBuffers(onUnblocked, buffersAppendedTo).catch(function (error) {
  5821. _this13.warn("Fragment buffered callback " + error);
  5822. _this13.stepOperationQueue(_this13.sourceBufferTypes);
  5823. });
  5824. };
  5825. _proto.onFragChanged = function onFragChanged(event, data) {
  5826. this.trimBuffers();
  5827. };
  5828. // on BUFFER_EOS mark matching sourcebuffer(s) as "ending" and "ended" and queue endOfStream after remaining operations(s)
  5829. // an undefined data.type will mark all buffers as EOS.
  5830. _proto.onBufferEos = function onBufferEos(event, data) {
  5831. var _this14 = this,
  5832. _this$overrides;
  5833. this.sourceBuffers.forEach(function (_ref5) {
  5834. var type = _ref5[0];
  5835. if (type) {
  5836. var track = _this14.tracks[type];
  5837. if (!data.type || data.type === type) {
  5838. track.ending = true;
  5839. if (!track.ended) {
  5840. track.ended = true;
  5841. _this14.log(type + " buffer reached EOS");
  5842. }
  5843. }
  5844. }
  5845. });
  5846. var allowEndOfStream = ((_this$overrides = this.overrides) == null ? void 0 : _this$overrides.endOfStream) !== false;
  5847. var allTracksEnding = this.sourceBufferCount > 0 && !this.sourceBuffers.some(function (_ref6) {
  5848. var _this14$tracks$type;
  5849. var type = _ref6[0];
  5850. return type && !((_this14$tracks$type = _this14.tracks[type]) != null && _this14$tracks$type.ended);
  5851. });
  5852. if (allTracksEnding) {
  5853. if (allowEndOfStream) {
  5854. this.log("Queueing EOS");
  5855. this.blockUntilOpen(function () {
  5856. _this14.tracksEnded();
  5857. var mediaSource = _this14.mediaSource;
  5858. if (!mediaSource || mediaSource.readyState !== 'open') {
  5859. if (mediaSource) {
  5860. _this14.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: " + mediaSource.readyState);
  5861. }
  5862. return;
  5863. }
  5864. _this14.log("Calling mediaSource.endOfStream()");
  5865. // Allow this to throw and be caught by the enqueueing function
  5866. mediaSource.endOfStream();
  5867. _this14.hls.trigger(Events.BUFFERED_TO_END, undefined);
  5868. });
  5869. } else {
  5870. this.tracksEnded();
  5871. this.hls.trigger(Events.BUFFERED_TO_END, undefined);
  5872. }
  5873. }
  5874. };
  5875. _proto.tracksEnded = function tracksEnded() {
  5876. var _this15 = this;
  5877. this.sourceBuffers.forEach(function (_ref7) {
  5878. var type = _ref7[0];
  5879. if (type !== null) {
  5880. var track = _this15.tracks[type];
  5881. if (track) {
  5882. track.ending = false;
  5883. }
  5884. }
  5885. });
  5886. };
  5887. _proto.onLevelUpdated = function onLevelUpdated(event, _ref8) {
  5888. var details = _ref8.details;
  5889. if (!details.fragments.length) {
  5890. return;
  5891. }
  5892. this.details = details;
  5893. this.updateDuration();
  5894. };
  5895. _proto.updateDuration = function updateDuration() {
  5896. var _this16 = this;
  5897. this.blockUntilOpen(function () {
  5898. var durationAndRange = _this16.getDurationAndRange();
  5899. if (!durationAndRange) {
  5900. return;
  5901. }
  5902. _this16.updateMediaSource(durationAndRange);
  5903. });
  5904. };
  5905. _proto.onError = function onError(event, data) {
  5906. if (data.details === ErrorDetails.BUFFER_APPEND_ERROR && data.frag) {
  5907. var _data$errorAction;
  5908. var nextAutoLevel = (_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.nextAutoLevel;
  5909. if (isFiniteNumber(nextAutoLevel) && nextAutoLevel !== data.frag.level) {
  5910. this.resetAppendErrors();
  5911. }
  5912. }
  5913. };
  5914. _proto.resetAppendErrors = function resetAppendErrors() {
  5915. this.appendErrors = {
  5916. audio: 0,
  5917. video: 0,
  5918. audiovideo: 0
  5919. };
  5920. };
  5921. _proto.trimBuffers = function trimBuffers() {
  5922. var hls = this.hls,
  5923. details = this.details,
  5924. media = this.media;
  5925. if (!media || details === null) {
  5926. return;
  5927. }
  5928. if (!this.sourceBufferCount) {
  5929. return;
  5930. }
  5931. var config = hls.config;
  5932. var currentTime = media.currentTime;
  5933. var targetDuration = details.levelTargetDuration;
  5934. // Support for deprecated liveBackBufferLength
  5935. var backBufferLength = details.live && config.liveBackBufferLength !== null ? config.liveBackBufferLength : config.backBufferLength;
  5936. if (isFiniteNumber(backBufferLength) && backBufferLength >= 0) {
  5937. var maxBackBufferLength = Math.max(backBufferLength, targetDuration);
  5938. var targetBackBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration - maxBackBufferLength;
  5939. this.flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition);
  5940. }
  5941. if (isFiniteNumber(config.frontBufferFlushThreshold) && config.frontBufferFlushThreshold > 0) {
  5942. var frontBufferLength = Math.max(config.maxBufferLength, config.frontBufferFlushThreshold);
  5943. var maxFrontBufferLength = Math.max(frontBufferLength, targetDuration);
  5944. var targetFrontBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration + maxFrontBufferLength;
  5945. this.flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition);
  5946. }
  5947. };
  5948. _proto.flushBackBuffer = function flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition) {
  5949. var _this17 = this;
  5950. this.sourceBuffers.forEach(function (_ref9) {
  5951. var type = _ref9[0],
  5952. sb = _ref9[1];
  5953. if (sb) {
  5954. var buffered = BufferHelper.getBuffered(sb);
  5955. // when target buffer start exceeds actual buffer start
  5956. if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
  5957. var _this17$details;
  5958. _this17.hls.trigger(Events.BACK_BUFFER_REACHED, {
  5959. bufferEnd: targetBackBufferPosition
  5960. });
  5961. // Support for deprecated event:
  5962. var track = _this17.tracks[type];
  5963. if ((_this17$details = _this17.details) != null && _this17$details.live) {
  5964. _this17.hls.trigger(Events.LIVE_BACK_BUFFER_REACHED, {
  5965. bufferEnd: targetBackBufferPosition
  5966. });
  5967. } else if (track != null && track.ended) {
  5968. _this17.log("Cannot flush " + type + " back buffer while SourceBuffer is in ended state");
  5969. return;
  5970. }
  5971. _this17.hls.trigger(Events.BUFFER_FLUSHING, {
  5972. startOffset: 0,
  5973. endOffset: targetBackBufferPosition,
  5974. type: type
  5975. });
  5976. }
  5977. }
  5978. });
  5979. };
  5980. _proto.flushFrontBuffer = function flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition) {
  5981. var _this18 = this;
  5982. this.sourceBuffers.forEach(function (_ref0) {
  5983. var type = _ref0[0],
  5984. sb = _ref0[1];
  5985. if (sb) {
  5986. var buffered = BufferHelper.getBuffered(sb);
  5987. var numBufferedRanges = buffered.length;
  5988. // The buffer is either empty or contiguous
  5989. if (numBufferedRanges < 2) {
  5990. return;
  5991. }
  5992. var bufferStart = buffered.start(numBufferedRanges - 1);
  5993. var bufferEnd = buffered.end(numBufferedRanges - 1);
  5994. // No flush if we can tolerate the current buffer length or the current buffer range we would flush is contiguous with current position
  5995. if (targetFrontBufferPosition > bufferStart || currentTime >= bufferStart && currentTime <= bufferEnd) {
  5996. return;
  5997. }
  5998. _this18.hls.trigger(Events.BUFFER_FLUSHING, {
  5999. startOffset: bufferStart,
  6000. endOffset: Infinity,
  6001. type: type
  6002. });
  6003. }
  6004. });
  6005. }
  6006. /**
  6007. * Update Media Source duration to current level duration or override to Infinity if configuration parameter
  6008. * 'liveDurationInfinity` is set to `true`
  6009. * More details: https://github.com/video-dev/hls.js/issues/355
  6010. */;
  6011. _proto.getDurationAndRange = function getDurationAndRange() {
  6012. var _this$overrides2;
  6013. var details = this.details,
  6014. mediaSource = this.mediaSource;
  6015. if (!details || !this.media || (mediaSource == null ? void 0 : mediaSource.readyState) !== 'open') {
  6016. return null;
  6017. }
  6018. var playlistEnd = details.edge;
  6019. if (details.live && this.hls.config.liveDurationInfinity) {
  6020. var len = details.fragments.length;
  6021. if (len && details.live && !!mediaSource.setLiveSeekableRange) {
  6022. var start = Math.max(0, details.fragmentStart);
  6023. var end = Math.max(start, playlistEnd);
  6024. return {
  6025. duration: Infinity,
  6026. start: start,
  6027. end: end
  6028. };
  6029. }
  6030. return {
  6031. duration: Infinity
  6032. };
  6033. }
  6034. var overrideDuration = (_this$overrides2 = this.overrides) == null ? void 0 : _this$overrides2.duration;
  6035. if (overrideDuration) {
  6036. if (!isFiniteNumber(overrideDuration)) {
  6037. return null;
  6038. }
  6039. return {
  6040. duration: overrideDuration
  6041. };
  6042. }
  6043. var mediaDuration = this.media.duration;
  6044. var msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : 0;
  6045. if (playlistEnd > msDuration && playlistEnd > mediaDuration || !isFiniteNumber(mediaDuration)) {
  6046. return {
  6047. duration: playlistEnd
  6048. };
  6049. }
  6050. return null;
  6051. };
  6052. _proto.updateMediaSource = function updateMediaSource(_ref1) {
  6053. var duration = _ref1.duration,
  6054. start = _ref1.start,
  6055. end = _ref1.end;
  6056. var mediaSource = this.mediaSource;
  6057. if (!this.media || !mediaSource || mediaSource.readyState !== 'open') {
  6058. return;
  6059. }
  6060. if (mediaSource.duration !== duration) {
  6061. if (isFiniteNumber(duration)) {
  6062. this.log("Updating MediaSource duration to " + duration.toFixed(3));
  6063. }
  6064. mediaSource.duration = duration;
  6065. }
  6066. if (start !== undefined && end !== undefined) {
  6067. this.log("MediaSource duration is set to " + mediaSource.duration + ". Setting seekable range to " + start + "-" + end + ".");
  6068. mediaSource.setLiveSeekableRange(start, end);
  6069. }
  6070. };
  6071. _proto.checkPendingTracks = function checkPendingTracks() {
  6072. var bufferCodecEventsTotal = this.bufferCodecEventsTotal,
  6073. pendingTrackCount = this.pendingTrackCount,
  6074. tracks = this.tracks;
  6075. this.log("checkPendingTracks (pending: " + pendingTrackCount + " codec events expected: " + bufferCodecEventsTotal + ") " + stringify(tracks));
  6076. // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.
  6077. // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after
  6078. // data has been appended to existing ones.
  6079. // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.
  6080. if (this.tracksReady) {
  6081. var _this$transferData3;
  6082. var transferredTracks = (_this$transferData3 = this.transferData) == null ? void 0 : _this$transferData3.tracks;
  6083. if (transferredTracks && Object.keys(transferredTracks).length) {
  6084. this.attachTransferred();
  6085. } else {
  6086. // ok, let's create them now !
  6087. this.createSourceBuffers();
  6088. }
  6089. }
  6090. };
  6091. _proto.bufferCreated = function bufferCreated() {
  6092. var _this19 = this;
  6093. if (this.sourceBufferCount) {
  6094. var tracks = {};
  6095. this.sourceBuffers.forEach(function (_ref10) {
  6096. var type = _ref10[0],
  6097. buffer = _ref10[1];
  6098. if (type) {
  6099. var track = _this19.tracks[type];
  6100. tracks[type] = {
  6101. buffer: buffer,
  6102. container: track.container,
  6103. codec: track.codec,
  6104. supplemental: track.supplemental,
  6105. levelCodec: track.levelCodec,
  6106. id: track.id,
  6107. metadata: track.metadata
  6108. };
  6109. }
  6110. });
  6111. this.hls.trigger(Events.BUFFER_CREATED, {
  6112. tracks: tracks
  6113. });
  6114. this.log("SourceBuffers created. Running queue: " + this.operationQueue);
  6115. this.sourceBuffers.forEach(function (_ref11) {
  6116. var type = _ref11[0];
  6117. _this19.executeNext(type);
  6118. });
  6119. } else {
  6120. var error = new Error('could not create source buffer for media codec(s)');
  6121. this.hls.trigger(Events.ERROR, {
  6122. type: ErrorTypes.MEDIA_ERROR,
  6123. details: ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,
  6124. fatal: true,
  6125. error: error,
  6126. reason: error.message
  6127. });
  6128. }
  6129. };
  6130. _proto.createSourceBuffers = function createSourceBuffers() {
  6131. var tracks = this.tracks,
  6132. sourceBuffers = this.sourceBuffers,
  6133. mediaSource = this.mediaSource;
  6134. if (!mediaSource) {
  6135. throw new Error('createSourceBuffers called when mediaSource was null');
  6136. }
  6137. for (var trackName in tracks) {
  6138. var type = trackName;
  6139. var track = tracks[type];
  6140. if (this.isPending(track)) {
  6141. var codec = this.getTrackCodec(track, type);
  6142. var mimeType = track.container + ";codecs=" + codec;
  6143. track.codec = codec;
  6144. this.log("creating sourceBuffer(" + mimeType + ")" + (this.currentOp(type) ? ' Queued' : '') + " " + stringify(track));
  6145. try {
  6146. var sb = mediaSource.addSourceBuffer(mimeType);
  6147. var sbIndex = sourceBufferNameToIndex(type);
  6148. var sbTuple = [type, sb];
  6149. sourceBuffers[sbIndex] = sbTuple;
  6150. track.buffer = sb;
  6151. } catch (error) {
  6152. var _this$operationQueue;
  6153. this.error("error while trying to add sourceBuffer: " + error.message);
  6154. // remove init segment from queue and delete track info
  6155. this.shiftAndExecuteNext(type);
  6156. (_this$operationQueue = this.operationQueue) == null ? void 0 : _this$operationQueue.removeBlockers();
  6157. delete this.tracks[type];
  6158. this.hls.trigger(Events.ERROR, {
  6159. type: ErrorTypes.MEDIA_ERROR,
  6160. details: ErrorDetails.BUFFER_ADD_CODEC_ERROR,
  6161. fatal: false,
  6162. error: error,
  6163. sourceBufferName: type,
  6164. mimeType: mimeType,
  6165. parent: track.id
  6166. });
  6167. return;
  6168. }
  6169. this.trackSourceBuffer(type, track);
  6170. }
  6171. }
  6172. this.bufferCreated();
  6173. };
  6174. _proto.getTrackCodec = function getTrackCodec(track, trackName) {
  6175. // Use supplemental video codec when supported when adding SourceBuffer (#5558)
  6176. var supplementalCodec = track.supplemental;
  6177. var trackCodec = track.codec;
  6178. if (supplementalCodec && (trackName === 'video' || trackName === 'audiovideo') && areCodecsMediaSourceSupported(supplementalCodec, 'video')) {
  6179. trackCodec = replaceVideoCodec(trackCodec, supplementalCodec);
  6180. }
  6181. var codec = pickMostCompleteCodecName(trackCodec, track.levelCodec);
  6182. if (codec) {
  6183. if (trackName.slice(0, 5) === 'audio') {
  6184. return getCodecCompatibleName(codec, this.appendSource);
  6185. }
  6186. return codec;
  6187. }
  6188. return '';
  6189. };
  6190. _proto.trackSourceBuffer = function trackSourceBuffer(type, track) {
  6191. var _this20 = this;
  6192. var buffer = track.buffer;
  6193. if (!buffer) {
  6194. return;
  6195. }
  6196. var codec = this.getTrackCodec(track, type);
  6197. this.tracks[type] = {
  6198. buffer: buffer,
  6199. codec: codec,
  6200. container: track.container,
  6201. levelCodec: track.levelCodec,
  6202. supplemental: track.supplemental,
  6203. metadata: track.metadata,
  6204. id: track.id,
  6205. listeners: []
  6206. };
  6207. this.removeBufferListeners(type);
  6208. this.addBufferListener(type, 'updatestart', this.onSBUpdateStart);
  6209. this.addBufferListener(type, 'updateend', this.onSBUpdateEnd);
  6210. this.addBufferListener(type, 'error', this.onSBUpdateError);
  6211. // ManagedSourceBuffer bufferedchange event
  6212. if (this.appendSource) {
  6213. this.addBufferListener(type, 'bufferedchange', function (type, event) {
  6214. // If media was ejected check for a change. Added ranges are redundant with changes on 'updateend' event.
  6215. var removedRanges = event.removedRanges;
  6216. if (removedRanges != null && removedRanges.length) {
  6217. _this20.hls.trigger(Events.BUFFER_FLUSHED, {
  6218. type: type
  6219. });
  6220. }
  6221. });
  6222. }
  6223. };
  6224. _proto.onSBUpdateStart = function onSBUpdateStart(type) {
  6225. var operation = this.currentOp(type);
  6226. if (!operation) {
  6227. return;
  6228. }
  6229. operation.onStart();
  6230. };
  6231. _proto.onSBUpdateEnd = function onSBUpdateEnd(type) {
  6232. var _this$mediaSource2;
  6233. if (((_this$mediaSource2 = this.mediaSource) == null ? void 0 : _this$mediaSource2.readyState) === 'closed') {
  6234. this.resetBuffer(type);
  6235. return;
  6236. }
  6237. var operation = this.currentOp(type);
  6238. if (!operation) {
  6239. return;
  6240. }
  6241. operation.onComplete();
  6242. this.shiftAndExecuteNext(type);
  6243. };
  6244. _proto.onSBUpdateError = function onSBUpdateError(type, event) {
  6245. var _this$mediaSource3;
  6246. var error = new Error(type + " SourceBuffer error. MediaSource readyState: " + ((_this$mediaSource3 = this.mediaSource) == null ? void 0 : _this$mediaSource3.readyState));
  6247. this.error("" + error, event);
  6248. // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
  6249. // SourceBuffer errors are not necessarily fatal; if so, the HTMLMediaElement will fire an error event
  6250. this.hls.trigger(Events.ERROR, {
  6251. type: ErrorTypes.MEDIA_ERROR,
  6252. details: ErrorDetails.BUFFER_APPENDING_ERROR,
  6253. sourceBufferName: type,
  6254. error: error,
  6255. fatal: false
  6256. });
  6257. // updateend is always fired after error, so we'll allow that to shift the current operation off of the queue
  6258. var operation = this.currentOp(type);
  6259. if (operation) {
  6260. operation.onError(error);
  6261. }
  6262. };
  6263. _proto.updateTimestampOffset = function updateTimestampOffset(sb, timestampOffset, tolerance, type, sn, cc) {
  6264. var delta = timestampOffset - sb.timestampOffset;
  6265. if (Math.abs(delta) >= tolerance) {
  6266. this.log("Updating " + type + " SourceBuffer timestampOffset to " + timestampOffset + " (sn: " + sn + " cc: " + cc + ")");
  6267. sb.timestampOffset = timestampOffset;
  6268. }
  6269. }
  6270. // This method must result in an updateend event; if remove is not called, onSBUpdateEnd must be called manually
  6271. ;
  6272. _proto.removeExecutor = function removeExecutor(type, startOffset, endOffset) {
  6273. var media = this.media,
  6274. mediaSource = this.mediaSource;
  6275. var track = this.tracks[type];
  6276. var sb = track == null ? void 0 : track.buffer;
  6277. if (!media || !mediaSource || !sb) {
  6278. this.warn("Attempting to remove from the " + type + " SourceBuffer, but it does not exist");
  6279. this.shiftAndExecuteNext(type);
  6280. return;
  6281. }
  6282. var mediaDuration = isFiniteNumber(media.duration) ? media.duration : Infinity;
  6283. var msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : Infinity;
  6284. var removeStart = Math.max(0, startOffset);
  6285. var removeEnd = Math.min(endOffset, mediaDuration, msDuration);
  6286. if (removeEnd > removeStart && (!track.ending || track.ended)) {
  6287. track.ended = false;
  6288. this.log("Removing [" + removeStart + "," + removeEnd + "] from the " + type + " SourceBuffer");
  6289. sb.remove(removeStart, removeEnd);
  6290. } else {
  6291. // Cycle the queue
  6292. this.shiftAndExecuteNext(type);
  6293. }
  6294. }
  6295. // This method must result in an updateend event; if append is not called, onSBUpdateEnd must be called manually
  6296. ;
  6297. _proto.appendExecutor = function appendExecutor(data, type) {
  6298. var track = this.tracks[type];
  6299. var sb = track == null ? void 0 : track.buffer;
  6300. if (!sb) {
  6301. throw new HlsJsTrackRemovedError("Attempting to append to the " + type + " SourceBuffer, but it does not exist");
  6302. }
  6303. track.ending = false;
  6304. track.ended = false;
  6305. sb.appendBuffer(data);
  6306. };
  6307. _proto.blockUntilOpen = function blockUntilOpen(callback) {
  6308. var _this21 = this;
  6309. if (this.isUpdating() || this.isQueued()) {
  6310. this.blockBuffers(callback).catch(function (error) {
  6311. _this21.warn("SourceBuffer blocked callback " + error);
  6312. _this21.stepOperationQueue(_this21.sourceBufferTypes);
  6313. });
  6314. } else {
  6315. try {
  6316. callback();
  6317. } catch (error) {
  6318. this.warn("Callback run without blocking " + this.operationQueue + " " + error);
  6319. }
  6320. }
  6321. };
  6322. _proto.isUpdating = function isUpdating() {
  6323. return this.sourceBuffers.some(function (_ref12) {
  6324. var type = _ref12[0],
  6325. sb = _ref12[1];
  6326. return type && sb.updating;
  6327. });
  6328. };
  6329. _proto.isQueued = function isQueued() {
  6330. var _this22 = this;
  6331. return this.sourceBuffers.some(function (_ref13) {
  6332. var type = _ref13[0];
  6333. return type && !!_this22.currentOp(type);
  6334. });
  6335. };
  6336. _proto.isPending = function isPending(track) {
  6337. return !!track && !track.buffer;
  6338. }
  6339. // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises
  6340. // resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue
  6341. // upon completion, since we already do it here
  6342. ;
  6343. _proto.blockBuffers = function blockBuffers(onUnblocked, bufferNames) {
  6344. var _this23 = this;
  6345. if (bufferNames === void 0) {
  6346. bufferNames = this.sourceBufferTypes;
  6347. }
  6348. if (!bufferNames.length) {
  6349. this.log('Blocking operation requested, but no SourceBuffers exist');
  6350. return Promise.resolve().then(onUnblocked);
  6351. }
  6352. var operationQueue = this.operationQueue;
  6353. // logger.debug(`[buffer-controller]: Blocking ${buffers} SourceBuffer`);
  6354. var blockingOperations = bufferNames.map(function (type) {
  6355. return _this23.appendBlocker(type);
  6356. });
  6357. var audioBlocked = bufferNames.length > 1 && !!this.blockedAudioAppend;
  6358. if (audioBlocked) {
  6359. this.unblockAudio();
  6360. }
  6361. return Promise.all(blockingOperations).then(function (result) {
  6362. if (operationQueue !== _this23.operationQueue) {
  6363. return;
  6364. }
  6365. // logger.debug(`[buffer-controller]: Blocking operation resolved; unblocking ${buffers} SourceBuffer`);
  6366. onUnblocked();
  6367. _this23.stepOperationQueue(_this23.sourceBufferTypes);
  6368. });
  6369. };
  6370. _proto.stepOperationQueue = function stepOperationQueue(bufferNames) {
  6371. var _this24 = this;
  6372. bufferNames.forEach(function (type) {
  6373. var _this24$tracks$type;
  6374. var sb = (_this24$tracks$type = _this24.tracks[type]) == null ? void 0 : _this24$tracks$type.buffer;
  6375. // Only cycle the queue if the SB is not updating. There's a bug in Chrome which sets the SB updating flag to
  6376. // true when changing the MediaSource duration (https://bugs.chromium.org/p/chromium/issues/detail?id=959359&can=2&q=mediasource%20duration)
  6377. // While this is a workaround, it's probably useful to have around
  6378. if (!sb || sb.updating) {
  6379. return;
  6380. }
  6381. _this24.shiftAndExecuteNext(type);
  6382. });
  6383. };
  6384. _proto.append = function append(operation, type, pending) {
  6385. if (this.operationQueue) {
  6386. this.operationQueue.append(operation, type, pending);
  6387. }
  6388. };
  6389. _proto.appendBlocker = function appendBlocker(type) {
  6390. if (this.operationQueue) {
  6391. return this.operationQueue.appendBlocker(type);
  6392. }
  6393. };
  6394. _proto.currentOp = function currentOp(type) {
  6395. if (this.operationQueue) {
  6396. return this.operationQueue.current(type);
  6397. }
  6398. return null;
  6399. };
  6400. _proto.executeNext = function executeNext(type) {
  6401. if (type && this.operationQueue) {
  6402. this.operationQueue.executeNext(type);
  6403. }
  6404. };
  6405. _proto.shiftAndExecuteNext = function shiftAndExecuteNext(type) {
  6406. if (this.operationQueue) {
  6407. this.operationQueue.shiftAndExecuteNext(type);
  6408. }
  6409. };
  6410. _proto.addBufferListener = function addBufferListener(type, event, fn) {
  6411. var track = this.tracks[type];
  6412. if (!track) {
  6413. return;
  6414. }
  6415. var buffer = track.buffer;
  6416. if (!buffer) {
  6417. return;
  6418. }
  6419. var listener = fn.bind(this, type);
  6420. track.listeners.push({
  6421. event: event,
  6422. listener: listener
  6423. });
  6424. buffer.addEventListener(event, listener);
  6425. };
  6426. _proto.removeBufferListeners = function removeBufferListeners(type) {
  6427. var track = this.tracks[type];
  6428. if (!track) {
  6429. return;
  6430. }
  6431. var buffer = track.buffer;
  6432. if (!buffer) {
  6433. return;
  6434. }
  6435. track.listeners.forEach(function (l) {
  6436. buffer.removeEventListener(l.event, l.listener);
  6437. });
  6438. track.listeners.length = 0;
  6439. };
  6440. return _createClass(BufferController, [{
  6441. key: "mediaSourceOpenOrEnded",
  6442. get: function get() {
  6443. var _this$mediaSource4;
  6444. var readyState = (_this$mediaSource4 = this.mediaSource) == null ? void 0 : _this$mediaSource4.readyState;
  6445. return readyState === 'open' || readyState === 'ended';
  6446. }
  6447. }, {
  6448. key: "sourceBufferTracks",
  6449. get: function get() {
  6450. var _this25 = this;
  6451. return Object.keys(this.tracks).reduce(function (baseTracks, type) {
  6452. var track = _this25.tracks[type];
  6453. baseTracks[type] = {
  6454. id: track.id,
  6455. container: track.container,
  6456. codec: track.codec,
  6457. levelCodec: track.levelCodec
  6458. };
  6459. return baseTracks;
  6460. }, {});
  6461. }
  6462. }, {
  6463. key: "bufferedToEnd",
  6464. get: function get() {
  6465. var _this26 = this;
  6466. return this.sourceBufferCount > 0 && !this.sourceBuffers.some(function (_ref14) {
  6467. var _this26$tracks$type, _this26$tracks$type2;
  6468. var type = _ref14[0];
  6469. return type && (!((_this26$tracks$type = _this26.tracks[type]) != null && _this26$tracks$type.ended) || ((_this26$tracks$type2 = _this26.tracks[type]) == null ? void 0 : _this26$tracks$type2.ending));
  6470. });
  6471. }
  6472. }, {
  6473. key: "tracksReady",
  6474. get: function get() {
  6475. var pendingTrackCount = this.pendingTrackCount;
  6476. return pendingTrackCount > 0 && (pendingTrackCount >= this.bufferCodecEventsTotal || this.isPending(this.tracks.audiovideo));
  6477. }
  6478. }, {
  6479. key: "mediaSrc",
  6480. get: function get() {
  6481. var _this$media, _this$media$querySele;
  6482. var media = ((_this$media = this.media) == null ? void 0 : (_this$media$querySele = _this$media.querySelector) == null ? void 0 : _this$media$querySele.call(_this$media, 'source')) || this.media;
  6483. return media == null ? void 0 : media.src;
  6484. }
  6485. }, {
  6486. key: "pendingTrackCount",
  6487. get: function get() {
  6488. var _this27 = this;
  6489. return Object.keys(this.tracks).reduce(function (acc, type) {
  6490. return acc + (_this27.isPending(_this27.tracks[type]) ? 1 : 0);
  6491. }, 0);
  6492. }
  6493. }, {
  6494. key: "sourceBufferCount",
  6495. get: function get() {
  6496. return this.sourceBuffers.reduce(function (acc, _ref15) {
  6497. var type = _ref15[0];
  6498. return acc + (type ? 1 : 0);
  6499. }, 0);
  6500. }
  6501. }, {
  6502. key: "sourceBufferTypes",
  6503. get: function get() {
  6504. return this.sourceBuffers.map(function (_ref16) {
  6505. var type = _ref16[0];
  6506. return type;
  6507. }).filter(function (type) {
  6508. return !!type;
  6509. });
  6510. }
  6511. }]);
  6512. }(Logger);
  6513. function removeSourceChildren(node) {
  6514. var sourceChildren = node.querySelectorAll('source');
  6515. [].slice.call(sourceChildren).forEach(function (source) {
  6516. node.removeChild(source);
  6517. });
  6518. }
  6519. function addSource(media, url) {
  6520. var source = self.document.createElement('source');
  6521. source.type = 'video/mp4';
  6522. source.src = url;
  6523. media.appendChild(source);
  6524. }
  6525. function sourceBufferNameToIndex(type) {
  6526. return type === 'audio' ? 1 : 0;
  6527. }
  6528. var CapLevelController = /*#__PURE__*/function () {
  6529. function CapLevelController(hls) {
  6530. this.hls = void 0;
  6531. this.autoLevelCapping = void 0;
  6532. this.firstLevel = void 0;
  6533. this.media = void 0;
  6534. this.restrictedLevels = void 0;
  6535. this.timer = void 0;
  6536. this.clientRect = void 0;
  6537. this.streamController = void 0;
  6538. this.hls = hls;
  6539. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  6540. this.firstLevel = -1;
  6541. this.media = null;
  6542. this.restrictedLevels = [];
  6543. this.timer = undefined;
  6544. this.clientRect = null;
  6545. this.registerListeners();
  6546. }
  6547. var _proto = CapLevelController.prototype;
  6548. _proto.setStreamController = function setStreamController(streamController) {
  6549. this.streamController = streamController;
  6550. };
  6551. _proto.destroy = function destroy() {
  6552. if (this.hls) {
  6553. this.unregisterListener();
  6554. }
  6555. if (this.timer) {
  6556. this.stopCapping();
  6557. }
  6558. this.media = null;
  6559. this.clientRect = null;
  6560. // @ts-ignore
  6561. this.hls = this.streamController = null;
  6562. };
  6563. _proto.registerListeners = function registerListeners() {
  6564. var hls = this.hls;
  6565. hls.on(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  6566. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  6567. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  6568. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  6569. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  6570. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  6571. };
  6572. _proto.unregisterListener = function unregisterListener() {
  6573. var hls = this.hls;
  6574. hls.off(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  6575. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  6576. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  6577. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  6578. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  6579. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  6580. };
  6581. _proto.onFpsDropLevelCapping = function onFpsDropLevelCapping(event, data) {
  6582. // Don't add a restricted level more than once
  6583. var level = this.hls.levels[data.droppedLevel];
  6584. if (this.isLevelAllowed(level)) {
  6585. this.restrictedLevels.push({
  6586. bitrate: level.bitrate,
  6587. height: level.height,
  6588. width: level.width
  6589. });
  6590. }
  6591. };
  6592. _proto.onMediaAttaching = function onMediaAttaching(event, data) {
  6593. this.media = data.media instanceof HTMLVideoElement ? data.media : null;
  6594. this.clientRect = null;
  6595. if (this.timer && this.hls.levels.length) {
  6596. this.detectPlayerSize();
  6597. }
  6598. };
  6599. _proto.onManifestParsed = function onManifestParsed(event, data) {
  6600. var hls = this.hls;
  6601. this.restrictedLevels = [];
  6602. this.firstLevel = data.firstLevel;
  6603. if (hls.config.capLevelToPlayerSize && data.video) {
  6604. // Start capping immediately if the manifest has signaled video codecs
  6605. this.startCapping();
  6606. }
  6607. };
  6608. _proto.onLevelsUpdated = function onLevelsUpdated(event, data) {
  6609. if (this.timer && isFiniteNumber(this.autoLevelCapping)) {
  6610. this.detectPlayerSize();
  6611. }
  6612. }
  6613. // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted
  6614. // to the first level
  6615. ;
  6616. _proto.onBufferCodecs = function onBufferCodecs(event, data) {
  6617. var hls = this.hls;
  6618. if (hls.config.capLevelToPlayerSize && data.video) {
  6619. // If the manifest did not signal a video codec capping has been deferred until we're certain video is present
  6620. this.startCapping();
  6621. }
  6622. };
  6623. _proto.onMediaDetaching = function onMediaDetaching() {
  6624. this.stopCapping();
  6625. this.media = null;
  6626. };
  6627. _proto.detectPlayerSize = function detectPlayerSize() {
  6628. if (this.media) {
  6629. if (this.mediaHeight <= 0 || this.mediaWidth <= 0) {
  6630. this.clientRect = null;
  6631. return;
  6632. }
  6633. var levels = this.hls.levels;
  6634. if (levels.length) {
  6635. var hls = this.hls;
  6636. var maxLevel = this.getMaxLevel(levels.length - 1);
  6637. if (maxLevel !== this.autoLevelCapping) {
  6638. hls.logger.log("Setting autoLevelCapping to " + maxLevel + ": " + levels[maxLevel].height + "p@" + levels[maxLevel].bitrate + " for media " + this.mediaWidth + "x" + this.mediaHeight);
  6639. }
  6640. hls.autoLevelCapping = maxLevel;
  6641. if (hls.autoLevelEnabled && hls.autoLevelCapping > this.autoLevelCapping && this.streamController) {
  6642. // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch
  6643. // usually happen when the user go to the fullscreen mode.
  6644. this.streamController.nextLevelSwitch();
  6645. }
  6646. this.autoLevelCapping = hls.autoLevelCapping;
  6647. }
  6648. }
  6649. }
  6650. /*
  6651. * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
  6652. */;
  6653. _proto.getMaxLevel = function getMaxLevel(capLevelIndex) {
  6654. var _this = this;
  6655. var levels = this.hls.levels;
  6656. if (!levels.length) {
  6657. return -1;
  6658. }
  6659. var validLevels = levels.filter(function (level, index) {
  6660. return _this.isLevelAllowed(level) && index <= capLevelIndex;
  6661. });
  6662. this.clientRect = null;
  6663. return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
  6664. };
  6665. _proto.startCapping = function startCapping() {
  6666. if (this.timer) {
  6667. // Don't reset capping if started twice; this can happen if the manifest signals a video codec
  6668. return;
  6669. }
  6670. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  6671. self.clearInterval(this.timer);
  6672. this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1000);
  6673. this.detectPlayerSize();
  6674. };
  6675. _proto.stopCapping = function stopCapping() {
  6676. this.restrictedLevels = [];
  6677. this.firstLevel = -1;
  6678. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  6679. if (this.timer) {
  6680. self.clearInterval(this.timer);
  6681. this.timer = undefined;
  6682. }
  6683. };
  6684. _proto.getDimensions = function getDimensions() {
  6685. if (this.clientRect) {
  6686. return this.clientRect;
  6687. }
  6688. var media = this.media;
  6689. var boundsRect = {
  6690. width: 0,
  6691. height: 0
  6692. };
  6693. if (media) {
  6694. var clientRect = media.getBoundingClientRect();
  6695. boundsRect.width = clientRect.width;
  6696. boundsRect.height = clientRect.height;
  6697. if (!boundsRect.width && !boundsRect.height) {
  6698. // When the media element has no width or height (equivalent to not being in the DOM),
  6699. // then use its width and height attributes (media.width, media.height)
  6700. boundsRect.width = clientRect.right - clientRect.left || media.width || 0;
  6701. boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;
  6702. }
  6703. }
  6704. this.clientRect = boundsRect;
  6705. return boundsRect;
  6706. };
  6707. _proto.isLevelAllowed = function isLevelAllowed(level) {
  6708. var restrictedLevels = this.restrictedLevels;
  6709. return !restrictedLevels.some(function (restrictedLevel) {
  6710. return level.bitrate === restrictedLevel.bitrate && level.width === restrictedLevel.width && level.height === restrictedLevel.height;
  6711. });
  6712. };
  6713. CapLevelController.getMaxLevelByMediaSize = function getMaxLevelByMediaSize(levels, width, height) {
  6714. if (!(levels != null && levels.length)) {
  6715. return -1;
  6716. }
  6717. // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next
  6718. // to determine whether we've chosen the greatest bandwidth for the media's dimensions
  6719. var atGreatestBandwidth = function atGreatestBandwidth(curLevel, nextLevel) {
  6720. if (!nextLevel) {
  6721. return true;
  6722. }
  6723. return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
  6724. };
  6725. // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to
  6726. // the max level
  6727. var maxLevelIndex = levels.length - 1;
  6728. // Prevent changes in aspect-ratio from causing capping to toggle back and forth
  6729. var squareSize = Math.max(width, height);
  6730. for (var i = 0; i < levels.length; i += 1) {
  6731. var level = levels[i];
  6732. if ((level.width >= squareSize || level.height >= squareSize) && atGreatestBandwidth(level, levels[i + 1])) {
  6733. maxLevelIndex = i;
  6734. break;
  6735. }
  6736. }
  6737. return maxLevelIndex;
  6738. };
  6739. return _createClass(CapLevelController, [{
  6740. key: "mediaWidth",
  6741. get: function get() {
  6742. return this.getDimensions().width * this.contentScaleFactor;
  6743. }
  6744. }, {
  6745. key: "mediaHeight",
  6746. get: function get() {
  6747. return this.getDimensions().height * this.contentScaleFactor;
  6748. }
  6749. }, {
  6750. key: "contentScaleFactor",
  6751. get: function get() {
  6752. var pixelRatio = 1;
  6753. if (!this.hls.config.ignoreDevicePixelRatio) {
  6754. try {
  6755. pixelRatio = self.devicePixelRatio;
  6756. } catch (e) {
  6757. /* no-op */
  6758. }
  6759. }
  6760. return Math.min(pixelRatio, this.hls.config.maxDevicePixelRatio);
  6761. }
  6762. }]);
  6763. }();
  6764. var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/;
  6765. var ATTR_LIST_REGEX = /(.+?)=(".*?"|.*?)(?:,|$)/g;
  6766. // adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
  6767. var AttrList = /*#__PURE__*/function () {
  6768. function AttrList(attrs, parsed) {
  6769. if (typeof attrs === 'string') {
  6770. attrs = AttrList.parseAttrList(attrs, parsed);
  6771. }
  6772. _extends(this, attrs);
  6773. }
  6774. var _proto = AttrList.prototype;
  6775. _proto.decimalInteger = function decimalInteger(attrName) {
  6776. var intValue = parseInt(this[attrName], 10);
  6777. if (intValue > Number.MAX_SAFE_INTEGER) {
  6778. return Infinity;
  6779. }
  6780. return intValue;
  6781. };
  6782. _proto.hexadecimalInteger = function hexadecimalInteger(attrName) {
  6783. if (this[attrName]) {
  6784. var stringValue = (this[attrName] || '0x').slice(2);
  6785. stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;
  6786. var value = new Uint8Array(stringValue.length / 2);
  6787. for (var i = 0; i < stringValue.length / 2; i++) {
  6788. value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
  6789. }
  6790. return value;
  6791. }
  6792. return null;
  6793. };
  6794. _proto.hexadecimalIntegerAsNumber = function hexadecimalIntegerAsNumber(attrName) {
  6795. var intValue = parseInt(this[attrName], 16);
  6796. if (intValue > Number.MAX_SAFE_INTEGER) {
  6797. return Infinity;
  6798. }
  6799. return intValue;
  6800. };
  6801. _proto.decimalFloatingPoint = function decimalFloatingPoint(attrName) {
  6802. return parseFloat(this[attrName]);
  6803. };
  6804. _proto.optionalFloat = function optionalFloat(attrName, defaultValue) {
  6805. var value = this[attrName];
  6806. return value ? parseFloat(value) : defaultValue;
  6807. };
  6808. _proto.enumeratedString = function enumeratedString(attrName) {
  6809. return this[attrName];
  6810. };
  6811. _proto.enumeratedStringList = function enumeratedStringList(attrName, dict) {
  6812. var attrValue = this[attrName];
  6813. return (attrValue ? attrValue.split(/[ ,]+/) : []).reduce(function (result, identifier) {
  6814. result[identifier.toLowerCase()] = true;
  6815. return result;
  6816. }, dict);
  6817. };
  6818. _proto.bool = function bool(attrName) {
  6819. return this[attrName] === 'YES';
  6820. };
  6821. _proto.decimalResolution = function decimalResolution(attrName) {
  6822. var res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
  6823. if (res === null) {
  6824. return undefined;
  6825. }
  6826. return {
  6827. width: parseInt(res[1], 10),
  6828. height: parseInt(res[2], 10)
  6829. };
  6830. };
  6831. AttrList.parseAttrList = function parseAttrList(input, parsed) {
  6832. var match;
  6833. var attrs = {};
  6834. var quote = '"';
  6835. ATTR_LIST_REGEX.lastIndex = 0;
  6836. while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
  6837. var name = match[1].trim();
  6838. var value = match[2];
  6839. var quotedString = value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1;
  6840. var hexadecimalSequence = false;
  6841. if (quotedString) {
  6842. value = value.slice(1, -1);
  6843. } else {
  6844. switch (name) {
  6845. case 'IV':
  6846. case 'SCTE35-CMD':
  6847. case 'SCTE35-IN':
  6848. case 'SCTE35-OUT':
  6849. hexadecimalSequence = true;
  6850. }
  6851. }
  6852. if (parsed && (quotedString || hexadecimalSequence)) ; else if (!hexadecimalSequence && !quotedString) {
  6853. switch (name) {
  6854. case 'CLOSED-CAPTIONS':
  6855. if (value === 'NONE') {
  6856. break;
  6857. }
  6858. // falls through
  6859. case 'ALLOWED-CPC':
  6860. case 'CLASS':
  6861. case 'ASSOC-LANGUAGE':
  6862. case 'AUDIO':
  6863. case 'BYTERANGE':
  6864. case 'CHANNELS':
  6865. case 'CHARACTERISTICS':
  6866. case 'CODECS':
  6867. case 'DATA-ID':
  6868. case 'END-DATE':
  6869. case 'GROUP-ID':
  6870. case 'ID':
  6871. case 'IMPORT':
  6872. case 'INSTREAM-ID':
  6873. case 'KEYFORMAT':
  6874. case 'KEYFORMATVERSIONS':
  6875. case 'LANGUAGE':
  6876. case 'NAME':
  6877. case 'PATHWAY-ID':
  6878. case 'QUERYPARAM':
  6879. case 'RECENTLY-REMOVED-DATERANGES':
  6880. case 'SERVER-URI':
  6881. case 'STABLE-RENDITION-ID':
  6882. case 'STABLE-VARIANT-ID':
  6883. case 'START-DATE':
  6884. case 'SUBTITLES':
  6885. case 'SUPPLEMENTAL-CODECS':
  6886. case 'URI':
  6887. case 'VALUE':
  6888. case 'VIDEO':
  6889. case 'X-ASSET-LIST':
  6890. case 'X-ASSET-URI':
  6891. // Since we are not checking tag:attribute combination, just warn rather than ignoring attribute
  6892. logger.warn(input + ": attribute " + name + " is missing quotes");
  6893. // continue;
  6894. }
  6895. }
  6896. attrs[name] = value;
  6897. }
  6898. return attrs;
  6899. };
  6900. return _createClass(AttrList, [{
  6901. key: "clientAttrs",
  6902. get: function get() {
  6903. return Object.keys(this).filter(function (attr) {
  6904. return attr.substring(0, 2) === 'X-';
  6905. });
  6906. }
  6907. }]);
  6908. }();
  6909. // Avoid exporting const enum so that these values can be inlined
  6910. var CLASS_INTERSTITIAL = 'com.apple.hls.interstitial';
  6911. function isDateRangeCueAttribute(attrName) {
  6912. return attrName !== "ID" && attrName !== "CLASS" && attrName !== "CUE" && attrName !== "START-DATE" && attrName !== "DURATION" && attrName !== "END-DATE" && attrName !== "END-ON-NEXT";
  6913. }
  6914. function isSCTE35Attribute(attrName) {
  6915. return attrName === "SCTE35-OUT" || attrName === "SCTE35-IN" || attrName === "SCTE35-CMD";
  6916. }
  6917. var DateRange = /*#__PURE__*/function () {
  6918. function DateRange(dateRangeAttr, dateRangeWithSameId, tagCount) {
  6919. var _dateRangeWithSameId$;
  6920. if (tagCount === void 0) {
  6921. tagCount = 0;
  6922. }
  6923. this.attr = void 0;
  6924. this.tagAnchor = void 0;
  6925. this.tagOrder = void 0;
  6926. this._startDate = void 0;
  6927. this._endDate = void 0;
  6928. this._dateAtEnd = void 0;
  6929. this._cue = void 0;
  6930. this._badValueForSameId = void 0;
  6931. this.tagAnchor = (dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.tagAnchor) || null;
  6932. this.tagOrder = (_dateRangeWithSameId$ = dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.tagOrder) != null ? _dateRangeWithSameId$ : tagCount;
  6933. if (dateRangeWithSameId) {
  6934. var previousAttr = dateRangeWithSameId.attr;
  6935. for (var key in previousAttr) {
  6936. if (Object.prototype.hasOwnProperty.call(dateRangeAttr, key) && dateRangeAttr[key] !== previousAttr[key]) {
  6937. logger.warn("DATERANGE tag attribute: \"" + key + "\" does not match for tags with ID: \"" + dateRangeAttr.ID + "\"");
  6938. this._badValueForSameId = key;
  6939. break;
  6940. }
  6941. }
  6942. // Merge DateRange tags with the same ID
  6943. dateRangeAttr = _extends(new AttrList({}), previousAttr, dateRangeAttr);
  6944. }
  6945. this.attr = dateRangeAttr;
  6946. if (dateRangeWithSameId) {
  6947. this._startDate = dateRangeWithSameId._startDate;
  6948. this._cue = dateRangeWithSameId._cue;
  6949. this._endDate = dateRangeWithSameId._endDate;
  6950. this._dateAtEnd = dateRangeWithSameId._dateAtEnd;
  6951. } else {
  6952. this._startDate = new Date(dateRangeAttr["START-DATE"]);
  6953. }
  6954. if ("END-DATE" in this.attr) {
  6955. var endDate = (dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.endDate) || new Date(this.attr["END-DATE"]);
  6956. if (isFiniteNumber(endDate.getTime())) {
  6957. this._endDate = endDate;
  6958. }
  6959. }
  6960. }
  6961. return _createClass(DateRange, [{
  6962. key: "id",
  6963. get: function get() {
  6964. return this.attr.ID;
  6965. }
  6966. }, {
  6967. key: "class",
  6968. get: function get() {
  6969. return this.attr.CLASS;
  6970. }
  6971. }, {
  6972. key: "cue",
  6973. get: function get() {
  6974. var _cue = this._cue;
  6975. if (_cue === undefined) {
  6976. return this._cue = this.attr.enumeratedStringList(this.attr.CUE ? 'CUE' : 'X-CUE', {
  6977. pre: false,
  6978. post: false,
  6979. once: false
  6980. });
  6981. }
  6982. return _cue;
  6983. }
  6984. }, {
  6985. key: "startTime",
  6986. get: function get() {
  6987. var tagAnchor = this.tagAnchor;
  6988. // eslint-disable-next-line @typescript-eslint/prefer-optional-chain
  6989. if (tagAnchor === null || tagAnchor.programDateTime === null) {
  6990. logger.warn("Expected tagAnchor Fragment with PDT set for DateRange \"" + this.id + "\": " + tagAnchor);
  6991. return NaN;
  6992. }
  6993. return tagAnchor.start + (this.startDate.getTime() - tagAnchor.programDateTime) / 1000;
  6994. }
  6995. }, {
  6996. key: "startDate",
  6997. get: function get() {
  6998. return this._startDate;
  6999. }
  7000. }, {
  7001. key: "endDate",
  7002. get: function get() {
  7003. var dateAtEnd = this._endDate || this._dateAtEnd;
  7004. if (dateAtEnd) {
  7005. return dateAtEnd;
  7006. }
  7007. var duration = this.duration;
  7008. if (duration !== null) {
  7009. return this._dateAtEnd = new Date(this._startDate.getTime() + duration * 1000);
  7010. }
  7011. return null;
  7012. }
  7013. }, {
  7014. key: "duration",
  7015. get: function get() {
  7016. if ("DURATION" in this.attr) {
  7017. var duration = this.attr.decimalFloatingPoint("DURATION");
  7018. if (isFiniteNumber(duration)) {
  7019. return duration;
  7020. }
  7021. } else if (this._endDate) {
  7022. return (this._endDate.getTime() - this._startDate.getTime()) / 1000;
  7023. }
  7024. return null;
  7025. }
  7026. }, {
  7027. key: "plannedDuration",
  7028. get: function get() {
  7029. if ("PLANNED-DURATION" in this.attr) {
  7030. return this.attr.decimalFloatingPoint("PLANNED-DURATION");
  7031. }
  7032. return null;
  7033. }
  7034. }, {
  7035. key: "endOnNext",
  7036. get: function get() {
  7037. return this.attr.bool("END-ON-NEXT");
  7038. }
  7039. }, {
  7040. key: "isInterstitial",
  7041. get: function get() {
  7042. return this.class === CLASS_INTERSTITIAL;
  7043. }
  7044. }, {
  7045. key: "isValid",
  7046. get: function get() {
  7047. return !!this.id && !this._badValueForSameId && isFiniteNumber(this.startDate.getTime()) && (this.duration === null || this.duration >= 0) && (!this.endOnNext || !!this.class) && (!this.attr.CUE || !this.cue.pre && !this.cue.post || this.cue.pre !== this.cue.post) && (!this.isInterstitial || 'X-ASSET-URI' in this.attr || 'X-ASSET-LIST' in this.attr);
  7048. }
  7049. }]);
  7050. }();
  7051. var DEFAULT_TARGET_DURATION = 10;
  7052. /**
  7053. * Object representing parsed data from an HLS Media Playlist. Found in {@link hls.js#Level.details}.
  7054. */
  7055. var LevelDetails = /*#__PURE__*/function () {
  7056. function LevelDetails(baseUrl) {
  7057. this.PTSKnown = false;
  7058. this.alignedSliding = false;
  7059. this.averagetargetduration = void 0;
  7060. this.endCC = 0;
  7061. this.endSN = 0;
  7062. this.fragments = void 0;
  7063. this.fragmentHint = void 0;
  7064. this.partList = null;
  7065. this.dateRanges = void 0;
  7066. this.dateRangeTagCount = 0;
  7067. this.live = true;
  7068. this.requestScheduled = -1;
  7069. this.ageHeader = 0;
  7070. this.advancedDateTime = void 0;
  7071. this.updated = true;
  7072. this.advanced = true;
  7073. this.misses = 0;
  7074. this.startCC = 0;
  7075. this.startSN = 0;
  7076. this.startTimeOffset = null;
  7077. this.targetduration = 0;
  7078. this.totalduration = 0;
  7079. this.type = null;
  7080. this.url = void 0;
  7081. this.m3u8 = '';
  7082. this.version = null;
  7083. this.canBlockReload = false;
  7084. this.canSkipUntil = 0;
  7085. this.canSkipDateRanges = false;
  7086. this.skippedSegments = 0;
  7087. this.recentlyRemovedDateranges = void 0;
  7088. this.partHoldBack = 0;
  7089. this.holdBack = 0;
  7090. this.partTarget = 0;
  7091. this.preloadHint = void 0;
  7092. this.renditionReports = void 0;
  7093. this.tuneInGoal = 0;
  7094. this.deltaUpdateFailed = void 0;
  7095. this.driftStartTime = 0;
  7096. this.driftEndTime = 0;
  7097. this.driftStart = 0;
  7098. this.driftEnd = 0;
  7099. this.encryptedFragments = void 0;
  7100. this.playlistParsingError = null;
  7101. this.variableList = null;
  7102. this.hasVariableRefs = false;
  7103. this.appliedTimelineOffset = void 0;
  7104. this.fragments = [];
  7105. this.encryptedFragments = [];
  7106. this.dateRanges = {};
  7107. this.url = baseUrl;
  7108. }
  7109. var _proto = LevelDetails.prototype;
  7110. _proto.reloaded = function reloaded(previous) {
  7111. if (!previous) {
  7112. this.advanced = true;
  7113. this.updated = true;
  7114. return;
  7115. }
  7116. var partSnDiff = this.lastPartSn - previous.lastPartSn;
  7117. var partIndexDiff = this.lastPartIndex - previous.lastPartIndex;
  7118. this.updated = this.endSN !== previous.endSN || !!partIndexDiff || !!partSnDiff || !this.live;
  7119. this.advanced = this.endSN > previous.endSN || partSnDiff > 0 || partSnDiff === 0 && partIndexDiff > 0;
  7120. if (this.updated || this.advanced) {
  7121. this.misses = Math.floor(previous.misses * 0.6);
  7122. } else {
  7123. this.misses = previous.misses + 1;
  7124. }
  7125. };
  7126. return _createClass(LevelDetails, [{
  7127. key: "hasProgramDateTime",
  7128. get: function get() {
  7129. if (this.fragments.length) {
  7130. return isFiniteNumber(this.fragments[this.fragments.length - 1].programDateTime);
  7131. }
  7132. return false;
  7133. }
  7134. }, {
  7135. key: "levelTargetDuration",
  7136. get: function get() {
  7137. return this.averagetargetduration || this.targetduration || DEFAULT_TARGET_DURATION;
  7138. }
  7139. }, {
  7140. key: "drift",
  7141. get: function get() {
  7142. var runTime = this.driftEndTime - this.driftStartTime;
  7143. if (runTime > 0) {
  7144. var runDuration = this.driftEnd - this.driftStart;
  7145. return runDuration * 1000 / runTime;
  7146. }
  7147. return 1;
  7148. }
  7149. }, {
  7150. key: "edge",
  7151. get: function get() {
  7152. return this.partEnd || this.fragmentEnd;
  7153. }
  7154. }, {
  7155. key: "partEnd",
  7156. get: function get() {
  7157. var _this$partList;
  7158. if ((_this$partList = this.partList) != null && _this$partList.length) {
  7159. return this.partList[this.partList.length - 1].end;
  7160. }
  7161. return this.fragmentEnd;
  7162. }
  7163. }, {
  7164. key: "fragmentEnd",
  7165. get: function get() {
  7166. var _this$fragments;
  7167. if ((_this$fragments = this.fragments) != null && _this$fragments.length) {
  7168. return this.fragments[this.fragments.length - 1].end;
  7169. }
  7170. return 0;
  7171. }
  7172. }, {
  7173. key: "fragmentStart",
  7174. get: function get() {
  7175. var _this$fragments2;
  7176. if ((_this$fragments2 = this.fragments) != null && _this$fragments2.length) {
  7177. return this.fragments[0].start;
  7178. }
  7179. return 0;
  7180. }
  7181. }, {
  7182. key: "age",
  7183. get: function get() {
  7184. if (this.advancedDateTime) {
  7185. return Math.max(Date.now() - this.advancedDateTime, 0) / 1000;
  7186. }
  7187. return 0;
  7188. }
  7189. }, {
  7190. key: "lastPartIndex",
  7191. get: function get() {
  7192. var _this$partList2;
  7193. if ((_this$partList2 = this.partList) != null && _this$partList2.length) {
  7194. return this.partList[this.partList.length - 1].index;
  7195. }
  7196. return -1;
  7197. }
  7198. }, {
  7199. key: "maxPartIndex",
  7200. get: function get() {
  7201. var partList = this.partList;
  7202. if (partList) {
  7203. var lastIndex = this.lastPartIndex;
  7204. if (lastIndex !== -1) {
  7205. for (var i = partList.length; i--;) {
  7206. if (partList[i].index > lastIndex) {
  7207. return partList[i].index;
  7208. }
  7209. }
  7210. return lastIndex;
  7211. }
  7212. }
  7213. return 0;
  7214. }
  7215. }, {
  7216. key: "lastPartSn",
  7217. get: function get() {
  7218. var _this$partList3;
  7219. if ((_this$partList3 = this.partList) != null && _this$partList3.length) {
  7220. return this.partList[this.partList.length - 1].fragment.sn;
  7221. }
  7222. return this.endSN;
  7223. }
  7224. }, {
  7225. key: "expired",
  7226. get: function get() {
  7227. if (this.live && this.age && this.misses < 3) {
  7228. var playlistWindowDuration = this.partEnd - this.fragmentStart;
  7229. return this.age > Math.max(playlistWindowDuration, this.totalduration) + this.levelTargetDuration;
  7230. }
  7231. return false;
  7232. }
  7233. }]);
  7234. }();
  7235. var DecrypterAesMode = {
  7236. cbc: 0,
  7237. ctr: 1
  7238. };
  7239. function isFullSegmentEncryption(method) {
  7240. return method === 'AES-128' || method === 'AES-256' || method === 'AES-256-CTR';
  7241. }
  7242. function getAesModeFromFullSegmentMethod(method) {
  7243. switch (method) {
  7244. case 'AES-128':
  7245. case 'AES-256':
  7246. return DecrypterAesMode.cbc;
  7247. case 'AES-256-CTR':
  7248. return DecrypterAesMode.ctr;
  7249. default:
  7250. throw new Error("invalid full segment method " + method);
  7251. }
  7252. }
  7253. var LevelKey = /*#__PURE__*/function () {
  7254. function LevelKey(method, uri, format, formatversions, iv, keyId) {
  7255. if (formatversions === void 0) {
  7256. formatversions = [1];
  7257. }
  7258. if (iv === void 0) {
  7259. iv = null;
  7260. }
  7261. this.uri = void 0;
  7262. this.method = void 0;
  7263. this.keyFormat = void 0;
  7264. this.keyFormatVersions = void 0;
  7265. this.encrypted = void 0;
  7266. this.isCommonEncryption = void 0;
  7267. this.iv = null;
  7268. this.key = null;
  7269. this.keyId = null;
  7270. this.pssh = null;
  7271. this.method = method;
  7272. this.uri = uri;
  7273. this.keyFormat = format;
  7274. this.keyFormatVersions = formatversions;
  7275. this.iv = iv;
  7276. this.encrypted = method ? method !== 'NONE' : false;
  7277. this.isCommonEncryption = this.encrypted && !isFullSegmentEncryption(method);
  7278. if (keyId != null && keyId.startsWith('0x')) {
  7279. this.keyId = new Uint8Array(hexToArrayBuffer(keyId));
  7280. }
  7281. }
  7282. LevelKey.clearKeyUriToKeyIdMap = function clearKeyUriToKeyIdMap() {
  7283. };
  7284. var _proto = LevelKey.prototype;
  7285. _proto.matches = function matches(key) {
  7286. var _key$iv, _this$iv;
  7287. return key.uri === this.uri && key.method === this.method && key.encrypted === this.encrypted && key.keyFormat === this.keyFormat && key.keyFormatVersions.join(',') === this.keyFormatVersions.join(',') && ((_key$iv = key.iv) == null ? void 0 : _key$iv.join(',')) === ((_this$iv = this.iv) == null ? void 0 : _this$iv.join(','));
  7288. };
  7289. _proto.isSupported = function isSupported() {
  7290. // If it's Segment encryption or No encryption, just select that key system
  7291. if (this.method) {
  7292. if (isFullSegmentEncryption(this.method) || this.method === 'NONE') {
  7293. return true;
  7294. }
  7295. if (this.keyFormat === 'identity') {
  7296. // Maintain support for clear SAMPLE-AES with MPEG-3 TS
  7297. return this.method === 'SAMPLE-AES';
  7298. }
  7299. }
  7300. return false;
  7301. };
  7302. _proto.getDecryptData = function getDecryptData(sn) {
  7303. if (!this.encrypted || !this.uri) {
  7304. return null;
  7305. }
  7306. if (isFullSegmentEncryption(this.method) && this.uri && !this.iv) {
  7307. if (typeof sn !== 'number') {
  7308. // We are fetching decryption data for a initialization segment
  7309. // If the segment was encrypted with AES-128/256
  7310. // It must have an IV defined. We cannot substitute the Segment Number in.
  7311. logger.warn("missing IV for initialization segment with method=\"" + this.method + "\" - compliance issue");
  7312. // Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation.
  7313. sn = 0;
  7314. }
  7315. var iv = createInitializationVector(sn);
  7316. var decryptdata = new LevelKey(this.method, this.uri, 'identity', this.keyFormatVersions, iv);
  7317. return decryptdata;
  7318. }
  7319. {
  7320. return this;
  7321. }
  7322. };
  7323. return LevelKey;
  7324. }();
  7325. function createInitializationVector(segmentNumber) {
  7326. var uint8View = new Uint8Array(16);
  7327. for (var i = 12; i < 16; i++) {
  7328. uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff;
  7329. }
  7330. return uint8View;
  7331. }
  7332. var MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g;
  7333. var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
  7334. var IS_MEDIA_PLAYLIST = /^#EXT(?:INF|-X-TARGETDURATION):/m; // Handle empty Media Playlist (first EXTINF not signaled, but TARGETDURATION present)
  7335. var LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,
  7336. // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
  7337. /(?!#) *(\S[^\r\n]*)/.source,
  7338. // segment URI, group 3 => the URI (note newline is not eaten)
  7339. /#.*/.source // All other non-segment oriented tags will match with all groups empty
  7340. ].join('|'), 'g');
  7341. var LEVEL_PLAYLIST_REGEX_SLOW = new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|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|INDEPENDENT-SEGMENTS)/.source, /(#)([^:]*):(.*)/.source, /(#)(.*)(?:.*)\r?\n?/.source].join('|'));
  7342. var M3U8Parser = /*#__PURE__*/function () {
  7343. function M3U8Parser() {}
  7344. M3U8Parser.findGroup = function findGroup(groups, mediaGroupId) {
  7345. for (var i = 0; i < groups.length; i++) {
  7346. var group = groups[i];
  7347. if (group.id === mediaGroupId) {
  7348. return group;
  7349. }
  7350. }
  7351. };
  7352. M3U8Parser.resolve = function resolve(url, baseUrl) {
  7353. return urlToolkitExports.buildAbsoluteURL(baseUrl, url, {
  7354. alwaysNormalize: true
  7355. });
  7356. };
  7357. M3U8Parser.isMediaPlaylist = function isMediaPlaylist(str) {
  7358. return IS_MEDIA_PLAYLIST.test(str);
  7359. };
  7360. M3U8Parser.parseMasterPlaylist = function parseMasterPlaylist(string, baseurl) {
  7361. var hasVariableRefs = false;
  7362. var parsed = {
  7363. contentSteering: null,
  7364. levels: [],
  7365. playlistParsingError: null,
  7366. sessionData: null,
  7367. sessionKeys: null,
  7368. startTimeOffset: null,
  7369. variableList: null,
  7370. hasVariableRefs: hasVariableRefs
  7371. };
  7372. var levelsWithKnownCodecs = [];
  7373. MASTER_PLAYLIST_REGEX.lastIndex = 0;
  7374. var result;
  7375. while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
  7376. if (result[1]) {
  7377. var _level$unknownCodecs;
  7378. // '#EXT-X-STREAM-INF' is found, parse level tag in group 1
  7379. var attrs = new AttrList(result[1], parsed);
  7380. var uri = result[2];
  7381. var level = {
  7382. attrs: attrs,
  7383. bitrate: attrs.decimalInteger('BANDWIDTH') || attrs.decimalInteger('AVERAGE-BANDWIDTH'),
  7384. name: attrs.NAME,
  7385. url: M3U8Parser.resolve(uri, baseurl)
  7386. };
  7387. var resolution = attrs.decimalResolution('RESOLUTION');
  7388. if (resolution) {
  7389. level.width = resolution.width;
  7390. level.height = resolution.height;
  7391. }
  7392. setCodecs(attrs.CODECS, level);
  7393. var supplementalCodecs = attrs['SUPPLEMENTAL-CODECS'];
  7394. if (supplementalCodecs) {
  7395. level.supplemental = {};
  7396. setCodecs(supplementalCodecs, level.supplemental);
  7397. }
  7398. if (!((_level$unknownCodecs = level.unknownCodecs) != null && _level$unknownCodecs.length)) {
  7399. levelsWithKnownCodecs.push(level);
  7400. }
  7401. parsed.levels.push(level);
  7402. } else if (result[3]) {
  7403. var tag = result[3];
  7404. var attributes = result[4];
  7405. switch (tag) {
  7406. case 'SESSION-DATA':
  7407. {
  7408. // #EXT-X-SESSION-DATA
  7409. var sessionAttrs = new AttrList(attributes, parsed);
  7410. var dataId = sessionAttrs['DATA-ID'];
  7411. if (dataId) {
  7412. if (parsed.sessionData === null) {
  7413. parsed.sessionData = {};
  7414. }
  7415. parsed.sessionData[dataId] = sessionAttrs;
  7416. }
  7417. break;
  7418. }
  7419. case 'SESSION-KEY':
  7420. {
  7421. // #EXT-X-SESSION-KEY
  7422. var sessionKey = parseKey(attributes, baseurl, parsed);
  7423. if (sessionKey.encrypted && sessionKey.isSupported()) {
  7424. if (parsed.sessionKeys === null) {
  7425. parsed.sessionKeys = [];
  7426. }
  7427. parsed.sessionKeys.push(sessionKey);
  7428. } else {
  7429. logger.warn("[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: \"" + attributes + "\"");
  7430. }
  7431. break;
  7432. }
  7433. case 'DEFINE':
  7434. {
  7435. break;
  7436. }
  7437. case 'CONTENT-STEERING':
  7438. {
  7439. // #EXT-X-CONTENT-STEERING
  7440. var contentSteeringAttributes = new AttrList(attributes, parsed);
  7441. parsed.contentSteering = {
  7442. uri: M3U8Parser.resolve(contentSteeringAttributes['SERVER-URI'], baseurl),
  7443. pathwayId: contentSteeringAttributes['PATHWAY-ID'] || '.'
  7444. };
  7445. break;
  7446. }
  7447. case 'START':
  7448. {
  7449. // #EXT-X-START
  7450. parsed.startTimeOffset = parseStartTimeOffset(attributes);
  7451. break;
  7452. }
  7453. }
  7454. }
  7455. }
  7456. // Filter out levels with unknown codecs if it does not remove all levels
  7457. var stripUnknownCodecLevels = levelsWithKnownCodecs.length > 0 && levelsWithKnownCodecs.length < parsed.levels.length;
  7458. parsed.levels = stripUnknownCodecLevels ? levelsWithKnownCodecs : parsed.levels;
  7459. if (parsed.levels.length === 0) {
  7460. parsed.playlistParsingError = new Error('no levels found in manifest');
  7461. }
  7462. return parsed;
  7463. };
  7464. M3U8Parser.parseMasterPlaylistMedia = function parseMasterPlaylistMedia(string, baseurl, parsed) {
  7465. var result;
  7466. var results = {};
  7467. var levels = parsed.levels;
  7468. var groupsByType = {
  7469. AUDIO: levels.map(function (level) {
  7470. return {
  7471. id: level.attrs.AUDIO,
  7472. audioCodec: level.audioCodec
  7473. };
  7474. }),
  7475. SUBTITLES: levels.map(function (level) {
  7476. return {
  7477. id: level.attrs.SUBTITLES,
  7478. textCodec: level.textCodec
  7479. };
  7480. }),
  7481. 'CLOSED-CAPTIONS': []
  7482. };
  7483. var id = 0;
  7484. MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
  7485. while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
  7486. var attrs = new AttrList(result[1], parsed);
  7487. var type = attrs.TYPE;
  7488. if (type) {
  7489. var groups = groupsByType[type];
  7490. var medias = results[type] || [];
  7491. results[type] = medias;
  7492. var lang = attrs.LANGUAGE;
  7493. var assocLang = attrs['ASSOC-LANGUAGE'];
  7494. var channels = attrs.CHANNELS;
  7495. var characteristics = attrs.CHARACTERISTICS;
  7496. var instreamId = attrs['INSTREAM-ID'];
  7497. var media = {
  7498. attrs: attrs,
  7499. bitrate: 0,
  7500. id: id++,
  7501. groupId: attrs['GROUP-ID'] || '',
  7502. name: attrs.NAME || lang || '',
  7503. type: type,
  7504. default: attrs.bool('DEFAULT'),
  7505. autoselect: attrs.bool('AUTOSELECT'),
  7506. forced: attrs.bool('FORCED'),
  7507. lang: lang,
  7508. url: attrs.URI ? M3U8Parser.resolve(attrs.URI, baseurl) : ''
  7509. };
  7510. if (assocLang) {
  7511. media.assocLang = assocLang;
  7512. }
  7513. if (channels) {
  7514. media.channels = channels;
  7515. }
  7516. if (characteristics) {
  7517. media.characteristics = characteristics;
  7518. }
  7519. if (instreamId) {
  7520. media.instreamId = instreamId;
  7521. }
  7522. if (groups != null && groups.length) {
  7523. // If there are audio or text groups signalled in the manifest, let's look for a matching codec string for this track
  7524. // If we don't find the track signalled, lets use the first audio groups codec we have
  7525. // Acting as a best guess
  7526. var groupCodec = M3U8Parser.findGroup(groups, media.groupId) || groups[0];
  7527. assignCodec(media, groupCodec, 'audioCodec');
  7528. assignCodec(media, groupCodec, 'textCodec');
  7529. }
  7530. medias.push(media);
  7531. }
  7532. }
  7533. return results;
  7534. };
  7535. M3U8Parser.parseLevelPlaylist = function parseLevelPlaylist(string, baseurl, id, type, levelUrlId, multivariantVariableList) {
  7536. var _LEVEL_PLAYLIST_REGEX;
  7537. var base = {
  7538. url: baseurl
  7539. };
  7540. var level = new LevelDetails(baseurl);
  7541. var fragments = level.fragments;
  7542. var programDateTimes = [];
  7543. // The most recent init segment seen (applies to all subsequent segments)
  7544. var currentInitSegment = null;
  7545. var currentSN = 0;
  7546. var currentPart = 0;
  7547. var totalduration = 0;
  7548. var discontinuityCounter = 0;
  7549. var currentBitrate = 0;
  7550. var prevFrag = null;
  7551. var frag = new Fragment(type, base);
  7552. var result;
  7553. var i;
  7554. var levelkeys;
  7555. var firstPdtIndex = -1;
  7556. var createNextFrag = false;
  7557. var nextByteRange = null;
  7558. var serverControlAttrs;
  7559. LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
  7560. level.m3u8 = string;
  7561. level.hasVariableRefs = false;
  7562. if (((_LEVEL_PLAYLIST_REGEX = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) == null ? void 0 : _LEVEL_PLAYLIST_REGEX[0]) !== '#EXTM3U') {
  7563. level.playlistParsingError = new Error('Missing format identifier #EXTM3U');
  7564. return level;
  7565. }
  7566. while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
  7567. if (createNextFrag) {
  7568. createNextFrag = false;
  7569. frag = new Fragment(type, base);
  7570. // setup the next fragment for part loading
  7571. frag.playlistOffset = totalduration;
  7572. frag.start = totalduration;
  7573. frag.sn = currentSN;
  7574. frag.cc = discontinuityCounter;
  7575. if (currentBitrate) {
  7576. frag.bitrate = currentBitrate;
  7577. }
  7578. frag.level = id;
  7579. if (currentInitSegment) {
  7580. frag.initSegment = currentInitSegment;
  7581. if (currentInitSegment.rawProgramDateTime) {
  7582. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  7583. currentInitSegment.rawProgramDateTime = null;
  7584. }
  7585. if (nextByteRange) {
  7586. frag.setByteRange(nextByteRange);
  7587. nextByteRange = null;
  7588. }
  7589. }
  7590. }
  7591. var duration = result[1];
  7592. if (duration) {
  7593. // INF
  7594. frag.duration = parseFloat(duration);
  7595. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  7596. var title = (' ' + result[2]).slice(1);
  7597. frag.title = title || null;
  7598. frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);
  7599. } else if (result[3]) {
  7600. // url
  7601. if (isFiniteNumber(frag.duration)) {
  7602. frag.playlistOffset = totalduration;
  7603. frag.start = totalduration;
  7604. if (levelkeys) {
  7605. setFragLevelKeys(frag, levelkeys, level);
  7606. }
  7607. frag.sn = currentSN;
  7608. frag.level = id;
  7609. frag.cc = discontinuityCounter;
  7610. fragments.push(frag);
  7611. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  7612. var uri = (' ' + result[3]).slice(1);
  7613. frag.relurl = uri;
  7614. assignProgramDateTime(frag, prevFrag, programDateTimes);
  7615. prevFrag = frag;
  7616. totalduration += frag.duration;
  7617. currentSN++;
  7618. currentPart = 0;
  7619. createNextFrag = true;
  7620. }
  7621. } else {
  7622. result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
  7623. if (!result) {
  7624. logger.warn('No matches on slow regex match for level playlist!');
  7625. continue;
  7626. }
  7627. for (i = 1; i < result.length; i++) {
  7628. if (result[i] !== undefined) {
  7629. break;
  7630. }
  7631. }
  7632. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  7633. var tag = (' ' + result[i]).slice(1);
  7634. var value1 = (' ' + result[i + 1]).slice(1);
  7635. var value2 = result[i + 2] ? (' ' + result[i + 2]).slice(1) : null;
  7636. switch (tag) {
  7637. case 'BYTERANGE':
  7638. if (prevFrag) {
  7639. frag.setByteRange(value1, prevFrag);
  7640. } else {
  7641. frag.setByteRange(value1);
  7642. }
  7643. break;
  7644. case 'PROGRAM-DATE-TIME':
  7645. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  7646. frag.rawProgramDateTime = value1;
  7647. frag.tagList.push(['PROGRAM-DATE-TIME', value1]);
  7648. if (firstPdtIndex === -1) {
  7649. firstPdtIndex = fragments.length;
  7650. }
  7651. break;
  7652. case 'PLAYLIST-TYPE':
  7653. if (level.type) {
  7654. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  7655. }
  7656. level.type = value1.toUpperCase();
  7657. break;
  7658. case 'MEDIA-SEQUENCE':
  7659. if (level.startSN !== 0) {
  7660. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  7661. } else if (fragments.length > 0) {
  7662. assignMustAppearBeforeSegmentsError(level, tag, result);
  7663. }
  7664. currentSN = level.startSN = parseInt(value1);
  7665. break;
  7666. case 'SKIP':
  7667. {
  7668. if (level.skippedSegments) {
  7669. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  7670. }
  7671. var skipAttrs = new AttrList(value1, level);
  7672. var skippedSegments = skipAttrs.decimalInteger('SKIPPED-SEGMENTS');
  7673. if (isFiniteNumber(skippedSegments)) {
  7674. level.skippedSegments += skippedSegments;
  7675. // This will result in fragments[] containing undefined values, which we will fill in with `mergeDetails`
  7676. for (var _i = skippedSegments; _i--;) {
  7677. fragments.push(null);
  7678. }
  7679. currentSN += skippedSegments;
  7680. }
  7681. var recentlyRemovedDateranges = skipAttrs.enumeratedString('RECENTLY-REMOVED-DATERANGES');
  7682. if (recentlyRemovedDateranges) {
  7683. level.recentlyRemovedDateranges = (level.recentlyRemovedDateranges || []).concat(recentlyRemovedDateranges.split('\t'));
  7684. }
  7685. break;
  7686. }
  7687. case 'TARGETDURATION':
  7688. if (level.targetduration !== 0) {
  7689. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  7690. }
  7691. level.targetduration = Math.max(parseInt(value1), 1);
  7692. break;
  7693. case 'VERSION':
  7694. if (level.version !== null) {
  7695. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  7696. }
  7697. level.version = parseInt(value1);
  7698. break;
  7699. case 'INDEPENDENT-SEGMENTS':
  7700. break;
  7701. case 'ENDLIST':
  7702. if (!level.live) {
  7703. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  7704. }
  7705. level.live = false;
  7706. break;
  7707. case '#':
  7708. if (value1 || value2) {
  7709. frag.tagList.push(value2 ? [value1, value2] : [value1]);
  7710. }
  7711. break;
  7712. case 'DISCONTINUITY':
  7713. discontinuityCounter++;
  7714. frag.tagList.push(['DIS']);
  7715. break;
  7716. case 'GAP':
  7717. frag.gap = true;
  7718. frag.tagList.push([tag]);
  7719. break;
  7720. case 'BITRATE':
  7721. frag.tagList.push([tag, value1]);
  7722. currentBitrate = parseInt(value1) * 1000;
  7723. if (isFiniteNumber(currentBitrate)) {
  7724. frag.bitrate = currentBitrate;
  7725. } else {
  7726. currentBitrate = 0;
  7727. }
  7728. break;
  7729. case 'DATERANGE':
  7730. {
  7731. var dateRangeAttr = new AttrList(value1, level);
  7732. var dateRange = new DateRange(dateRangeAttr, level.dateRanges[dateRangeAttr.ID], level.dateRangeTagCount);
  7733. level.dateRangeTagCount++;
  7734. if (dateRange.isValid || level.skippedSegments) {
  7735. level.dateRanges[dateRange.id] = dateRange;
  7736. } else {
  7737. logger.warn("Ignoring invalid DATERANGE tag: \"" + value1 + "\"");
  7738. }
  7739. // Add to fragment tag list for backwards compatibility (< v1.2.0)
  7740. frag.tagList.push(['EXT-X-DATERANGE', value1]);
  7741. break;
  7742. }
  7743. case 'DEFINE':
  7744. {
  7745. break;
  7746. }
  7747. case 'DISCONTINUITY-SEQUENCE':
  7748. if (level.startCC !== 0) {
  7749. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  7750. } else if (fragments.length > 0) {
  7751. assignMustAppearBeforeSegmentsError(level, tag, result);
  7752. }
  7753. level.startCC = discontinuityCounter = parseInt(value1);
  7754. break;
  7755. case 'KEY':
  7756. {
  7757. var levelKey = parseKey(value1, baseurl, level);
  7758. if (levelKey.isSupported()) {
  7759. if (levelKey.method === 'NONE') {
  7760. levelkeys = undefined;
  7761. break;
  7762. }
  7763. if (!levelkeys) {
  7764. levelkeys = {};
  7765. }
  7766. var currentKey = levelkeys[levelKey.keyFormat];
  7767. // Ignore duplicate playlist KEY tags
  7768. if (!(currentKey != null && currentKey.matches(levelKey))) {
  7769. if (currentKey) {
  7770. levelkeys = _extends({}, levelkeys);
  7771. }
  7772. levelkeys[levelKey.keyFormat] = levelKey;
  7773. }
  7774. } else {
  7775. logger.warn("[Keys] Ignoring invalid EXT-X-KEY tag: \"" + value1 + "\"");
  7776. }
  7777. break;
  7778. }
  7779. case 'START':
  7780. level.startTimeOffset = parseStartTimeOffset(value1);
  7781. break;
  7782. case 'MAP':
  7783. {
  7784. var mapAttrs = new AttrList(value1, level);
  7785. if (frag.duration) {
  7786. // Initial segment tag is after segment duration tag.
  7787. // #EXTINF: 6.0
  7788. // #EXT-X-MAP:URI="init.mp4
  7789. var init = new Fragment(type, base);
  7790. setInitSegment(init, mapAttrs, id, levelkeys);
  7791. currentInitSegment = init;
  7792. frag.initSegment = currentInitSegment;
  7793. if (currentInitSegment.rawProgramDateTime && !frag.rawProgramDateTime) {
  7794. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  7795. }
  7796. } else {
  7797. // Initial segment tag is before segment duration tag
  7798. // Handle case where EXT-X-MAP is declared after EXT-X-BYTERANGE
  7799. var end = frag.byteRangeEndOffset;
  7800. if (end) {
  7801. var start = frag.byteRangeStartOffset;
  7802. nextByteRange = end - start + "@" + start;
  7803. } else {
  7804. nextByteRange = null;
  7805. }
  7806. setInitSegment(frag, mapAttrs, id, levelkeys);
  7807. currentInitSegment = frag;
  7808. createNextFrag = true;
  7809. }
  7810. currentInitSegment.cc = discontinuityCounter;
  7811. break;
  7812. }
  7813. case 'SERVER-CONTROL':
  7814. {
  7815. if (serverControlAttrs) {
  7816. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  7817. }
  7818. serverControlAttrs = new AttrList(value1);
  7819. level.canBlockReload = serverControlAttrs.bool('CAN-BLOCK-RELOAD');
  7820. level.canSkipUntil = serverControlAttrs.optionalFloat('CAN-SKIP-UNTIL', 0);
  7821. level.canSkipDateRanges = level.canSkipUntil > 0 && serverControlAttrs.bool('CAN-SKIP-DATERANGES');
  7822. level.partHoldBack = serverControlAttrs.optionalFloat('PART-HOLD-BACK', 0);
  7823. level.holdBack = serverControlAttrs.optionalFloat('HOLD-BACK', 0);
  7824. break;
  7825. }
  7826. case 'PART-INF':
  7827. {
  7828. if (level.partTarget) {
  7829. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  7830. }
  7831. var partInfAttrs = new AttrList(value1);
  7832. level.partTarget = partInfAttrs.decimalFloatingPoint('PART-TARGET');
  7833. break;
  7834. }
  7835. case 'PART':
  7836. {
  7837. var partList = level.partList;
  7838. if (!partList) {
  7839. partList = level.partList = [];
  7840. }
  7841. var previousFragmentPart = currentPart > 0 ? partList[partList.length - 1] : undefined;
  7842. var index = currentPart++;
  7843. var partAttrs = new AttrList(value1, level);
  7844. var part = new Part(partAttrs, frag, base, index, previousFragmentPart);
  7845. partList.push(part);
  7846. frag.duration += part.duration;
  7847. break;
  7848. }
  7849. case 'PRELOAD-HINT':
  7850. {
  7851. var preloadHintAttrs = new AttrList(value1, level);
  7852. level.preloadHint = preloadHintAttrs;
  7853. break;
  7854. }
  7855. case 'RENDITION-REPORT':
  7856. {
  7857. var renditionReportAttrs = new AttrList(value1, level);
  7858. level.renditionReports = level.renditionReports || [];
  7859. level.renditionReports.push(renditionReportAttrs);
  7860. break;
  7861. }
  7862. default:
  7863. logger.warn("line parsed but not handled: " + result);
  7864. break;
  7865. }
  7866. }
  7867. }
  7868. if (prevFrag && !prevFrag.relurl) {
  7869. fragments.pop();
  7870. totalduration -= prevFrag.duration;
  7871. if (level.partList) {
  7872. level.fragmentHint = prevFrag;
  7873. }
  7874. } else if (level.partList) {
  7875. assignProgramDateTime(frag, prevFrag, programDateTimes);
  7876. frag.cc = discontinuityCounter;
  7877. level.fragmentHint = frag;
  7878. if (levelkeys) {
  7879. setFragLevelKeys(frag, levelkeys, level);
  7880. }
  7881. }
  7882. if (!level.targetduration) {
  7883. level.playlistParsingError = new Error("#EXT-X-TARGETDURATION is required");
  7884. }
  7885. var fragmentLength = fragments.length;
  7886. var firstFragment = fragments[0];
  7887. var lastFragment = fragments[fragmentLength - 1];
  7888. totalduration += level.skippedSegments * level.targetduration;
  7889. if (totalduration > 0 && fragmentLength && lastFragment) {
  7890. level.averagetargetduration = totalduration / fragmentLength;
  7891. var lastSn = lastFragment.sn;
  7892. level.endSN = lastSn !== 'initSegment' ? lastSn : 0;
  7893. if (!level.live) {
  7894. lastFragment.endList = true;
  7895. }
  7896. if (firstFragment && level.startCC === undefined) {
  7897. level.startCC = firstFragment.cc;
  7898. }
  7899. /**
  7900. * Backfill any missing PDT values
  7901. * "If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after
  7902. * one or more Media Segment URIs, the client SHOULD extrapolate
  7903. * backward from that tag (using EXTINF durations and/or media
  7904. * timestamps) to associate dates with those segments."
  7905. * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs
  7906. * computed.
  7907. */
  7908. if (firstPdtIndex > 0) {
  7909. backfillProgramDateTimes(fragments, firstPdtIndex);
  7910. if (firstFragment) {
  7911. programDateTimes.unshift(firstFragment);
  7912. }
  7913. }
  7914. } else {
  7915. level.endSN = 0;
  7916. level.startCC = 0;
  7917. }
  7918. if (level.fragmentHint) {
  7919. totalduration += level.fragmentHint.duration;
  7920. }
  7921. level.totalduration = totalduration;
  7922. if (programDateTimes.length && level.dateRangeTagCount && firstFragment) {
  7923. mapDateRanges(programDateTimes, level);
  7924. }
  7925. level.endCC = discontinuityCounter;
  7926. return level;
  7927. };
  7928. return M3U8Parser;
  7929. }();
  7930. function mapDateRanges(programDateTimes, details) {
  7931. // Make sure DateRanges are mapped to a ProgramDateTime tag that applies a date to a segment that overlaps with its start date
  7932. var programDateTimeCount = programDateTimes.length;
  7933. if (!programDateTimeCount) {
  7934. return;
  7935. }
  7936. var lastProgramDateTime = programDateTimes[programDateTimeCount - 1];
  7937. var playlistEnd = details.live ? Infinity : details.totalduration;
  7938. var dateRangeIds = Object.keys(details.dateRanges);
  7939. for (var i = dateRangeIds.length; i--;) {
  7940. var dateRange = details.dateRanges[dateRangeIds[i]];
  7941. var startDateTime = dateRange.startDate.getTime();
  7942. dateRange.tagAnchor = lastProgramDateTime.ref;
  7943. for (var j = programDateTimeCount; j--;) {
  7944. var fragIndex = findFragmentWithStartDate(details, startDateTime, programDateTimes, j, playlistEnd);
  7945. if (fragIndex !== -1) {
  7946. dateRange.tagAnchor = details.fragments[fragIndex].ref;
  7947. break;
  7948. }
  7949. }
  7950. }
  7951. }
  7952. function findFragmentWithStartDate(details, startDateTime, programDateTimes, index, endTime) {
  7953. var pdtFragment = programDateTimes[index];
  7954. if (pdtFragment) {
  7955. // find matching range between PDT tags
  7956. var pdtStart = pdtFragment.programDateTime;
  7957. if (startDateTime >= pdtStart || index === 0) {
  7958. var _programDateTimes;
  7959. var durationBetweenPdt = (((_programDateTimes = programDateTimes[index + 1]) == null ? void 0 : _programDateTimes.start) || endTime) - pdtFragment.start;
  7960. if (startDateTime <= pdtStart + durationBetweenPdt * 1000) {
  7961. // map to fragment with date-time range
  7962. var startIndex = programDateTimes[index].sn - details.startSN;
  7963. var fragments = details.fragments;
  7964. if (fragments.length > programDateTimes.length) {
  7965. var endSegment = programDateTimes[index + 1] || fragments[fragments.length - 1];
  7966. var endIndex = endSegment.sn - details.startSN;
  7967. for (var i = endIndex; i > startIndex; i--) {
  7968. var fragStartDateTime = fragments[i].programDateTime;
  7969. if (startDateTime >= fragStartDateTime && startDateTime < fragStartDateTime + fragments[i].duration * 1000) {
  7970. return i;
  7971. }
  7972. }
  7973. }
  7974. return startIndex;
  7975. }
  7976. }
  7977. }
  7978. return -1;
  7979. }
  7980. function parseKey(keyTagAttributes, baseurl, parsed) {
  7981. var _keyAttrs$METHOD, _keyAttrs$KEYFORMAT;
  7982. // https://tools.ietf.org/html/rfc8216#section-4.3.2.4
  7983. var keyAttrs = new AttrList(keyTagAttributes, parsed);
  7984. var decryptmethod = (_keyAttrs$METHOD = keyAttrs.METHOD) != null ? _keyAttrs$METHOD : '';
  7985. var decrypturi = keyAttrs.URI;
  7986. var decryptiv = keyAttrs.hexadecimalInteger('IV');
  7987. var decryptkeyformatversions = keyAttrs.KEYFORMATVERSIONS;
  7988. // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of "identity".
  7989. var decryptkeyformat = (_keyAttrs$KEYFORMAT = keyAttrs.KEYFORMAT) != null ? _keyAttrs$KEYFORMAT : 'identity';
  7990. if (decrypturi && keyAttrs.IV && !decryptiv) {
  7991. logger.error("Invalid IV: " + keyAttrs.IV);
  7992. }
  7993. // If decrypturi is a URI with a scheme, then baseurl will be ignored
  7994. // No uri is allowed when METHOD is NONE
  7995. var resolvedUri = decrypturi ? M3U8Parser.resolve(decrypturi, baseurl) : '';
  7996. var keyFormatVersions = (decryptkeyformatversions ? decryptkeyformatversions : '1').split('/').map(Number).filter(Number.isFinite);
  7997. return new LevelKey(decryptmethod, resolvedUri, decryptkeyformat, keyFormatVersions, decryptiv, keyAttrs.KEYID);
  7998. }
  7999. function parseStartTimeOffset(startAttributes) {
  8000. var startAttrs = new AttrList(startAttributes);
  8001. var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');
  8002. if (isFiniteNumber(startTimeOffset)) {
  8003. return startTimeOffset;
  8004. }
  8005. return null;
  8006. }
  8007. function setCodecs(codecsAttributeValue, level) {
  8008. var codecs = (codecsAttributeValue || '').split(/[ ,]+/).filter(function (c) {
  8009. return c;
  8010. });
  8011. ['video', 'audio', 'text'].forEach(function (type) {
  8012. var filtered = codecs.filter(function (codec) {
  8013. return isCodecType(codec, type);
  8014. });
  8015. if (filtered.length) {
  8016. // Comma separated list of all codecs for type
  8017. level[type + "Codec"] = filtered.map(function (c) {
  8018. return c.split('/')[0];
  8019. }).join(',');
  8020. // Remove known codecs so that only unknownCodecs are left after iterating through each type
  8021. codecs = codecs.filter(function (codec) {
  8022. return filtered.indexOf(codec) === -1;
  8023. });
  8024. }
  8025. });
  8026. level.unknownCodecs = codecs;
  8027. }
  8028. function assignCodec(media, groupItem, codecProperty) {
  8029. var codecValue = groupItem[codecProperty];
  8030. if (codecValue) {
  8031. media[codecProperty] = codecValue;
  8032. }
  8033. }
  8034. function backfillProgramDateTimes(fragments, firstPdtIndex) {
  8035. var fragPrev = fragments[firstPdtIndex];
  8036. for (var i = firstPdtIndex; i--;) {
  8037. var frag = fragments[i];
  8038. // Exit on delta-playlist skipped segments
  8039. if (!frag) {
  8040. return;
  8041. }
  8042. frag.programDateTime = fragPrev.programDateTime - frag.duration * 1000;
  8043. fragPrev = frag;
  8044. }
  8045. }
  8046. function assignProgramDateTime(frag, prevFrag, programDateTimes) {
  8047. if (frag.rawProgramDateTime) {
  8048. programDateTimes.push(frag);
  8049. } else if (prevFrag != null && prevFrag.programDateTime) {
  8050. frag.programDateTime = prevFrag.endProgramDateTime;
  8051. }
  8052. }
  8053. function setInitSegment(frag, mapAttrs, id, levelkeys) {
  8054. frag.relurl = mapAttrs.URI;
  8055. if (mapAttrs.BYTERANGE) {
  8056. frag.setByteRange(mapAttrs.BYTERANGE);
  8057. }
  8058. frag.level = id;
  8059. frag.sn = 'initSegment';
  8060. if (levelkeys) {
  8061. frag.levelkeys = levelkeys;
  8062. }
  8063. frag.initSegment = null;
  8064. }
  8065. function setFragLevelKeys(frag, levelkeys, level) {
  8066. frag.levelkeys = levelkeys;
  8067. var encryptedFragments = level.encryptedFragments;
  8068. if ((!encryptedFragments.length || encryptedFragments[encryptedFragments.length - 1].levelkeys !== levelkeys) && Object.keys(levelkeys).some(function (format) {
  8069. return levelkeys[format].isCommonEncryption;
  8070. })) {
  8071. encryptedFragments.push(frag);
  8072. }
  8073. }
  8074. function assignMultipleMediaPlaylistTagOccuranceError(level, tag, result) {
  8075. level.playlistParsingError = new Error("#EXT-X-" + tag + " must not appear more than once (" + result[0] + ")");
  8076. }
  8077. function assignMustAppearBeforeSegmentsError(level, tag, result) {
  8078. level.playlistParsingError = new Error("#EXT-X-" + tag + " must appear before the first Media Segment (" + result[0] + ")");
  8079. }
  8080. function updateFromToPTS(fragFrom, fragTo) {
  8081. var fragToPTS = fragTo.startPTS;
  8082. // if we know startPTS[toIdx]
  8083. if (isFiniteNumber(fragToPTS)) {
  8084. // update fragment duration.
  8085. // it helps to fix drifts between playlist reported duration and fragment real duration
  8086. var duration = 0;
  8087. var frag;
  8088. if (fragTo.sn > fragFrom.sn) {
  8089. duration = fragToPTS - fragFrom.start;
  8090. frag = fragFrom;
  8091. } else {
  8092. duration = fragFrom.start - fragToPTS;
  8093. frag = fragTo;
  8094. }
  8095. if (frag.duration !== duration) {
  8096. frag.setDuration(duration);
  8097. }
  8098. // we dont know startPTS[toIdx]
  8099. } else if (fragTo.sn > fragFrom.sn) {
  8100. var contiguous = fragFrom.cc === fragTo.cc;
  8101. // TODO: With part-loading end/durations we need to confirm the whole fragment is loaded before using (or setting) minEndPTS
  8102. if (contiguous && fragFrom.minEndPTS) {
  8103. fragTo.setStart(fragFrom.start + (fragFrom.minEndPTS - fragFrom.start));
  8104. } else {
  8105. fragTo.setStart(fragFrom.start + fragFrom.duration);
  8106. }
  8107. } else {
  8108. fragTo.setStart(Math.max(fragFrom.start - fragTo.duration, 0));
  8109. }
  8110. }
  8111. function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
  8112. var parsedMediaDuration = endPTS - startPTS;
  8113. if (parsedMediaDuration <= 0) {
  8114. logger.warn('Fragment should have a positive duration', frag);
  8115. endPTS = startPTS + frag.duration;
  8116. endDTS = startDTS + frag.duration;
  8117. }
  8118. var maxStartPTS = startPTS;
  8119. var minEndPTS = endPTS;
  8120. var fragStartPts = frag.startPTS;
  8121. var fragEndPts = frag.endPTS;
  8122. if (isFiniteNumber(fragStartPts)) {
  8123. // delta PTS between audio and video
  8124. var deltaPTS = Math.abs(fragStartPts - startPTS);
  8125. if (!isFiniteNumber(frag.deltaPTS)) {
  8126. frag.deltaPTS = deltaPTS;
  8127. } else {
  8128. frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
  8129. }
  8130. maxStartPTS = Math.max(startPTS, fragStartPts);
  8131. startPTS = Math.min(startPTS, fragStartPts);
  8132. startDTS = Math.min(startDTS, frag.startDTS);
  8133. minEndPTS = Math.min(endPTS, fragEndPts);
  8134. endPTS = Math.max(endPTS, fragEndPts);
  8135. endDTS = Math.max(endDTS, frag.endDTS);
  8136. }
  8137. var drift = startPTS - frag.start;
  8138. if (frag.start !== 0) {
  8139. frag.setStart(startPTS);
  8140. }
  8141. frag.setDuration(endPTS - frag.start);
  8142. frag.startPTS = startPTS;
  8143. frag.maxStartPTS = maxStartPTS;
  8144. frag.startDTS = startDTS;
  8145. frag.endPTS = endPTS;
  8146. frag.minEndPTS = minEndPTS;
  8147. frag.endDTS = endDTS;
  8148. var sn = frag.sn;
  8149. // exit if sn out of range
  8150. if (!details || sn < details.startSN || sn > details.endSN) {
  8151. return 0;
  8152. }
  8153. var i;
  8154. var fragIdx = sn - details.startSN;
  8155. var fragments = details.fragments;
  8156. // update frag reference in fragments array
  8157. // rationale is that fragments array might not contain this frag object.
  8158. // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()
  8159. // if we don't update frag, we won't be able to propagate PTS info on the playlist
  8160. // resulting in invalid sliding computation
  8161. fragments[fragIdx] = frag;
  8162. // adjust fragment PTS/duration from seqnum-1 to frag 0
  8163. for (i = fragIdx; i > 0; i--) {
  8164. updateFromToPTS(fragments[i], fragments[i - 1]);
  8165. }
  8166. // adjust fragment PTS/duration from seqnum to last frag
  8167. for (i = fragIdx; i < fragments.length - 1; i++) {
  8168. updateFromToPTS(fragments[i], fragments[i + 1]);
  8169. }
  8170. if (details.fragmentHint) {
  8171. updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint);
  8172. }
  8173. details.PTSKnown = details.alignedSliding = true;
  8174. return drift;
  8175. }
  8176. function mergeDetails(oldDetails, newDetails) {
  8177. if (oldDetails === newDetails) {
  8178. return;
  8179. }
  8180. // Track the last initSegment processed. Initialize it to the last one on the timeline.
  8181. var currentInitSegment = null;
  8182. var oldFragments = oldDetails.fragments;
  8183. for (var i = oldFragments.length - 1; i >= 0; i--) {
  8184. var oldInit = oldFragments[i].initSegment;
  8185. if (oldInit) {
  8186. currentInitSegment = oldInit;
  8187. break;
  8188. }
  8189. }
  8190. if (oldDetails.fragmentHint) {
  8191. // prevent PTS and duration from being adjusted on the next hint
  8192. delete oldDetails.fragmentHint.endPTS;
  8193. }
  8194. // check if old/new playlists have fragments in common
  8195. // loop through overlapping SN and update startPTS, cc, and duration if any found
  8196. var PTSFrag;
  8197. mapFragmentIntersection(oldDetails, newDetails, function (oldFrag, newFrag, newFragIndex, newFragments) {
  8198. if ((!newDetails.startCC || newDetails.skippedSegments) && newFrag.cc !== oldFrag.cc) {
  8199. var ccOffset = oldFrag.cc - newFrag.cc;
  8200. for (var _i = newFragIndex; _i < newFragments.length; _i++) {
  8201. newFragments[_i].cc += ccOffset;
  8202. }
  8203. newDetails.endCC = newFragments[newFragments.length - 1].cc;
  8204. }
  8205. if (isFiniteNumber(oldFrag.startPTS) && isFiniteNumber(oldFrag.endPTS)) {
  8206. newFrag.setStart(newFrag.startPTS = oldFrag.startPTS);
  8207. newFrag.startDTS = oldFrag.startDTS;
  8208. newFrag.maxStartPTS = oldFrag.maxStartPTS;
  8209. newFrag.endPTS = oldFrag.endPTS;
  8210. newFrag.endDTS = oldFrag.endDTS;
  8211. newFrag.minEndPTS = oldFrag.minEndPTS;
  8212. newFrag.setDuration(oldFrag.endPTS - oldFrag.startPTS);
  8213. if (newFrag.duration) {
  8214. PTSFrag = newFrag;
  8215. }
  8216. // PTS is known when any segment has startPTS and endPTS
  8217. newDetails.PTSKnown = newDetails.alignedSliding = true;
  8218. }
  8219. if (oldFrag.hasStreams) {
  8220. newFrag.elementaryStreams = oldFrag.elementaryStreams;
  8221. }
  8222. newFrag.loader = oldFrag.loader;
  8223. if (oldFrag.hasStats) {
  8224. newFrag.stats = oldFrag.stats;
  8225. }
  8226. if (oldFrag.initSegment) {
  8227. newFrag.initSegment = oldFrag.initSegment;
  8228. currentInitSegment = oldFrag.initSegment;
  8229. }
  8230. });
  8231. var newFragments = newDetails.fragments;
  8232. var fragmentsToCheck = newDetails.fragmentHint ? newFragments.concat(newDetails.fragmentHint) : newFragments;
  8233. if (currentInitSegment) {
  8234. fragmentsToCheck.forEach(function (frag) {
  8235. var _currentInitSegment;
  8236. if (frag && (!frag.initSegment || frag.initSegment.relurl === ((_currentInitSegment = currentInitSegment) == null ? void 0 : _currentInitSegment.relurl))) {
  8237. frag.initSegment = currentInitSegment;
  8238. }
  8239. });
  8240. }
  8241. if (newDetails.skippedSegments) {
  8242. newDetails.deltaUpdateFailed = newFragments.some(function (frag) {
  8243. return !frag;
  8244. });
  8245. if (newDetails.deltaUpdateFailed) {
  8246. logger.warn('[level-helper] Previous playlist missing segments skipped in delta playlist');
  8247. for (var _i2 = newDetails.skippedSegments; _i2--;) {
  8248. newFragments.shift();
  8249. }
  8250. newDetails.startSN = newFragments[0].sn;
  8251. } else {
  8252. if (newDetails.canSkipDateRanges) {
  8253. newDetails.dateRanges = mergeDateRanges(oldDetails.dateRanges, newDetails);
  8254. }
  8255. var programDateTimes = oldDetails.fragments.filter(function (frag) {
  8256. return frag.rawProgramDateTime;
  8257. });
  8258. if (oldDetails.hasProgramDateTime && !newDetails.hasProgramDateTime) {
  8259. for (var _i3 = 1; _i3 < fragmentsToCheck.length; _i3++) {
  8260. if (fragmentsToCheck[_i3].programDateTime === null) {
  8261. assignProgramDateTime(fragmentsToCheck[_i3], fragmentsToCheck[_i3 - 1], programDateTimes);
  8262. }
  8263. }
  8264. }
  8265. mapDateRanges(programDateTimes, newDetails);
  8266. }
  8267. newDetails.endCC = newFragments[newFragments.length - 1].cc;
  8268. }
  8269. if (!newDetails.startCC) {
  8270. var _fragPriorToNewStart$;
  8271. var fragPriorToNewStart = getFragmentWithSN(oldDetails, newDetails.startSN - 1);
  8272. newDetails.startCC = (_fragPriorToNewStart$ = fragPriorToNewStart == null ? void 0 : fragPriorToNewStart.cc) != null ? _fragPriorToNewStart$ : newFragments[0].cc;
  8273. }
  8274. // Merge parts
  8275. mapPartIntersection(oldDetails.partList, newDetails.partList, function (oldPart, newPart) {
  8276. newPart.elementaryStreams = oldPart.elementaryStreams;
  8277. newPart.stats = oldPart.stats;
  8278. });
  8279. // if at least one fragment contains PTS info, recompute PTS information for all fragments
  8280. if (PTSFrag) {
  8281. updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
  8282. } else {
  8283. // ensure that delta is within oldFragments range
  8284. // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])
  8285. // in that case we also need to adjust start offset of all fragments
  8286. adjustSliding(oldDetails, newDetails);
  8287. }
  8288. if (newFragments.length) {
  8289. newDetails.totalduration = newDetails.edge - newFragments[0].start;
  8290. }
  8291. newDetails.driftStartTime = oldDetails.driftStartTime;
  8292. newDetails.driftStart = oldDetails.driftStart;
  8293. var advancedDateTime = newDetails.advancedDateTime;
  8294. if (newDetails.advanced && advancedDateTime) {
  8295. var edge = newDetails.edge;
  8296. if (!newDetails.driftStart) {
  8297. newDetails.driftStartTime = advancedDateTime;
  8298. newDetails.driftStart = edge;
  8299. }
  8300. newDetails.driftEndTime = advancedDateTime;
  8301. newDetails.driftEnd = edge;
  8302. } else {
  8303. newDetails.driftEndTime = oldDetails.driftEndTime;
  8304. newDetails.driftEnd = oldDetails.driftEnd;
  8305. newDetails.advancedDateTime = oldDetails.advancedDateTime;
  8306. }
  8307. if (newDetails.requestScheduled === -1) {
  8308. newDetails.requestScheduled = oldDetails.requestScheduled;
  8309. }
  8310. }
  8311. function mergeDateRanges(oldDateRanges, newDetails) {
  8312. var deltaDateRanges = newDetails.dateRanges,
  8313. recentlyRemovedDateranges = newDetails.recentlyRemovedDateranges;
  8314. var dateRanges = _extends({}, oldDateRanges);
  8315. if (recentlyRemovedDateranges) {
  8316. recentlyRemovedDateranges.forEach(function (id) {
  8317. delete dateRanges[id];
  8318. });
  8319. }
  8320. var mergeIds = Object.keys(dateRanges);
  8321. var mergeCount = mergeIds.length;
  8322. if (mergeCount) {
  8323. Object.keys(deltaDateRanges).forEach(function (id) {
  8324. var mergedDateRange = dateRanges[id];
  8325. var dateRange = new DateRange(deltaDateRanges[id].attr, mergedDateRange);
  8326. if (dateRange.isValid) {
  8327. dateRanges[id] = dateRange;
  8328. if (!mergedDateRange) {
  8329. dateRange.tagOrder += mergeCount;
  8330. }
  8331. } else {
  8332. logger.warn("Ignoring invalid Playlist Delta Update DATERANGE tag: \"" + stringify(deltaDateRanges[id].attr) + "\"");
  8333. }
  8334. });
  8335. }
  8336. return dateRanges;
  8337. }
  8338. function mapPartIntersection(oldParts, newParts, intersectionFn) {
  8339. if (oldParts && newParts) {
  8340. var delta = 0;
  8341. for (var i = 0, len = oldParts.length; i <= len; i++) {
  8342. var _oldPart = oldParts[i];
  8343. var _newPart = newParts[i + delta];
  8344. if (_oldPart && _newPart && _oldPart.index === _newPart.index && _oldPart.fragment.sn === _newPart.fragment.sn) {
  8345. intersectionFn(_oldPart, _newPart);
  8346. } else {
  8347. delta--;
  8348. }
  8349. }
  8350. }
  8351. }
  8352. function mapFragmentIntersection(oldDetails, newDetails, intersectionFn) {
  8353. var skippedSegments = newDetails.skippedSegments;
  8354. var start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;
  8355. var end = (oldDetails.fragmentHint ? 1 : 0) + (skippedSegments ? newDetails.endSN : Math.min(oldDetails.endSN, newDetails.endSN)) - newDetails.startSN;
  8356. var delta = newDetails.startSN - oldDetails.startSN;
  8357. var newFrags = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
  8358. var oldFrags = oldDetails.fragmentHint ? oldDetails.fragments.concat(oldDetails.fragmentHint) : oldDetails.fragments;
  8359. for (var i = start; i <= end; i++) {
  8360. var _oldFrag = oldFrags[delta + i];
  8361. var _newFrag = newFrags[i];
  8362. if (skippedSegments && !_newFrag && _oldFrag) {
  8363. // Fill in skipped segments in delta playlist
  8364. _newFrag = newDetails.fragments[i] = _oldFrag;
  8365. }
  8366. if (_oldFrag && _newFrag) {
  8367. intersectionFn(_oldFrag, _newFrag, i, newFrags);
  8368. if (_oldFrag.url && _oldFrag.url !== _newFrag.url) {
  8369. newDetails.playlistParsingError = getSequenceError("media sequence mismatch " + _newFrag.sn + ":", oldDetails, newDetails, _oldFrag, _newFrag);
  8370. return;
  8371. } else if (_oldFrag.cc !== _newFrag.cc) {
  8372. newDetails.playlistParsingError = getSequenceError("discontinuity sequence mismatch (" + _oldFrag.cc + "!=" + _newFrag.cc + ")", oldDetails, newDetails, _oldFrag, _newFrag);
  8373. return;
  8374. }
  8375. }
  8376. }
  8377. }
  8378. function getSequenceError(message, oldDetails, newDetails, oldFrag, newFrag) {
  8379. return new Error(message + " " + newFrag.url + "\nPlaylist starting @" + oldDetails.startSN + "\n" + oldDetails.m3u8 + "\n\nPlaylist starting @" + newDetails.startSN + "\n" + newDetails.m3u8);
  8380. }
  8381. function adjustSliding(oldDetails, newDetails, matchingStableVariantOrRendition) {
  8382. if (matchingStableVariantOrRendition === void 0) {
  8383. matchingStableVariantOrRendition = true;
  8384. }
  8385. var delta = newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN;
  8386. var oldFragments = oldDetails.fragments;
  8387. var advancedOrStable = delta >= 0;
  8388. var sliding = 0;
  8389. if (advancedOrStable && delta < oldFragments.length) {
  8390. sliding = oldFragments[delta].start;
  8391. } else if (advancedOrStable && newDetails.startSN === oldDetails.endSN + 1) {
  8392. sliding = oldDetails.fragmentEnd;
  8393. } else if (advancedOrStable && matchingStableVariantOrRendition) {
  8394. // align with expected position (updated playlist start sequence is past end sequence of last update)
  8395. sliding = oldDetails.fragmentStart + delta * newDetails.levelTargetDuration;
  8396. } else if (!newDetails.skippedSegments && newDetails.fragmentStart === 0) {
  8397. // align new start with old (playlist switch has a sequence with no overlap and should not be used for alignment)
  8398. sliding = oldDetails.fragmentStart;
  8399. } else {
  8400. // new details already has a sliding offset or has skipped segments
  8401. return;
  8402. }
  8403. addSliding(newDetails, sliding);
  8404. }
  8405. function addSliding(details, sliding) {
  8406. if (sliding) {
  8407. var fragments = details.fragments;
  8408. for (var i = details.skippedSegments; i < fragments.length; i++) {
  8409. fragments[i].addStart(sliding);
  8410. }
  8411. if (details.fragmentHint) {
  8412. details.fragmentHint.addStart(sliding);
  8413. }
  8414. }
  8415. }
  8416. function computeReloadInterval(newDetails, distanceToLiveEdgeMs) {
  8417. if (distanceToLiveEdgeMs === void 0) {
  8418. distanceToLiveEdgeMs = Infinity;
  8419. }
  8420. var reloadInterval = 1000 * newDetails.targetduration;
  8421. if (newDetails.updated) {
  8422. // Use last segment duration when shorter than target duration and near live edge
  8423. var fragments = newDetails.fragments;
  8424. var liveEdgeMaxTargetDurations = 4;
  8425. if (fragments.length && reloadInterval * liveEdgeMaxTargetDurations > distanceToLiveEdgeMs) {
  8426. var lastSegmentDuration = fragments[fragments.length - 1].duration * 1000;
  8427. if (lastSegmentDuration < reloadInterval) {
  8428. reloadInterval = lastSegmentDuration;
  8429. }
  8430. }
  8431. } else {
  8432. // estimate = 'miss half average';
  8433. // follow HLS Spec, If the client reloads a Playlist file and finds that it has not
  8434. // changed then it MUST wait for a period of one-half the target
  8435. // duration before retrying.
  8436. reloadInterval /= 2;
  8437. }
  8438. return Math.round(reloadInterval);
  8439. }
  8440. function getFragmentWithSN(details, sn, fragCurrent) {
  8441. if (!details) {
  8442. return null;
  8443. }
  8444. var fragment = details.fragments[sn - details.startSN];
  8445. if (fragment) {
  8446. return fragment;
  8447. }
  8448. fragment = details.fragmentHint;
  8449. if (fragment && fragment.sn === sn) {
  8450. return fragment;
  8451. }
  8452. if (sn < details.startSN && fragCurrent && fragCurrent.sn === sn) {
  8453. return fragCurrent;
  8454. }
  8455. return null;
  8456. }
  8457. function getPartWith(details, sn, partIndex) {
  8458. if (!details) {
  8459. return null;
  8460. }
  8461. return findPart(details.partList, sn, partIndex);
  8462. }
  8463. function findPart(partList, sn, partIndex) {
  8464. if (partList) {
  8465. for (var i = partList.length; i--;) {
  8466. var part = partList[i];
  8467. if (part.index === partIndex && part.fragment.sn === sn) {
  8468. return part;
  8469. }
  8470. }
  8471. }
  8472. return null;
  8473. }
  8474. function reassignFragmentLevelIndexes(levels) {
  8475. levels.forEach(function (level, index) {
  8476. var _level$details;
  8477. (_level$details = level.details) == null ? void 0 : _level$details.fragments.forEach(function (fragment) {
  8478. fragment.level = index;
  8479. if (fragment.initSegment) {
  8480. fragment.initSegment.level = index;
  8481. }
  8482. });
  8483. });
  8484. }
  8485. var PATHWAY_PENALTY_DURATION_MS = 300000;
  8486. var ContentSteeringController = /*#__PURE__*/function (_Logger) {
  8487. function ContentSteeringController(hls) {
  8488. var _this;
  8489. _this = _Logger.call(this, 'content-steering', hls.logger) || this;
  8490. _this.hls = void 0;
  8491. _this.loader = null;
  8492. _this.uri = null;
  8493. _this.pathwayId = '.';
  8494. _this._pathwayPriority = null;
  8495. _this.timeToLoad = 300;
  8496. _this.reloadTimer = -1;
  8497. _this.updated = 0;
  8498. _this.started = false;
  8499. _this.enabled = true;
  8500. _this.levels = null;
  8501. _this.audioTracks = null;
  8502. _this.subtitleTracks = null;
  8503. _this.penalizedPathways = {};
  8504. _this.hls = hls;
  8505. _this.registerListeners();
  8506. return _this;
  8507. }
  8508. _inheritsLoose(ContentSteeringController, _Logger);
  8509. var _proto = ContentSteeringController.prototype;
  8510. _proto.registerListeners = function registerListeners() {
  8511. var hls = this.hls;
  8512. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  8513. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  8514. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  8515. hls.on(Events.ERROR, this.onError, this);
  8516. };
  8517. _proto.unregisterListeners = function unregisterListeners() {
  8518. var hls = this.hls;
  8519. if (!hls) {
  8520. return;
  8521. }
  8522. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  8523. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  8524. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  8525. hls.off(Events.ERROR, this.onError, this);
  8526. };
  8527. _proto.pathways = function pathways() {
  8528. return (this.levels || []).reduce(function (pathways, level) {
  8529. if (pathways.indexOf(level.pathwayId) === -1) {
  8530. pathways.push(level.pathwayId);
  8531. }
  8532. return pathways;
  8533. }, []);
  8534. };
  8535. _proto.startLoad = function startLoad() {
  8536. this.started = true;
  8537. this.clearTimeout();
  8538. if (this.enabled && this.uri) {
  8539. if (this.updated) {
  8540. var ttl = this.timeToLoad * 1000 - (performance.now() - this.updated);
  8541. if (ttl > 0) {
  8542. this.scheduleRefresh(this.uri, ttl);
  8543. return;
  8544. }
  8545. }
  8546. this.loadSteeringManifest(this.uri);
  8547. }
  8548. };
  8549. _proto.stopLoad = function stopLoad() {
  8550. this.started = false;
  8551. if (this.loader) {
  8552. this.loader.destroy();
  8553. this.loader = null;
  8554. }
  8555. this.clearTimeout();
  8556. };
  8557. _proto.clearTimeout = function clearTimeout() {
  8558. if (this.reloadTimer !== -1) {
  8559. self.clearTimeout(this.reloadTimer);
  8560. this.reloadTimer = -1;
  8561. }
  8562. };
  8563. _proto.destroy = function destroy() {
  8564. this.unregisterListeners();
  8565. this.stopLoad();
  8566. // @ts-ignore
  8567. this.hls = null;
  8568. this.levels = this.audioTracks = this.subtitleTracks = null;
  8569. };
  8570. _proto.removeLevel = function removeLevel(levelToRemove) {
  8571. var levels = this.levels;
  8572. if (levels) {
  8573. this.levels = levels.filter(function (level) {
  8574. return level !== levelToRemove;
  8575. });
  8576. }
  8577. };
  8578. _proto.onManifestLoading = function onManifestLoading() {
  8579. this.stopLoad();
  8580. this.enabled = true;
  8581. this.timeToLoad = 300;
  8582. this.updated = 0;
  8583. this.uri = null;
  8584. this.pathwayId = '.';
  8585. this.levels = this.audioTracks = this.subtitleTracks = null;
  8586. };
  8587. _proto.onManifestLoaded = function onManifestLoaded(event, data) {
  8588. var contentSteering = data.contentSteering;
  8589. if (contentSteering === null) {
  8590. return;
  8591. }
  8592. this.pathwayId = contentSteering.pathwayId;
  8593. this.uri = contentSteering.uri;
  8594. if (this.started) {
  8595. this.startLoad();
  8596. }
  8597. };
  8598. _proto.onManifestParsed = function onManifestParsed(event, data) {
  8599. this.audioTracks = data.audioTracks;
  8600. this.subtitleTracks = data.subtitleTracks;
  8601. };
  8602. _proto.onError = function onError(event, data) {
  8603. var errorAction = data.errorAction;
  8604. if ((errorAction == null ? void 0 : errorAction.action) === NetworkErrorAction.SendAlternateToPenaltyBox && errorAction.flags === ErrorActionFlags.MoveAllAlternatesMatchingHost) {
  8605. var levels = this.levels;
  8606. var pathwayPriority = this._pathwayPriority;
  8607. var errorPathway = this.pathwayId;
  8608. if (data.context) {
  8609. var _data$context = data.context,
  8610. groupId = _data$context.groupId,
  8611. pathwayId = _data$context.pathwayId,
  8612. type = _data$context.type;
  8613. if (groupId && levels) {
  8614. errorPathway = this.getPathwayForGroupId(groupId, type, errorPathway);
  8615. } else if (pathwayId) {
  8616. errorPathway = pathwayId;
  8617. }
  8618. }
  8619. if (!(errorPathway in this.penalizedPathways)) {
  8620. this.penalizedPathways[errorPathway] = performance.now();
  8621. }
  8622. if (!pathwayPriority && levels) {
  8623. // If PATHWAY-PRIORITY was not provided, list pathways for error handling
  8624. pathwayPriority = this.pathways();
  8625. }
  8626. if (pathwayPriority && pathwayPriority.length > 1) {
  8627. this.updatePathwayPriority(pathwayPriority);
  8628. errorAction.resolved = this.pathwayId !== errorPathway;
  8629. }
  8630. if (data.details === ErrorDetails.BUFFER_APPEND_ERROR && !data.fatal) {
  8631. // Error will become fatal in buffer-controller when reaching `appendErrorMaxRetry`
  8632. // Stream-controllers are expected to reduce buffer length even if this is not deemed a QuotaExceededError
  8633. errorAction.resolved = true;
  8634. } else if (!errorAction.resolved) {
  8635. this.warn("Could not resolve " + data.details + " (\"" + data.error.message + "\") with content-steering for Pathway: " + errorPathway + " levels: " + (levels ? levels.length : levels) + " priorities: " + stringify(pathwayPriority) + " penalized: " + stringify(this.penalizedPathways));
  8636. }
  8637. }
  8638. };
  8639. _proto.filterParsedLevels = function filterParsedLevels(levels) {
  8640. // Filter levels to only include those that are in the initial pathway
  8641. this.levels = levels;
  8642. var pathwayLevels = this.getLevelsForPathway(this.pathwayId);
  8643. if (pathwayLevels.length === 0) {
  8644. var pathwayId = levels[0].pathwayId;
  8645. this.log("No levels found in Pathway " + this.pathwayId + ". Setting initial Pathway to \"" + pathwayId + "\"");
  8646. pathwayLevels = this.getLevelsForPathway(pathwayId);
  8647. this.pathwayId = pathwayId;
  8648. }
  8649. if (pathwayLevels.length !== levels.length) {
  8650. this.log("Found " + pathwayLevels.length + "/" + levels.length + " levels in Pathway \"" + this.pathwayId + "\"");
  8651. }
  8652. return pathwayLevels;
  8653. };
  8654. _proto.getLevelsForPathway = function getLevelsForPathway(pathwayId) {
  8655. if (this.levels === null) {
  8656. return [];
  8657. }
  8658. return this.levels.filter(function (level) {
  8659. return pathwayId === level.pathwayId;
  8660. });
  8661. };
  8662. _proto.updatePathwayPriority = function updatePathwayPriority(pathwayPriority) {
  8663. this._pathwayPriority = pathwayPriority;
  8664. var levels;
  8665. // Evaluate if we should remove the pathway from the penalized list
  8666. var penalizedPathways = this.penalizedPathways;
  8667. var now = performance.now();
  8668. Object.keys(penalizedPathways).forEach(function (pathwayId) {
  8669. if (now - penalizedPathways[pathwayId] > PATHWAY_PENALTY_DURATION_MS) {
  8670. delete penalizedPathways[pathwayId];
  8671. }
  8672. });
  8673. for (var i = 0; i < pathwayPriority.length; i++) {
  8674. var pathwayId = pathwayPriority[i];
  8675. if (pathwayId in penalizedPathways) {
  8676. continue;
  8677. }
  8678. if (pathwayId === this.pathwayId) {
  8679. return;
  8680. }
  8681. var selectedIndex = this.hls.nextLoadLevel;
  8682. var selectedLevel = this.hls.levels[selectedIndex];
  8683. levels = this.getLevelsForPathway(pathwayId);
  8684. if (levels.length > 0) {
  8685. this.log("Setting Pathway to \"" + pathwayId + "\"");
  8686. this.pathwayId = pathwayId;
  8687. reassignFragmentLevelIndexes(levels);
  8688. this.hls.trigger(Events.LEVELS_UPDATED, {
  8689. levels: levels
  8690. });
  8691. // Set LevelController's level to trigger LEVEL_SWITCHING which loads playlist if needed
  8692. var levelAfterChange = this.hls.levels[selectedIndex];
  8693. if (selectedLevel && levelAfterChange && this.levels) {
  8694. if (levelAfterChange.attrs['STABLE-VARIANT-ID'] !== selectedLevel.attrs['STABLE-VARIANT-ID'] && levelAfterChange.bitrate !== selectedLevel.bitrate) {
  8695. this.log("Unstable Pathways change from bitrate " + selectedLevel.bitrate + " to " + levelAfterChange.bitrate);
  8696. }
  8697. this.hls.nextLoadLevel = selectedIndex;
  8698. }
  8699. break;
  8700. }
  8701. }
  8702. };
  8703. _proto.getPathwayForGroupId = function getPathwayForGroupId(groupId, type, defaultPathway) {
  8704. var levels = this.getLevelsForPathway(defaultPathway).concat(this.levels || []);
  8705. for (var i = 0; i < levels.length; i++) {
  8706. if (type === PlaylistContextType.AUDIO_TRACK && levels[i].hasAudioGroup(groupId) || type === PlaylistContextType.SUBTITLE_TRACK && levels[i].hasSubtitleGroup(groupId)) {
  8707. return levels[i].pathwayId;
  8708. }
  8709. }
  8710. return defaultPathway;
  8711. };
  8712. _proto.clonePathways = function clonePathways(pathwayClones) {
  8713. var _this2 = this;
  8714. var levels = this.levels;
  8715. if (!levels) {
  8716. return;
  8717. }
  8718. var audioGroupCloneMap = {};
  8719. var subtitleGroupCloneMap = {};
  8720. pathwayClones.forEach(function (pathwayClone) {
  8721. var cloneId = pathwayClone.ID,
  8722. baseId = pathwayClone['BASE-ID'],
  8723. uriReplacement = pathwayClone['URI-REPLACEMENT'];
  8724. if (levels.some(function (level) {
  8725. return level.pathwayId === cloneId;
  8726. })) {
  8727. return;
  8728. }
  8729. var clonedVariants = _this2.getLevelsForPathway(baseId).map(function (baseLevel) {
  8730. var attributes = new AttrList(baseLevel.attrs);
  8731. attributes['PATHWAY-ID'] = cloneId;
  8732. var clonedAudioGroupId = attributes.AUDIO && attributes.AUDIO + "_clone_" + cloneId;
  8733. var clonedSubtitleGroupId = attributes.SUBTITLES && attributes.SUBTITLES + "_clone_" + cloneId;
  8734. if (clonedAudioGroupId) {
  8735. audioGroupCloneMap[attributes.AUDIO] = clonedAudioGroupId;
  8736. attributes.AUDIO = clonedAudioGroupId;
  8737. }
  8738. if (clonedSubtitleGroupId) {
  8739. subtitleGroupCloneMap[attributes.SUBTITLES] = clonedSubtitleGroupId;
  8740. attributes.SUBTITLES = clonedSubtitleGroupId;
  8741. }
  8742. var url = performUriReplacement(baseLevel.uri, attributes['STABLE-VARIANT-ID'], 'PER-VARIANT-URIS', uriReplacement);
  8743. var clonedLevel = new Level({
  8744. attrs: attributes,
  8745. audioCodec: baseLevel.audioCodec,
  8746. bitrate: baseLevel.bitrate,
  8747. height: baseLevel.height,
  8748. name: baseLevel.name,
  8749. url: url,
  8750. videoCodec: baseLevel.videoCodec,
  8751. width: baseLevel.width
  8752. });
  8753. if (baseLevel.audioGroups) {
  8754. for (var i = 1; i < baseLevel.audioGroups.length; i++) {
  8755. clonedLevel.addGroupId('audio', baseLevel.audioGroups[i] + "_clone_" + cloneId);
  8756. }
  8757. }
  8758. if (baseLevel.subtitleGroups) {
  8759. for (var _i = 1; _i < baseLevel.subtitleGroups.length; _i++) {
  8760. clonedLevel.addGroupId('text', baseLevel.subtitleGroups[_i] + "_clone_" + cloneId);
  8761. }
  8762. }
  8763. return clonedLevel;
  8764. });
  8765. levels.push.apply(levels, clonedVariants);
  8766. cloneRenditionGroups(_this2.audioTracks, audioGroupCloneMap, uriReplacement, cloneId);
  8767. cloneRenditionGroups(_this2.subtitleTracks, subtitleGroupCloneMap, uriReplacement, cloneId);
  8768. });
  8769. };
  8770. _proto.loadSteeringManifest = function loadSteeringManifest(uri) {
  8771. var _this3 = this;
  8772. var config = this.hls.config;
  8773. var Loader = config.loader;
  8774. if (this.loader) {
  8775. this.loader.destroy();
  8776. }
  8777. this.loader = new Loader(config);
  8778. var url;
  8779. try {
  8780. url = new self.URL(uri);
  8781. } catch (error) {
  8782. this.enabled = false;
  8783. this.log("Failed to parse Steering Manifest URI: " + uri);
  8784. return;
  8785. }
  8786. if (url.protocol !== 'data:') {
  8787. var throughput = (this.hls.bandwidthEstimate || config.abrEwmaDefaultEstimate) | 0;
  8788. url.searchParams.set('_HLS_pathway', this.pathwayId);
  8789. url.searchParams.set('_HLS_throughput', '' + throughput);
  8790. }
  8791. var context = {
  8792. responseType: 'json',
  8793. url: url.href
  8794. };
  8795. var loadPolicy = config.steeringManifestLoadPolicy.default;
  8796. var legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  8797. var loaderConfig = {
  8798. loadPolicy: loadPolicy,
  8799. timeout: loadPolicy.maxLoadTimeMs,
  8800. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  8801. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  8802. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  8803. };
  8804. var callbacks = {
  8805. onSuccess: function onSuccess(response, stats, context, networkDetails) {
  8806. _this3.log("Loaded steering manifest: \"" + url + "\"");
  8807. var steeringData = response.data;
  8808. if ((steeringData == null ? void 0 : steeringData.VERSION) !== 1) {
  8809. _this3.log("Steering VERSION " + steeringData.VERSION + " not supported!");
  8810. return;
  8811. }
  8812. _this3.updated = performance.now();
  8813. _this3.timeToLoad = steeringData.TTL;
  8814. var reloadUri = steeringData['RELOAD-URI'],
  8815. pathwayClones = steeringData['PATHWAY-CLONES'],
  8816. pathwayPriority = steeringData['PATHWAY-PRIORITY'];
  8817. if (reloadUri) {
  8818. try {
  8819. _this3.uri = new self.URL(reloadUri, url).href;
  8820. } catch (error) {
  8821. _this3.enabled = false;
  8822. _this3.log("Failed to parse Steering Manifest RELOAD-URI: " + reloadUri);
  8823. return;
  8824. }
  8825. }
  8826. _this3.scheduleRefresh(_this3.uri || context.url);
  8827. if (pathwayClones) {
  8828. _this3.clonePathways(pathwayClones);
  8829. }
  8830. var loadedSteeringData = {
  8831. steeringManifest: steeringData,
  8832. url: url.toString()
  8833. };
  8834. _this3.hls.trigger(Events.STEERING_MANIFEST_LOADED, loadedSteeringData);
  8835. if (pathwayPriority) {
  8836. _this3.updatePathwayPriority(pathwayPriority);
  8837. }
  8838. },
  8839. onError: function onError(error, context, networkDetails, stats) {
  8840. _this3.log("Error loading steering manifest: " + error.code + " " + error.text + " (" + context.url + ")");
  8841. _this3.stopLoad();
  8842. if (error.code === 410) {
  8843. _this3.enabled = false;
  8844. _this3.log("Steering manifest " + context.url + " no longer available");
  8845. return;
  8846. }
  8847. var ttl = _this3.timeToLoad * 1000;
  8848. if (error.code === 429) {
  8849. var loader = _this3.loader;
  8850. if (typeof (loader == null ? void 0 : loader.getResponseHeader) === 'function') {
  8851. var retryAfter = loader.getResponseHeader('Retry-After');
  8852. if (retryAfter) {
  8853. ttl = parseFloat(retryAfter) * 1000;
  8854. }
  8855. }
  8856. _this3.log("Steering manifest " + context.url + " rate limited");
  8857. return;
  8858. }
  8859. _this3.scheduleRefresh(_this3.uri || context.url, ttl);
  8860. },
  8861. onTimeout: function onTimeout(stats, context, networkDetails) {
  8862. _this3.log("Timeout loading steering manifest (" + context.url + ")");
  8863. _this3.scheduleRefresh(_this3.uri || context.url);
  8864. }
  8865. };
  8866. this.log("Requesting steering manifest: " + url);
  8867. this.loader.load(context, loaderConfig, callbacks);
  8868. };
  8869. _proto.scheduleRefresh = function scheduleRefresh(uri, ttlMs) {
  8870. var _this4 = this;
  8871. if (ttlMs === void 0) {
  8872. ttlMs = this.timeToLoad * 1000;
  8873. }
  8874. this.clearTimeout();
  8875. this.reloadTimer = self.setTimeout(function () {
  8876. var _this4$hls;
  8877. var media = (_this4$hls = _this4.hls) == null ? void 0 : _this4$hls.media;
  8878. if (media && !media.ended) {
  8879. _this4.loadSteeringManifest(uri);
  8880. return;
  8881. }
  8882. _this4.scheduleRefresh(uri, _this4.timeToLoad * 1000);
  8883. }, ttlMs);
  8884. };
  8885. return _createClass(ContentSteeringController, [{
  8886. key: "pathwayPriority",
  8887. get: function get() {
  8888. return this._pathwayPriority;
  8889. },
  8890. set: function set(pathwayPriority) {
  8891. this.updatePathwayPriority(pathwayPriority);
  8892. }
  8893. }]);
  8894. }(Logger);
  8895. function cloneRenditionGroups(tracks, groupCloneMap, uriReplacement, cloneId) {
  8896. if (!tracks) {
  8897. return;
  8898. }
  8899. Object.keys(groupCloneMap).forEach(function (audioGroupId) {
  8900. var clonedTracks = tracks.filter(function (track) {
  8901. return track.groupId === audioGroupId;
  8902. }).map(function (track) {
  8903. var clonedTrack = _extends({}, track);
  8904. clonedTrack.details = undefined;
  8905. clonedTrack.attrs = new AttrList(clonedTrack.attrs);
  8906. clonedTrack.url = clonedTrack.attrs.URI = performUriReplacement(track.url, track.attrs['STABLE-RENDITION-ID'], 'PER-RENDITION-URIS', uriReplacement);
  8907. clonedTrack.groupId = clonedTrack.attrs['GROUP-ID'] = groupCloneMap[audioGroupId];
  8908. clonedTrack.attrs['PATHWAY-ID'] = cloneId;
  8909. return clonedTrack;
  8910. });
  8911. tracks.push.apply(tracks, clonedTracks);
  8912. });
  8913. }
  8914. function performUriReplacement(uri, stableId, perOptionKey, uriReplacement) {
  8915. var host = uriReplacement.HOST,
  8916. params = uriReplacement.PARAMS,
  8917. perOptionUris = uriReplacement[perOptionKey];
  8918. var perVariantUri;
  8919. if (stableId) {
  8920. perVariantUri = perOptionUris == null ? void 0 : perOptionUris[stableId];
  8921. if (perVariantUri) {
  8922. uri = perVariantUri;
  8923. }
  8924. }
  8925. var url = new self.URL(uri);
  8926. if (host && !perVariantUri) {
  8927. url.host = host;
  8928. }
  8929. if (params) {
  8930. Object.keys(params).sort().forEach(function (key) {
  8931. if (key) {
  8932. url.searchParams.set(key, params[key]);
  8933. }
  8934. });
  8935. }
  8936. return url.href;
  8937. }
  8938. var FPSController = /*#__PURE__*/function () {
  8939. function FPSController(hls) {
  8940. this.hls = void 0;
  8941. this.isVideoPlaybackQualityAvailable = false;
  8942. this.timer = void 0;
  8943. this.media = null;
  8944. this.lastTime = void 0;
  8945. this.lastDroppedFrames = 0;
  8946. this.lastDecodedFrames = 0;
  8947. // stream controller must be provided as a dependency!
  8948. this.streamController = void 0;
  8949. this.hls = hls;
  8950. this.registerListeners();
  8951. }
  8952. var _proto = FPSController.prototype;
  8953. _proto.setStreamController = function setStreamController(streamController) {
  8954. this.streamController = streamController;
  8955. };
  8956. _proto.registerListeners = function registerListeners() {
  8957. this.hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  8958. this.hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  8959. };
  8960. _proto.unregisterListeners = function unregisterListeners() {
  8961. this.hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  8962. this.hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  8963. };
  8964. _proto.destroy = function destroy() {
  8965. if (this.timer) {
  8966. clearInterval(this.timer);
  8967. }
  8968. this.unregisterListeners();
  8969. this.isVideoPlaybackQualityAvailable = false;
  8970. this.media = null;
  8971. };
  8972. _proto.onMediaAttaching = function onMediaAttaching(event, data) {
  8973. var config = this.hls.config;
  8974. if (config.capLevelOnFPSDrop) {
  8975. var media = data.media instanceof self.HTMLVideoElement ? data.media : null;
  8976. this.media = media;
  8977. if (media && typeof media.getVideoPlaybackQuality === 'function') {
  8978. this.isVideoPlaybackQualityAvailable = true;
  8979. }
  8980. self.clearInterval(this.timer);
  8981. this.timer = self.setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
  8982. }
  8983. };
  8984. _proto.onMediaDetaching = function onMediaDetaching() {
  8985. this.media = null;
  8986. };
  8987. _proto.checkFPS = function checkFPS(video, decodedFrames, droppedFrames) {
  8988. var currentTime = performance.now();
  8989. if (decodedFrames) {
  8990. if (this.lastTime) {
  8991. var currentPeriod = currentTime - this.lastTime;
  8992. var currentDropped = droppedFrames - this.lastDroppedFrames;
  8993. var currentDecoded = decodedFrames - this.lastDecodedFrames;
  8994. var droppedFPS = 1000 * currentDropped / currentPeriod;
  8995. var hls = this.hls;
  8996. hls.trigger(Events.FPS_DROP, {
  8997. currentDropped: currentDropped,
  8998. currentDecoded: currentDecoded,
  8999. totalDroppedFrames: droppedFrames
  9000. });
  9001. if (droppedFPS > 0) {
  9002. // hls.logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));
  9003. if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
  9004. var currentLevel = hls.currentLevel;
  9005. hls.logger.warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);
  9006. if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
  9007. currentLevel = currentLevel - 1;
  9008. hls.trigger(Events.FPS_DROP_LEVEL_CAPPING, {
  9009. level: currentLevel,
  9010. droppedLevel: hls.currentLevel
  9011. });
  9012. hls.autoLevelCapping = currentLevel;
  9013. this.streamController.nextLevelSwitch();
  9014. }
  9015. }
  9016. }
  9017. }
  9018. this.lastTime = currentTime;
  9019. this.lastDroppedFrames = droppedFrames;
  9020. this.lastDecodedFrames = decodedFrames;
  9021. }
  9022. };
  9023. _proto.checkFPSInterval = function checkFPSInterval() {
  9024. var video = this.media;
  9025. if (video) {
  9026. if (this.isVideoPlaybackQualityAvailable) {
  9027. var videoPlaybackQuality = video.getVideoPlaybackQuality();
  9028. this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
  9029. } else {
  9030. // HTMLVideoElement doesn't include the webkit types
  9031. this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
  9032. }
  9033. }
  9034. };
  9035. return FPSController;
  9036. }();
  9037. var ChunkCache = /*#__PURE__*/function () {
  9038. function ChunkCache() {
  9039. this.chunks = [];
  9040. this.dataLength = 0;
  9041. }
  9042. var _proto = ChunkCache.prototype;
  9043. _proto.push = function push(chunk) {
  9044. this.chunks.push(chunk);
  9045. this.dataLength += chunk.length;
  9046. };
  9047. _proto.flush = function flush() {
  9048. var chunks = this.chunks,
  9049. dataLength = this.dataLength;
  9050. var result;
  9051. if (!chunks.length) {
  9052. return new Uint8Array(0);
  9053. } else if (chunks.length === 1) {
  9054. result = chunks[0];
  9055. } else {
  9056. result = concatUint8Arrays(chunks, dataLength);
  9057. }
  9058. this.reset();
  9059. return result;
  9060. };
  9061. _proto.reset = function reset() {
  9062. this.chunks.length = 0;
  9063. this.dataLength = 0;
  9064. };
  9065. return ChunkCache;
  9066. }();
  9067. function concatUint8Arrays(chunks, dataLength) {
  9068. var result = new Uint8Array(dataLength);
  9069. var offset = 0;
  9070. for (var i = 0; i < chunks.length; i++) {
  9071. var chunk = chunks[i];
  9072. result.set(chunk, offset);
  9073. offset += chunk.length;
  9074. }
  9075. return result;
  9076. }
  9077. /**
  9078. * Returns true if an ID3 footer can be found at offset in data
  9079. *
  9080. * @param data - The data to search in
  9081. * @param offset - The offset at which to start searching
  9082. *
  9083. * @returns `true` if an ID3 footer is found
  9084. *
  9085. * @internal
  9086. *
  9087. * @group ID3
  9088. */
  9089. function isId3Footer(data, offset) {
  9090. /*
  9091. * The footer is a copy of the header, but with a different identifier
  9092. */
  9093. if (offset + 10 <= data.length) {
  9094. // look for '3DI' identifier
  9095. if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) {
  9096. // check version is within range
  9097. if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {
  9098. // check size is within range
  9099. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  9100. return true;
  9101. }
  9102. }
  9103. }
  9104. }
  9105. return false;
  9106. }
  9107. /**
  9108. * Returns true if an ID3 header can be found at offset in data
  9109. *
  9110. * @param data - The data to search in
  9111. * @param offset - The offset at which to start searching
  9112. *
  9113. * @returns `true` if an ID3 header is found
  9114. *
  9115. * @internal
  9116. *
  9117. * @group ID3
  9118. */
  9119. function isId3Header(data, offset) {
  9120. /*
  9121. * http://id3.org/id3v2.3.0
  9122. * [0] = 'I'
  9123. * [1] = 'D'
  9124. * [2] = '3'
  9125. * [3,4] = {Version}
  9126. * [5] = {Flags}
  9127. * [6-9] = {ID3 Size}
  9128. *
  9129. * An ID3v2 tag can be detected with the following pattern:
  9130. * $49 44 33 yy yy xx zz zz zz zz
  9131. * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80
  9132. */
  9133. if (offset + 10 <= data.length) {
  9134. // look for 'ID3' identifier
  9135. if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) {
  9136. // check version is within range
  9137. if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {
  9138. // check size is within range
  9139. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  9140. return true;
  9141. }
  9142. }
  9143. }
  9144. }
  9145. return false;
  9146. }
  9147. /**
  9148. * Read ID3 size
  9149. *
  9150. * @param data - The data to read from
  9151. * @param offset - The offset at which to start reading
  9152. *
  9153. * @returns The size
  9154. *
  9155. * @internal
  9156. *
  9157. * @group ID3
  9158. */
  9159. function readId3Size(data, offset) {
  9160. var size = 0;
  9161. size = (data[offset] & 0x7f) << 21;
  9162. size |= (data[offset + 1] & 0x7f) << 14;
  9163. size |= (data[offset + 2] & 0x7f) << 7;
  9164. size |= data[offset + 3] & 0x7f;
  9165. return size;
  9166. }
  9167. /**
  9168. * Returns any adjacent ID3 tags found in data starting at offset, as one block of data
  9169. *
  9170. * @param data - The data to search in
  9171. * @param offset - The offset at which to start searching
  9172. *
  9173. * @returns The block of data containing any ID3 tags found
  9174. * or `undefined` if no header is found at the starting offset
  9175. *
  9176. * @internal
  9177. *
  9178. * @group ID3
  9179. */
  9180. function getId3Data(data, offset) {
  9181. var front = offset;
  9182. var length = 0;
  9183. while (isId3Header(data, offset)) {
  9184. // ID3 header is 10 bytes
  9185. length += 10;
  9186. var size = readId3Size(data, offset + 6);
  9187. length += size;
  9188. if (isId3Footer(data, offset + 10)) {
  9189. // ID3 footer is 10 bytes
  9190. length += 10;
  9191. }
  9192. offset += length;
  9193. }
  9194. if (length > 0) {
  9195. return data.subarray(front, front + length);
  9196. }
  9197. return undefined;
  9198. }
  9199. function getAudioConfig(observer, data, offset, manifestCodec) {
  9200. var adtsSamplingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  9201. var byte2 = data[offset + 2];
  9202. var adtsSamplingIndex = byte2 >> 2 & 0xf;
  9203. if (adtsSamplingIndex > 12) {
  9204. var error = new Error("invalid ADTS sampling index:" + adtsSamplingIndex);
  9205. observer.emit(Events.ERROR, Events.ERROR, {
  9206. type: ErrorTypes.MEDIA_ERROR,
  9207. details: ErrorDetails.FRAG_PARSING_ERROR,
  9208. fatal: true,
  9209. error: error,
  9210. reason: error.message
  9211. });
  9212. return;
  9213. }
  9214. // MPEG-4 Audio Object Type (profile_ObjectType+1)
  9215. var adtsObjectType = (byte2 >> 6 & 0x3) + 1;
  9216. var channelCount = data[offset + 3] >> 6 & 0x3 | (byte2 & 1) << 2;
  9217. var codec = 'mp4a.40.' + adtsObjectType;
  9218. /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config
  9219. ISO/IEC 14496-3 - Table 1.13 — Syntax of AudioSpecificConfig()
  9220. Audio Profile / Audio Object Type
  9221. 0: Null
  9222. 1: AAC Main
  9223. 2: AAC LC (Low Complexity)
  9224. 3: AAC SSR (Scalable Sample Rate)
  9225. 4: AAC LTP (Long Term Prediction)
  9226. 5: SBR (Spectral Band Replication)
  9227. 6: AAC Scalable
  9228. sampling freq
  9229. 0: 96000 Hz
  9230. 1: 88200 Hz
  9231. 2: 64000 Hz
  9232. 3: 48000 Hz
  9233. 4: 44100 Hz
  9234. 5: 32000 Hz
  9235. 6: 24000 Hz
  9236. 7: 22050 Hz
  9237. 8: 16000 Hz
  9238. 9: 12000 Hz
  9239. 10: 11025 Hz
  9240. 11: 8000 Hz
  9241. 12: 7350 Hz
  9242. 13: Reserved
  9243. 14: Reserved
  9244. 15: frequency is written explictly
  9245. Channel Configurations
  9246. These are the channel configurations:
  9247. 0: Defined in AOT Specifc Config
  9248. 1: 1 channel: front-center
  9249. 2: 2 channels: front-left, front-right
  9250. */
  9251. // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1
  9252. var samplerate = adtsSamplingRates[adtsSamplingIndex];
  9253. var aacSampleIndex = adtsSamplingIndex;
  9254. if (adtsObjectType === 5 || adtsObjectType === 29) {
  9255. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  9256. // there is a factor 2 between frame sample rate and output sample rate
  9257. // multiply frequency by 2 (see table above, equivalent to substract 3)
  9258. aacSampleIndex -= 3;
  9259. }
  9260. var config = [adtsObjectType << 3 | (aacSampleIndex & 0x0e) >> 1, (aacSampleIndex & 0x01) << 7 | channelCount << 3];
  9261. logger.log("manifest codec:" + manifestCodec + ", parsed codec:" + codec + ", channels:" + channelCount + ", rate:" + samplerate + " (ADTS object type:" + adtsObjectType + " sampling index:" + adtsSamplingIndex + ")");
  9262. return {
  9263. config: config,
  9264. samplerate: samplerate,
  9265. channelCount: channelCount,
  9266. codec: codec,
  9267. parsedCodec: codec,
  9268. manifestCodec: manifestCodec
  9269. };
  9270. }
  9271. function isHeaderPattern$1(data, offset) {
  9272. return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;
  9273. }
  9274. function getHeaderLength(data, offset) {
  9275. return data[offset + 1] & 0x01 ? 7 : 9;
  9276. }
  9277. function getFullFrameLength(data, offset) {
  9278. return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xe0) >>> 5;
  9279. }
  9280. function canGetFrameLength(data, offset) {
  9281. return offset + 5 < data.length;
  9282. }
  9283. function isHeader$1(data, offset) {
  9284. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  9285. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  9286. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  9287. return offset + 1 < data.length && isHeaderPattern$1(data, offset);
  9288. }
  9289. function canParse$1(data, offset) {
  9290. return canGetFrameLength(data, offset) && isHeaderPattern$1(data, offset) && getFullFrameLength(data, offset) <= data.length - offset;
  9291. }
  9292. function probe$1(data, offset) {
  9293. // same as isHeader but we also check that ADTS frame follows last ADTS frame
  9294. // or end of data is reached
  9295. if (isHeader$1(data, offset)) {
  9296. // ADTS header Length
  9297. var headerLength = getHeaderLength(data, offset);
  9298. if (offset + headerLength >= data.length) {
  9299. return false;
  9300. }
  9301. // ADTS frame Length
  9302. var frameLength = getFullFrameLength(data, offset);
  9303. if (frameLength <= headerLength) {
  9304. return false;
  9305. }
  9306. var newOffset = offset + frameLength;
  9307. return newOffset === data.length || isHeader$1(data, newOffset);
  9308. }
  9309. return false;
  9310. }
  9311. function initTrackConfig(track, observer, data, offset, audioCodec) {
  9312. if (!track.samplerate) {
  9313. var config = getAudioConfig(observer, data, offset, audioCodec);
  9314. if (!config) {
  9315. return;
  9316. }
  9317. _extends(track, config);
  9318. }
  9319. }
  9320. function getFrameDuration(samplerate) {
  9321. return 1024 * 90000 / samplerate;
  9322. }
  9323. function parseFrameHeader(data, offset) {
  9324. // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
  9325. var headerLength = getHeaderLength(data, offset);
  9326. if (offset + headerLength <= data.length) {
  9327. // retrieve frame size
  9328. var frameLength = getFullFrameLength(data, offset) - headerLength;
  9329. if (frameLength > 0) {
  9330. // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}`);
  9331. return {
  9332. headerLength: headerLength,
  9333. frameLength: frameLength
  9334. };
  9335. }
  9336. }
  9337. }
  9338. function appendFrame$1(track, data, offset, pts, frameIndex) {
  9339. var frameDuration = getFrameDuration(track.samplerate);
  9340. var stamp = pts + frameIndex * frameDuration;
  9341. var header = parseFrameHeader(data, offset);
  9342. var unit;
  9343. if (header) {
  9344. var frameLength = header.frameLength,
  9345. headerLength = header.headerLength;
  9346. var _length = headerLength + frameLength;
  9347. var missing = Math.max(0, offset + _length - data.length);
  9348. // logger.log(`AAC frame ${frameIndex}, pts:${stamp} length@offset/total: ${frameLength}@${offset+headerLength}/${data.byteLength} missing: ${missing}`);
  9349. if (missing) {
  9350. unit = new Uint8Array(_length - headerLength);
  9351. unit.set(data.subarray(offset + headerLength, data.length), 0);
  9352. } else {
  9353. unit = data.subarray(offset + headerLength, offset + _length);
  9354. }
  9355. var _sample = {
  9356. unit: unit,
  9357. pts: stamp
  9358. };
  9359. if (!missing) {
  9360. track.samples.push(_sample);
  9361. }
  9362. return {
  9363. sample: _sample,
  9364. length: _length,
  9365. missing: missing
  9366. };
  9367. }
  9368. // overflow incomplete header
  9369. var length = data.length - offset;
  9370. unit = new Uint8Array(length);
  9371. unit.set(data.subarray(offset, data.length), 0);
  9372. var sample = {
  9373. unit: unit,
  9374. pts: stamp
  9375. };
  9376. return {
  9377. sample: sample,
  9378. length: length,
  9379. missing: -1
  9380. };
  9381. }
  9382. /**
  9383. * Checks if the given data contains an ID3 tag.
  9384. *
  9385. * @param data - The data to check
  9386. * @param offset - The offset at which to start checking
  9387. *
  9388. * @returns `true` if an ID3 tag is found
  9389. *
  9390. * @group ID3
  9391. *
  9392. * @beta
  9393. */
  9394. function canParseId3(data, offset) {
  9395. return isId3Header(data, offset) && readId3Size(data, offset + 6) + 10 <= data.length - offset;
  9396. }
  9397. function toArrayBuffer(view) {
  9398. if (view instanceof ArrayBuffer) {
  9399. return view;
  9400. } else {
  9401. if (view.byteOffset == 0 && view.byteLength == view.buffer.byteLength) {
  9402. // This is a TypedArray over the whole buffer.
  9403. return view.buffer;
  9404. }
  9405. // This is a 'view' on the buffer. Create a new buffer that only contains
  9406. // the data. Note that since this isn't an ArrayBuffer, the 'new' call
  9407. // will allocate a new buffer to hold the copy.
  9408. return new Uint8Array(view).buffer;
  9409. }
  9410. }
  9411. function toUint8(data, offset, length) {
  9412. if (offset === void 0) {
  9413. offset = 0;
  9414. }
  9415. if (length === void 0) {
  9416. length = Infinity;
  9417. }
  9418. return view(data, offset, length, Uint8Array);
  9419. }
  9420. function view(data, offset, length, Type) {
  9421. var buffer = unsafeGetArrayBuffer(data);
  9422. var bytesPerElement = 1;
  9423. if ('BYTES_PER_ELEMENT' in Type) {
  9424. bytesPerElement = Type.BYTES_PER_ELEMENT;
  9425. }
  9426. // Absolute end of the |data| view within |buffer|.
  9427. var dataOffset = isArrayBufferView(data) ? data.byteOffset : 0;
  9428. var dataEnd = (dataOffset + data.byteLength) / bytesPerElement;
  9429. // Absolute start of the result within |buffer|.
  9430. var rawStart = (dataOffset + offset) / bytesPerElement;
  9431. var start = Math.floor(Math.max(0, Math.min(rawStart, dataEnd)));
  9432. // Absolute end of the result within |buffer|.
  9433. var end = Math.floor(Math.min(start + Math.max(length, 0), dataEnd));
  9434. return new Type(buffer, start, end - start);
  9435. }
  9436. function unsafeGetArrayBuffer(view) {
  9437. if (view instanceof ArrayBuffer) {
  9438. return view;
  9439. } else {
  9440. return view.buffer;
  9441. }
  9442. }
  9443. function isArrayBufferView(obj) {
  9444. return obj && obj.buffer instanceof ArrayBuffer && obj.byteLength !== undefined && obj.byteOffset !== undefined;
  9445. }
  9446. function decodeId3ImageFrame(frame) {
  9447. var metadataFrame = {
  9448. key: frame.type,
  9449. description: '',
  9450. data: '',
  9451. mimeType: null,
  9452. pictureType: null
  9453. };
  9454. var utf8Encoding = 0x03;
  9455. if (frame.size < 2) {
  9456. return undefined;
  9457. }
  9458. if (frame.data[0] !== utf8Encoding) {
  9459. console.log('Ignore frame with unrecognized character ' + 'encoding');
  9460. return undefined;
  9461. }
  9462. var mimeTypeEndIndex = frame.data.subarray(1).indexOf(0);
  9463. if (mimeTypeEndIndex === -1) {
  9464. return undefined;
  9465. }
  9466. var mimeType = utf8ArrayToStr(toUint8(frame.data, 1, mimeTypeEndIndex));
  9467. var pictureType = frame.data[2 + mimeTypeEndIndex];
  9468. var descriptionEndIndex = frame.data.subarray(3 + mimeTypeEndIndex).indexOf(0);
  9469. if (descriptionEndIndex === -1) {
  9470. return undefined;
  9471. }
  9472. var description = utf8ArrayToStr(toUint8(frame.data, 3 + mimeTypeEndIndex, descriptionEndIndex));
  9473. var data;
  9474. if (mimeType === '-->') {
  9475. data = utf8ArrayToStr(toUint8(frame.data, 4 + mimeTypeEndIndex + descriptionEndIndex));
  9476. } else {
  9477. data = toArrayBuffer(frame.data.subarray(4 + mimeTypeEndIndex + descriptionEndIndex));
  9478. }
  9479. metadataFrame.mimeType = mimeType;
  9480. metadataFrame.pictureType = pictureType;
  9481. metadataFrame.description = description;
  9482. metadataFrame.data = data;
  9483. return metadataFrame;
  9484. }
  9485. /**
  9486. * Decode an ID3 PRIV frame.
  9487. *
  9488. * @param frame - the ID3 PRIV frame
  9489. *
  9490. * @returns The decoded ID3 PRIV frame
  9491. *
  9492. * @internal
  9493. *
  9494. * @group ID3
  9495. */
  9496. function decodeId3PrivFrame(frame) {
  9497. /*
  9498. Format: <text string>\0<binary data>
  9499. */
  9500. if (frame.size < 2) {
  9501. return undefined;
  9502. }
  9503. var owner = utf8ArrayToStr(frame.data, true);
  9504. var privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
  9505. return {
  9506. key: frame.type,
  9507. info: owner,
  9508. data: privateData.buffer
  9509. };
  9510. }
  9511. /**
  9512. * Decodes an ID3 text frame
  9513. *
  9514. * @param frame - the ID3 text frame
  9515. *
  9516. * @returns The decoded ID3 text frame
  9517. *
  9518. * @internal
  9519. *
  9520. * @group ID3
  9521. */
  9522. function decodeId3TextFrame(frame) {
  9523. if (frame.size < 2) {
  9524. return undefined;
  9525. }
  9526. if (frame.type === 'TXXX') {
  9527. /*
  9528. Format:
  9529. [0] = {Text Encoding}
  9530. [1-?] = {Description}\0{Value}
  9531. */
  9532. var index = 1;
  9533. var description = utf8ArrayToStr(frame.data.subarray(index), true);
  9534. index += description.length + 1;
  9535. var value = utf8ArrayToStr(frame.data.subarray(index));
  9536. return {
  9537. key: frame.type,
  9538. info: description,
  9539. data: value
  9540. };
  9541. }
  9542. /*
  9543. Format:
  9544. [0] = {Text Encoding}
  9545. [1-?] = {Value}
  9546. */
  9547. var text = utf8ArrayToStr(frame.data.subarray(1));
  9548. return {
  9549. key: frame.type,
  9550. info: '',
  9551. data: text
  9552. };
  9553. }
  9554. /**
  9555. * Decode a URL frame
  9556. *
  9557. * @param frame - the ID3 URL frame
  9558. *
  9559. * @returns The decoded ID3 URL frame
  9560. *
  9561. * @internal
  9562. *
  9563. * @group ID3
  9564. */
  9565. function decodeId3UrlFrame(frame) {
  9566. if (frame.type === 'WXXX') {
  9567. /*
  9568. Format:
  9569. [0] = {Text Encoding}
  9570. [1-?] = {Description}\0{URL}
  9571. */
  9572. if (frame.size < 2) {
  9573. return undefined;
  9574. }
  9575. var index = 1;
  9576. var description = utf8ArrayToStr(frame.data.subarray(index), true);
  9577. index += description.length + 1;
  9578. var value = utf8ArrayToStr(frame.data.subarray(index));
  9579. return {
  9580. key: frame.type,
  9581. info: description,
  9582. data: value
  9583. };
  9584. }
  9585. /*
  9586. Format:
  9587. [0-?] = {URL}
  9588. */
  9589. var url = utf8ArrayToStr(frame.data);
  9590. return {
  9591. key: frame.type,
  9592. info: '',
  9593. data: url
  9594. };
  9595. }
  9596. /**
  9597. * Decode an ID3 frame.
  9598. *
  9599. * @param frame - the ID3 frame
  9600. *
  9601. * @returns The decoded ID3 frame
  9602. *
  9603. * @internal
  9604. *
  9605. * @group ID3
  9606. */
  9607. function decodeId3Frame(frame) {
  9608. if (frame.type === 'PRIV') {
  9609. return decodeId3PrivFrame(frame);
  9610. } else if (frame.type[0] === 'W') {
  9611. return decodeId3UrlFrame(frame);
  9612. } else if (frame.type === 'APIC') {
  9613. return decodeId3ImageFrame(frame);
  9614. }
  9615. return decodeId3TextFrame(frame);
  9616. }
  9617. /**
  9618. * Returns the data of an ID3 frame.
  9619. *
  9620. * @param data - The data to read from
  9621. *
  9622. * @returns The data of the ID3 frame
  9623. *
  9624. * @internal
  9625. *
  9626. * @group ID3
  9627. */
  9628. function getId3FrameData(data) {
  9629. /*
  9630. Frame ID $xx xx xx xx (four characters)
  9631. Size $xx xx xx xx
  9632. Flags $xx xx
  9633. */
  9634. var type = String.fromCharCode(data[0], data[1], data[2], data[3]);
  9635. var size = readId3Size(data, 4);
  9636. // skip frame id, size, and flags
  9637. var offset = 10;
  9638. return {
  9639. type: type,
  9640. size: size,
  9641. data: data.subarray(offset, offset + size)
  9642. };
  9643. }
  9644. var HEADER_FOOTER_SIZE = 10;
  9645. var FRAME_SIZE = 10;
  9646. /**
  9647. * Returns an array of ID3 frames found in all the ID3 tags in the id3Data
  9648. *
  9649. * @param id3Data - The ID3 data containing one or more ID3 tags
  9650. *
  9651. * @returns Array of ID3 frame objects
  9652. *
  9653. * @group ID3
  9654. *
  9655. * @beta
  9656. */
  9657. function getId3Frames(id3Data) {
  9658. var offset = 0;
  9659. var frames = [];
  9660. while (isId3Header(id3Data, offset)) {
  9661. var size = readId3Size(id3Data, offset + 6);
  9662. if (id3Data[offset + 5] >> 6 & 1) {
  9663. // skip extended header
  9664. offset += HEADER_FOOTER_SIZE;
  9665. }
  9666. // skip past ID3 header
  9667. offset += HEADER_FOOTER_SIZE;
  9668. var end = offset + size;
  9669. // loop through frames in the ID3 tag
  9670. while (offset + FRAME_SIZE < end) {
  9671. var frameData = getId3FrameData(id3Data.subarray(offset));
  9672. var frame = decodeId3Frame(frameData);
  9673. if (frame) {
  9674. frames.push(frame);
  9675. }
  9676. // skip frame header and frame data
  9677. offset += frameData.size + HEADER_FOOTER_SIZE;
  9678. }
  9679. if (isId3Footer(id3Data, offset)) {
  9680. offset += HEADER_FOOTER_SIZE;
  9681. }
  9682. }
  9683. return frames;
  9684. }
  9685. /**
  9686. * Returns true if the ID3 frame is an Elementary Stream timestamp frame
  9687. *
  9688. * @param frame - the ID3 frame
  9689. *
  9690. * @returns `true` if the ID3 frame is an Elementary Stream timestamp frame
  9691. *
  9692. * @internal
  9693. *
  9694. * @group ID3
  9695. */
  9696. function isId3TimestampFrame(frame) {
  9697. return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp';
  9698. }
  9699. /**
  9700. * Read a 33 bit timestamp from an ID3 frame.
  9701. *
  9702. * @param timeStampFrame - the ID3 frame
  9703. *
  9704. * @returns The timestamp
  9705. *
  9706. * @internal
  9707. *
  9708. * @group ID3
  9709. */
  9710. function readId3Timestamp(timeStampFrame) {
  9711. if (timeStampFrame.data.byteLength === 8) {
  9712. var data = new Uint8Array(timeStampFrame.data);
  9713. // timestamp is 33 bit expressed as a big-endian eight-octet number,
  9714. // with the upper 31 bits set to zero.
  9715. var pts33Bit = data[3] & 0x1;
  9716. var timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];
  9717. timestamp /= 45;
  9718. if (pts33Bit) {
  9719. timestamp += 47721858.84;
  9720. } // 2^32 / 90
  9721. return Math.round(timestamp);
  9722. }
  9723. return undefined;
  9724. }
  9725. /**
  9726. * Searches for the Elementary Stream timestamp found in the ID3 data chunk
  9727. *
  9728. * @param data - Block of data containing one or more ID3 tags
  9729. *
  9730. * @returns The timestamp
  9731. *
  9732. * @group ID3
  9733. *
  9734. * @beta
  9735. */
  9736. function getId3Timestamp(data) {
  9737. var frames = getId3Frames(data);
  9738. for (var i = 0; i < frames.length; i++) {
  9739. var frame = frames[i];
  9740. if (isId3TimestampFrame(frame)) {
  9741. return readId3Timestamp(frame);
  9742. }
  9743. }
  9744. return undefined;
  9745. }
  9746. var MetadataSchema = /*#__PURE__*/function (MetadataSchema) {
  9747. MetadataSchema["audioId3"] = "org.id3";
  9748. MetadataSchema["dateRange"] = "com.apple.quicktime.HLS";
  9749. MetadataSchema["emsg"] = "https://aomedia.org/emsg/ID3";
  9750. MetadataSchema["misbklv"] = "urn:misb:KLV:bin:1910.1";
  9751. return MetadataSchema;
  9752. }({});
  9753. function dummyTrack(type, inputTimeScale) {
  9754. if (type === void 0) {
  9755. type = '';
  9756. }
  9757. if (inputTimeScale === void 0) {
  9758. inputTimeScale = 90000;
  9759. }
  9760. return {
  9761. type: type,
  9762. id: -1,
  9763. pid: -1,
  9764. inputTimeScale: inputTimeScale,
  9765. sequenceNumber: -1,
  9766. samples: [],
  9767. dropped: 0
  9768. };
  9769. }
  9770. var BaseAudioDemuxer = /*#__PURE__*/function () {
  9771. function BaseAudioDemuxer() {
  9772. this._audioTrack = void 0;
  9773. this._id3Track = void 0;
  9774. this.frameIndex = 0;
  9775. this.cachedData = null;
  9776. this.basePTS = null;
  9777. this.initPTS = null;
  9778. this.lastPTS = null;
  9779. }
  9780. var _proto = BaseAudioDemuxer.prototype;
  9781. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  9782. this._id3Track = {
  9783. type: 'id3',
  9784. id: 3,
  9785. pid: -1,
  9786. inputTimeScale: 90000,
  9787. sequenceNumber: 0,
  9788. samples: [],
  9789. dropped: 0
  9790. };
  9791. };
  9792. _proto.resetTimeStamp = function resetTimeStamp(deaultTimestamp) {
  9793. this.initPTS = deaultTimestamp;
  9794. this.resetContiguity();
  9795. };
  9796. _proto.resetContiguity = function resetContiguity() {
  9797. this.basePTS = null;
  9798. this.lastPTS = null;
  9799. this.frameIndex = 0;
  9800. };
  9801. _proto.canParse = function canParse(data, offset) {
  9802. return false;
  9803. };
  9804. _proto.appendFrame = function appendFrame(track, data, offset) {}
  9805. // feed incoming data to the front of the parsing pipeline
  9806. ;
  9807. _proto.demux = function demux(data, timeOffset) {
  9808. if (this.cachedData) {
  9809. data = appendUint8Array(this.cachedData, data);
  9810. this.cachedData = null;
  9811. }
  9812. var id3Data = getId3Data(data, 0);
  9813. var offset = id3Data ? id3Data.length : 0;
  9814. var lastDataIndex;
  9815. var track = this._audioTrack;
  9816. var id3Track = this._id3Track;
  9817. var timestamp = id3Data ? getId3Timestamp(id3Data) : undefined;
  9818. var length = data.length;
  9819. if (this.basePTS === null || this.frameIndex === 0 && isFiniteNumber(timestamp)) {
  9820. this.basePTS = initPTSFn(timestamp, timeOffset, this.initPTS);
  9821. this.lastPTS = this.basePTS;
  9822. }
  9823. if (this.lastPTS === null) {
  9824. this.lastPTS = this.basePTS;
  9825. }
  9826. // more expressive than alternative: id3Data?.length
  9827. if (id3Data && id3Data.length > 0) {
  9828. id3Track.samples.push({
  9829. pts: this.lastPTS,
  9830. dts: this.lastPTS,
  9831. data: id3Data,
  9832. type: MetadataSchema.audioId3,
  9833. duration: Number.POSITIVE_INFINITY
  9834. });
  9835. }
  9836. while (offset < length) {
  9837. if (this.canParse(data, offset)) {
  9838. var frame = this.appendFrame(track, data, offset);
  9839. if (frame) {
  9840. this.frameIndex++;
  9841. this.lastPTS = frame.sample.pts;
  9842. offset += frame.length;
  9843. lastDataIndex = offset;
  9844. } else {
  9845. offset = length;
  9846. }
  9847. } else if (canParseId3(data, offset)) {
  9848. // after a canParse, a call to getId3Data *should* always returns some data
  9849. id3Data = getId3Data(data, offset);
  9850. id3Track.samples.push({
  9851. pts: this.lastPTS,
  9852. dts: this.lastPTS,
  9853. data: id3Data,
  9854. type: MetadataSchema.audioId3,
  9855. duration: Number.POSITIVE_INFINITY
  9856. });
  9857. offset += id3Data.length;
  9858. lastDataIndex = offset;
  9859. } else {
  9860. offset++;
  9861. }
  9862. if (offset === length && lastDataIndex !== length) {
  9863. var partialData = data.slice(lastDataIndex);
  9864. if (this.cachedData) {
  9865. this.cachedData = appendUint8Array(this.cachedData, partialData);
  9866. } else {
  9867. this.cachedData = partialData;
  9868. }
  9869. }
  9870. }
  9871. return {
  9872. audioTrack: track,
  9873. videoTrack: dummyTrack(),
  9874. id3Track: id3Track,
  9875. textTrack: dummyTrack()
  9876. };
  9877. };
  9878. _proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
  9879. return Promise.reject(new Error("[" + this + "] This demuxer does not support Sample-AES decryption"));
  9880. };
  9881. _proto.flush = function flush(timeOffset) {
  9882. // Parse cache in case of remaining frames.
  9883. var cachedData = this.cachedData;
  9884. if (cachedData) {
  9885. this.cachedData = null;
  9886. this.demux(cachedData, 0);
  9887. }
  9888. return {
  9889. audioTrack: this._audioTrack,
  9890. videoTrack: dummyTrack(),
  9891. id3Track: this._id3Track,
  9892. textTrack: dummyTrack()
  9893. };
  9894. };
  9895. _proto.destroy = function destroy() {
  9896. this.cachedData = null;
  9897. // @ts-ignore
  9898. this._audioTrack = this._id3Track = undefined;
  9899. };
  9900. return BaseAudioDemuxer;
  9901. }();
  9902. /**
  9903. * Initialize PTS
  9904. * <p>
  9905. * use timestamp unless it is undefined, NaN or Infinity
  9906. * </p>
  9907. */
  9908. var initPTSFn = function initPTSFn(timestamp, timeOffset, initPTS) {
  9909. if (isFiniteNumber(timestamp)) {
  9910. return timestamp * 90;
  9911. }
  9912. var init90kHz = initPTS ? initPTS.baseTime * 90000 / initPTS.timescale : 0;
  9913. return timeOffset * 90000 + init90kHz;
  9914. };
  9915. /**
  9916. * MPEG parser helper
  9917. */
  9918. var chromeVersion$1 = null;
  9919. 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];
  9920. var SamplingRateMap = [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000];
  9921. var SamplesCoefficients = [
  9922. // MPEG 2.5
  9923. [0,
  9924. // Reserved
  9925. 72,
  9926. // Layer3
  9927. 144,
  9928. // Layer2
  9929. 12 // Layer1
  9930. ],
  9931. // Reserved
  9932. [0,
  9933. // Reserved
  9934. 0,
  9935. // Layer3
  9936. 0,
  9937. // Layer2
  9938. 0 // Layer1
  9939. ],
  9940. // MPEG 2
  9941. [0,
  9942. // Reserved
  9943. 72,
  9944. // Layer3
  9945. 144,
  9946. // Layer2
  9947. 12 // Layer1
  9948. ],
  9949. // MPEG 1
  9950. [0,
  9951. // Reserved
  9952. 144,
  9953. // Layer3
  9954. 144,
  9955. // Layer2
  9956. 12 // Layer1
  9957. ]];
  9958. var BytesInSlot = [0,
  9959. // Reserved
  9960. 1,
  9961. // Layer3
  9962. 1,
  9963. // Layer2
  9964. 4 // Layer1
  9965. ];
  9966. function appendFrame(track, data, offset, pts, frameIndex) {
  9967. // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference
  9968. if (offset + 24 > data.length) {
  9969. return;
  9970. }
  9971. var header = parseHeader(data, offset);
  9972. if (header && offset + header.frameLength <= data.length) {
  9973. var frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;
  9974. var stamp = pts + frameIndex * frameDuration;
  9975. var sample = {
  9976. unit: data.subarray(offset, offset + header.frameLength),
  9977. pts: stamp,
  9978. dts: stamp
  9979. };
  9980. track.config = [];
  9981. track.channelCount = header.channelCount;
  9982. track.samplerate = header.sampleRate;
  9983. track.samples.push(sample);
  9984. return {
  9985. sample: sample,
  9986. length: header.frameLength,
  9987. missing: 0
  9988. };
  9989. }
  9990. }
  9991. function parseHeader(data, offset) {
  9992. var mpegVersion = data[offset + 1] >> 3 & 3;
  9993. var mpegLayer = data[offset + 1] >> 1 & 3;
  9994. var bitRateIndex = data[offset + 2] >> 4 & 15;
  9995. var sampleRateIndex = data[offset + 2] >> 2 & 3;
  9996. if (mpegVersion !== 1 && bitRateIndex !== 0 && bitRateIndex !== 15 && sampleRateIndex !== 3) {
  9997. var paddingBit = data[offset + 2] >> 1 & 1;
  9998. var channelMode = data[offset + 3] >> 6;
  9999. var columnInBitrates = mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4;
  10000. var bitRate = BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1000;
  10001. var columnInSampleRates = mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2;
  10002. var sampleRate = SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex];
  10003. var channelCount = channelMode === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)
  10004. var sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer];
  10005. var bytesInSlot = BytesInSlot[mpegLayer];
  10006. var samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
  10007. var frameLength = Math.floor(sampleCoefficient * bitRate / sampleRate + paddingBit) * bytesInSlot;
  10008. if (chromeVersion$1 === null) {
  10009. var userAgent = navigator.userAgent || '';
  10010. var result = userAgent.match(/Chrome\/(\d+)/i);
  10011. chromeVersion$1 = result ? parseInt(result[1]) : 0;
  10012. }
  10013. var needChromeFix = !!chromeVersion$1 && chromeVersion$1 <= 87;
  10014. if (needChromeFix && mpegLayer === 2 && bitRate >= 224000 && channelMode === 0) {
  10015. // Work around bug in Chromium by setting channelMode to dual-channel (01) instead of stereo (00)
  10016. data[offset + 3] = data[offset + 3] | 0x80;
  10017. }
  10018. return {
  10019. sampleRate: sampleRate,
  10020. channelCount: channelCount,
  10021. frameLength: frameLength,
  10022. samplesPerFrame: samplesPerFrame
  10023. };
  10024. }
  10025. }
  10026. function isHeaderPattern(data, offset) {
  10027. return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;
  10028. }
  10029. function isHeader(data, offset) {
  10030. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  10031. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  10032. // More info http://www.mp3-tech.org/programmer/frame_header.html
  10033. return offset + 1 < data.length && isHeaderPattern(data, offset);
  10034. }
  10035. function canParse(data, offset) {
  10036. var headerSize = 4;
  10037. return isHeaderPattern(data, offset) && headerSize <= data.length - offset;
  10038. }
  10039. function probe(data, offset) {
  10040. // same as isHeader but we also check that MPEG frame follows last MPEG frame
  10041. // or end of data is reached
  10042. if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
  10043. // MPEG header Length
  10044. var headerLength = 4;
  10045. // MPEG frame Length
  10046. var header = parseHeader(data, offset);
  10047. var frameLength = headerLength;
  10048. if (header != null && header.frameLength) {
  10049. frameLength = header.frameLength;
  10050. }
  10051. var newOffset = offset + frameLength;
  10052. return newOffset === data.length || isHeader(data, newOffset);
  10053. }
  10054. return false;
  10055. }
  10056. var AACDemuxer = /*#__PURE__*/function (_BaseAudioDemuxer) {
  10057. function AACDemuxer(observer, config) {
  10058. var _this;
  10059. _this = _BaseAudioDemuxer.call(this) || this;
  10060. _this.observer = void 0;
  10061. _this.config = void 0;
  10062. _this.observer = observer;
  10063. _this.config = config;
  10064. return _this;
  10065. }
  10066. _inheritsLoose(AACDemuxer, _BaseAudioDemuxer);
  10067. var _proto = AACDemuxer.prototype;
  10068. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  10069. _BaseAudioDemuxer.prototype.resetInitSegment.call(this, initSegment, audioCodec, videoCodec, trackDuration);
  10070. this._audioTrack = {
  10071. container: 'audio/adts',
  10072. type: 'audio',
  10073. id: 2,
  10074. pid: -1,
  10075. sequenceNumber: 0,
  10076. segmentCodec: 'aac',
  10077. samples: [],
  10078. manifestCodec: audioCodec,
  10079. duration: trackDuration,
  10080. inputTimeScale: 90000,
  10081. dropped: 0
  10082. };
  10083. }
  10084. // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS
  10085. ;
  10086. AACDemuxer.probe = function probe$2(data, logger) {
  10087. if (!data) {
  10088. return false;
  10089. }
  10090. // Check for the ADTS sync word
  10091. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  10092. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  10093. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  10094. var id3Data = getId3Data(data, 0);
  10095. var offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  10096. if (probe(data, offset)) {
  10097. return false;
  10098. }
  10099. for (var length = data.length; offset < length; offset++) {
  10100. if (probe$1(data, offset)) {
  10101. logger.log('ADTS sync word found !');
  10102. return true;
  10103. }
  10104. }
  10105. return false;
  10106. };
  10107. _proto.canParse = function canParse(data, offset) {
  10108. return canParse$1(data, offset);
  10109. };
  10110. _proto.appendFrame = function appendFrame(track, data, offset) {
  10111. initTrackConfig(track, this.observer, data, offset, track.manifestCodec);
  10112. var frame = appendFrame$1(track, data, offset, this.basePTS, this.frameIndex);
  10113. if (frame && frame.missing === 0) {
  10114. return frame;
  10115. }
  10116. };
  10117. return AACDemuxer;
  10118. }(BaseAudioDemuxer);
  10119. var getAudioBSID = function getAudioBSID(data, offset) {
  10120. // check the bsid to confirm ac-3 | ec-3
  10121. var bsid = 0;
  10122. var numBits = 5;
  10123. offset += numBits;
  10124. var temp = new Uint32Array(1); // unsigned 32 bit for temporary storage
  10125. var mask = new Uint32Array(1); // unsigned 32 bit mask value
  10126. var _byte = new Uint8Array(1); // unsigned 8 bit for temporary storage
  10127. while (numBits > 0) {
  10128. _byte[0] = data[offset];
  10129. // read remaining bits, upto 8 bits at a time
  10130. var bits = Math.min(numBits, 8);
  10131. var shift = 8 - bits;
  10132. mask[0] = 0xff000000 >>> 24 + shift << shift;
  10133. temp[0] = (_byte[0] & mask[0]) >> shift;
  10134. bsid = !bsid ? temp[0] : bsid << bits | temp[0];
  10135. offset += 1;
  10136. numBits -= bits;
  10137. }
  10138. return bsid;
  10139. };
  10140. var MP3Demuxer = /*#__PURE__*/function (_BaseAudioDemuxer) {
  10141. function MP3Demuxer() {
  10142. return _BaseAudioDemuxer.apply(this, arguments) || this;
  10143. }
  10144. _inheritsLoose(MP3Demuxer, _BaseAudioDemuxer);
  10145. var _proto = MP3Demuxer.prototype;
  10146. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  10147. _BaseAudioDemuxer.prototype.resetInitSegment.call(this, initSegment, audioCodec, videoCodec, trackDuration);
  10148. this._audioTrack = {
  10149. container: 'audio/mpeg',
  10150. type: 'audio',
  10151. id: 2,
  10152. pid: -1,
  10153. sequenceNumber: 0,
  10154. segmentCodec: 'mp3',
  10155. samples: [],
  10156. manifestCodec: audioCodec,
  10157. duration: trackDuration,
  10158. inputTimeScale: 90000,
  10159. dropped: 0
  10160. };
  10161. };
  10162. MP3Demuxer.probe = function probe$1(data) {
  10163. if (!data) {
  10164. return false;
  10165. }
  10166. // check if data contains ID3 timestamp and MPEG sync word
  10167. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  10168. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  10169. // More info http://www.mp3-tech.org/programmer/frame_header.html
  10170. var id3Data = getId3Data(data, 0);
  10171. var offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  10172. // Check for ac-3|ec-3 sync bytes and return false if present
  10173. if (id3Data && data[offset] === 0x0b && data[offset + 1] === 0x77 && getId3Timestamp(id3Data) !== undefined &&
  10174. // check the bsid to confirm ac-3 or ec-3 (not mp3)
  10175. getAudioBSID(data, offset) <= 16) {
  10176. return false;
  10177. }
  10178. for (var length = data.length; offset < length; offset++) {
  10179. if (probe(data, offset)) {
  10180. logger.log('MPEG Audio sync word found !');
  10181. return true;
  10182. }
  10183. }
  10184. return false;
  10185. };
  10186. _proto.canParse = function canParse$1(data, offset) {
  10187. return canParse(data, offset);
  10188. };
  10189. _proto.appendFrame = function appendFrame$1(track, data, offset) {
  10190. if (this.basePTS === null) {
  10191. return;
  10192. }
  10193. return appendFrame(track, data, offset, this.basePTS, this.frameIndex);
  10194. };
  10195. return MP3Demuxer;
  10196. }(BaseAudioDemuxer);
  10197. var AESCrypto = /*#__PURE__*/function () {
  10198. function AESCrypto(subtle, iv, aesMode) {
  10199. this.subtle = void 0;
  10200. this.aesIV = void 0;
  10201. this.aesMode = void 0;
  10202. this.subtle = subtle;
  10203. this.aesIV = iv;
  10204. this.aesMode = aesMode;
  10205. }
  10206. var _proto = AESCrypto.prototype;
  10207. _proto.decrypt = function decrypt(data, key) {
  10208. switch (this.aesMode) {
  10209. case DecrypterAesMode.cbc:
  10210. return this.subtle.decrypt({
  10211. name: 'AES-CBC',
  10212. iv: this.aesIV
  10213. }, key, data);
  10214. case DecrypterAesMode.ctr:
  10215. return this.subtle.decrypt({
  10216. name: 'AES-CTR',
  10217. counter: this.aesIV,
  10218. length: 64
  10219. },
  10220. //64 : NIST SP800-38A standard suggests that the counter should occupy half of the counter block
  10221. key, data);
  10222. default:
  10223. throw new Error("[AESCrypto] invalid aes mode " + this.aesMode);
  10224. }
  10225. };
  10226. return AESCrypto;
  10227. }();
  10228. // PKCS7
  10229. function removePadding(array) {
  10230. var outputBytes = array.byteLength;
  10231. var paddingBytes = outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1);
  10232. if (paddingBytes) {
  10233. return array.slice(0, outputBytes - paddingBytes);
  10234. }
  10235. return array;
  10236. }
  10237. var AESDecryptor = /*#__PURE__*/function () {
  10238. function AESDecryptor() {
  10239. this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
  10240. this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  10241. this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  10242. this.sBox = new Uint32Array(256);
  10243. this.invSBox = new Uint32Array(256);
  10244. this.key = new Uint32Array(0);
  10245. this.ksRows = 0;
  10246. this.keySize = 0;
  10247. this.keySchedule = void 0;
  10248. this.invKeySchedule = void 0;
  10249. this.initTable();
  10250. }
  10251. // Using view.getUint32() also swaps the byte order.
  10252. var _proto = AESDecryptor.prototype;
  10253. _proto.uint8ArrayToUint32Array_ = function uint8ArrayToUint32Array_(arrayBuffer) {
  10254. var view = new DataView(arrayBuffer);
  10255. var newArray = new Uint32Array(4);
  10256. for (var i = 0; i < 4; i++) {
  10257. newArray[i] = view.getUint32(i * 4);
  10258. }
  10259. return newArray;
  10260. };
  10261. _proto.initTable = function initTable() {
  10262. var sBox = this.sBox;
  10263. var invSBox = this.invSBox;
  10264. var subMix = this.subMix;
  10265. var subMix0 = subMix[0];
  10266. var subMix1 = subMix[1];
  10267. var subMix2 = subMix[2];
  10268. var subMix3 = subMix[3];
  10269. var invSubMix = this.invSubMix;
  10270. var invSubMix0 = invSubMix[0];
  10271. var invSubMix1 = invSubMix[1];
  10272. var invSubMix2 = invSubMix[2];
  10273. var invSubMix3 = invSubMix[3];
  10274. var d = new Uint32Array(256);
  10275. var x = 0;
  10276. var xi = 0;
  10277. var i = 0;
  10278. for (i = 0; i < 256; i++) {
  10279. if (i < 128) {
  10280. d[i] = i << 1;
  10281. } else {
  10282. d[i] = i << 1 ^ 0x11b;
  10283. }
  10284. }
  10285. for (i = 0; i < 256; i++) {
  10286. var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
  10287. sx = sx >>> 8 ^ sx & 0xff ^ 0x63;
  10288. sBox[x] = sx;
  10289. invSBox[sx] = x;
  10290. // Compute multiplication
  10291. var x2 = d[x];
  10292. var x4 = d[x2];
  10293. var x8 = d[x4];
  10294. // Compute sub/invSub bytes, mix columns tables
  10295. var t = d[sx] * 0x101 ^ sx * 0x1010100;
  10296. subMix0[x] = t << 24 | t >>> 8;
  10297. subMix1[x] = t << 16 | t >>> 16;
  10298. subMix2[x] = t << 8 | t >>> 24;
  10299. subMix3[x] = t;
  10300. // Compute inv sub bytes, inv mix columns tables
  10301. t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  10302. invSubMix0[sx] = t << 24 | t >>> 8;
  10303. invSubMix1[sx] = t << 16 | t >>> 16;
  10304. invSubMix2[sx] = t << 8 | t >>> 24;
  10305. invSubMix3[sx] = t;
  10306. // Compute next counter
  10307. if (!x) {
  10308. x = xi = 1;
  10309. } else {
  10310. x = x2 ^ d[d[d[x8 ^ x2]]];
  10311. xi ^= d[d[xi]];
  10312. }
  10313. }
  10314. };
  10315. _proto.expandKey = function expandKey(keyBuffer) {
  10316. // convert keyBuffer to Uint32Array
  10317. var key = this.uint8ArrayToUint32Array_(keyBuffer);
  10318. var sameKey = true;
  10319. var offset = 0;
  10320. while (offset < key.length && sameKey) {
  10321. sameKey = key[offset] === this.key[offset];
  10322. offset++;
  10323. }
  10324. if (sameKey) {
  10325. return;
  10326. }
  10327. this.key = key;
  10328. var keySize = this.keySize = key.length;
  10329. if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
  10330. throw new Error('Invalid aes key size=' + keySize);
  10331. }
  10332. var ksRows = this.ksRows = (keySize + 6 + 1) * 4;
  10333. var ksRow;
  10334. var invKsRow;
  10335. var keySchedule = this.keySchedule = new Uint32Array(ksRows);
  10336. var invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
  10337. var sbox = this.sBox;
  10338. var rcon = this.rcon;
  10339. var invSubMix = this.invSubMix;
  10340. var invSubMix0 = invSubMix[0];
  10341. var invSubMix1 = invSubMix[1];
  10342. var invSubMix2 = invSubMix[2];
  10343. var invSubMix3 = invSubMix[3];
  10344. var prev;
  10345. var t;
  10346. for (ksRow = 0; ksRow < ksRows; ksRow++) {
  10347. if (ksRow < keySize) {
  10348. prev = keySchedule[ksRow] = key[ksRow];
  10349. continue;
  10350. }
  10351. t = prev;
  10352. if (ksRow % keySize === 0) {
  10353. // Rot word
  10354. t = t << 8 | t >>> 24;
  10355. // Sub word
  10356. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  10357. // Mix Rcon
  10358. t ^= rcon[ksRow / keySize | 0] << 24;
  10359. } else if (keySize > 6 && ksRow % keySize === 4) {
  10360. // Sub word
  10361. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  10362. }
  10363. keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
  10364. }
  10365. for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
  10366. ksRow = ksRows - invKsRow;
  10367. if (invKsRow & 3) {
  10368. t = keySchedule[ksRow];
  10369. } else {
  10370. t = keySchedule[ksRow - 4];
  10371. }
  10372. if (invKsRow < 4 || ksRow <= 4) {
  10373. invKeySchedule[invKsRow] = t;
  10374. } else {
  10375. invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]];
  10376. }
  10377. invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
  10378. }
  10379. }
  10380. // Adding this as a method greatly improves performance.
  10381. ;
  10382. _proto.networkToHostOrderSwap = function networkToHostOrderSwap(word) {
  10383. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  10384. };
  10385. _proto.decrypt = function decrypt(inputArrayBuffer, offset, aesIV) {
  10386. var nRounds = this.keySize + 6;
  10387. var invKeySchedule = this.invKeySchedule;
  10388. var invSBOX = this.invSBox;
  10389. var invSubMix = this.invSubMix;
  10390. var invSubMix0 = invSubMix[0];
  10391. var invSubMix1 = invSubMix[1];
  10392. var invSubMix2 = invSubMix[2];
  10393. var invSubMix3 = invSubMix[3];
  10394. var initVector = this.uint8ArrayToUint32Array_(aesIV);
  10395. var initVector0 = initVector[0];
  10396. var initVector1 = initVector[1];
  10397. var initVector2 = initVector[2];
  10398. var initVector3 = initVector[3];
  10399. var inputInt32 = new Int32Array(inputArrayBuffer);
  10400. var outputInt32 = new Int32Array(inputInt32.length);
  10401. var t0, t1, t2, t3;
  10402. var s0, s1, s2, s3;
  10403. var inputWords0, inputWords1, inputWords2, inputWords3;
  10404. var ksRow, i;
  10405. var swapWord = this.networkToHostOrderSwap;
  10406. while (offset < inputInt32.length) {
  10407. inputWords0 = swapWord(inputInt32[offset]);
  10408. inputWords1 = swapWord(inputInt32[offset + 1]);
  10409. inputWords2 = swapWord(inputInt32[offset + 2]);
  10410. inputWords3 = swapWord(inputInt32[offset + 3]);
  10411. s0 = inputWords0 ^ invKeySchedule[0];
  10412. s1 = inputWords3 ^ invKeySchedule[1];
  10413. s2 = inputWords2 ^ invKeySchedule[2];
  10414. s3 = inputWords1 ^ invKeySchedule[3];
  10415. ksRow = 4;
  10416. // Iterate through the rounds of decryption
  10417. for (i = 1; i < nRounds; i++) {
  10418. t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];
  10419. t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  10420. t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  10421. t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  10422. // Update state
  10423. s0 = t0;
  10424. s1 = t1;
  10425. s2 = t2;
  10426. s3 = t3;
  10427. ksRow = ksRow + 4;
  10428. }
  10429. // Shift rows, sub bytes, add round key
  10430. t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow];
  10431. t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  10432. t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  10433. t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  10434. // Write
  10435. outputInt32[offset] = swapWord(t0 ^ initVector0);
  10436. outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
  10437. outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
  10438. outputInt32[offset + 3] = swapWord(t1 ^ initVector3);
  10439. // reset initVector to last 4 unsigned int
  10440. initVector0 = inputWords0;
  10441. initVector1 = inputWords1;
  10442. initVector2 = inputWords2;
  10443. initVector3 = inputWords3;
  10444. offset = offset + 4;
  10445. }
  10446. return outputInt32.buffer;
  10447. };
  10448. return AESDecryptor;
  10449. }();
  10450. var FastAESKey = /*#__PURE__*/function () {
  10451. function FastAESKey(subtle, key, aesMode) {
  10452. this.subtle = void 0;
  10453. this.key = void 0;
  10454. this.aesMode = void 0;
  10455. this.subtle = subtle;
  10456. this.key = key;
  10457. this.aesMode = aesMode;
  10458. }
  10459. var _proto = FastAESKey.prototype;
  10460. _proto.expandKey = function expandKey() {
  10461. var subtleAlgoName = getSubtleAlgoName(this.aesMode);
  10462. return this.subtle.importKey('raw', this.key, {
  10463. name: subtleAlgoName
  10464. }, false, ['encrypt', 'decrypt']);
  10465. };
  10466. return FastAESKey;
  10467. }();
  10468. function getSubtleAlgoName(aesMode) {
  10469. switch (aesMode) {
  10470. case DecrypterAesMode.cbc:
  10471. return 'AES-CBC';
  10472. case DecrypterAesMode.ctr:
  10473. return 'AES-CTR';
  10474. default:
  10475. throw new Error("[FastAESKey] invalid aes mode " + aesMode);
  10476. }
  10477. }
  10478. var CHUNK_SIZE = 16; // 16 bytes, 128 bits
  10479. var Decrypter = /*#__PURE__*/function () {
  10480. function Decrypter(config, _temp) {
  10481. var _ref = _temp === void 0 ? {} : _temp,
  10482. _ref$removePKCS7Paddi = _ref.removePKCS7Padding,
  10483. removePKCS7Padding = _ref$removePKCS7Paddi === void 0 ? true : _ref$removePKCS7Paddi;
  10484. this.logEnabled = true;
  10485. this.removePKCS7Padding = void 0;
  10486. this.subtle = null;
  10487. this.softwareDecrypter = null;
  10488. this.key = null;
  10489. this.fastAesKey = null;
  10490. this.remainderData = null;
  10491. this.currentIV = null;
  10492. this.currentResult = null;
  10493. this.useSoftware = void 0;
  10494. this.enableSoftwareAES = void 0;
  10495. this.enableSoftwareAES = config.enableSoftwareAES;
  10496. this.removePKCS7Padding = removePKCS7Padding;
  10497. // built in decryptor expects PKCS7 padding
  10498. if (removePKCS7Padding) {
  10499. try {
  10500. var browserCrypto = self.crypto;
  10501. if (browserCrypto) {
  10502. this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
  10503. }
  10504. } catch (e) {
  10505. /* no-op */
  10506. }
  10507. }
  10508. this.useSoftware = !this.subtle;
  10509. }
  10510. var _proto = Decrypter.prototype;
  10511. _proto.destroy = function destroy() {
  10512. this.subtle = null;
  10513. this.softwareDecrypter = null;
  10514. this.key = null;
  10515. this.fastAesKey = null;
  10516. this.remainderData = null;
  10517. this.currentIV = null;
  10518. this.currentResult = null;
  10519. };
  10520. _proto.isSync = function isSync() {
  10521. return this.useSoftware;
  10522. };
  10523. _proto.flush = function flush() {
  10524. var currentResult = this.currentResult,
  10525. remainderData = this.remainderData;
  10526. if (!currentResult || remainderData) {
  10527. this.reset();
  10528. return null;
  10529. }
  10530. var data = new Uint8Array(currentResult);
  10531. this.reset();
  10532. if (this.removePKCS7Padding) {
  10533. return removePadding(data);
  10534. }
  10535. return data;
  10536. };
  10537. _proto.reset = function reset() {
  10538. this.currentResult = null;
  10539. this.currentIV = null;
  10540. this.remainderData = null;
  10541. if (this.softwareDecrypter) {
  10542. this.softwareDecrypter = null;
  10543. }
  10544. };
  10545. _proto.decrypt = function decrypt(data, key, iv, aesMode) {
  10546. var _this = this;
  10547. if (this.useSoftware) {
  10548. return new Promise(function (resolve, reject) {
  10549. var dataView = ArrayBuffer.isView(data) ? data : new Uint8Array(data);
  10550. _this.softwareDecrypt(dataView, key, iv, aesMode);
  10551. var decryptResult = _this.flush();
  10552. if (decryptResult) {
  10553. resolve(decryptResult.buffer);
  10554. } else {
  10555. reject(new Error('[softwareDecrypt] Failed to decrypt data'));
  10556. }
  10557. });
  10558. }
  10559. return this.webCryptoDecrypt(new Uint8Array(data), key, iv, aesMode);
  10560. }
  10561. // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
  10562. // data is handled in the flush() call
  10563. ;
  10564. _proto.softwareDecrypt = function softwareDecrypt(data, key, iv, aesMode) {
  10565. var currentIV = this.currentIV,
  10566. currentResult = this.currentResult,
  10567. remainderData = this.remainderData;
  10568. if (aesMode !== DecrypterAesMode.cbc || key.byteLength !== 16) {
  10569. logger.warn('SoftwareDecrypt: can only handle AES-128-CBC');
  10570. return null;
  10571. }
  10572. this.logOnce('JS AES decrypt');
  10573. // The output is staggered during progressive parsing - the current result is cached, and emitted on the next call
  10574. // This is done in order to strip PKCS7 padding, which is found at the end of each segment. We only know we've reached
  10575. // the end on flush(), but by that time we have already received all bytes for the segment.
  10576. // Progressive decryption does not work with WebCrypto
  10577. if (remainderData) {
  10578. data = appendUint8Array(remainderData, data);
  10579. this.remainderData = null;
  10580. }
  10581. // Byte length must be a multiple of 16 (AES-128 = 128 bit blocks = 16 bytes)
  10582. var currentChunk = this.getValidChunk(data);
  10583. if (!currentChunk.length) {
  10584. return null;
  10585. }
  10586. if (currentIV) {
  10587. iv = currentIV;
  10588. }
  10589. var softwareDecrypter = this.softwareDecrypter;
  10590. if (!softwareDecrypter) {
  10591. softwareDecrypter = this.softwareDecrypter = new AESDecryptor();
  10592. }
  10593. softwareDecrypter.expandKey(key);
  10594. var result = currentResult;
  10595. this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv);
  10596. this.currentIV = currentChunk.slice(-16).buffer;
  10597. if (!result) {
  10598. return null;
  10599. }
  10600. return result;
  10601. };
  10602. _proto.webCryptoDecrypt = function webCryptoDecrypt(data, key, iv, aesMode) {
  10603. var _this2 = this;
  10604. if (this.key !== key || !this.fastAesKey) {
  10605. if (!this.subtle) {
  10606. return Promise.resolve(this.onWebCryptoError(data, key, iv, aesMode));
  10607. }
  10608. this.key = key;
  10609. this.fastAesKey = new FastAESKey(this.subtle, key, aesMode);
  10610. }
  10611. return this.fastAesKey.expandKey().then(function (aesKey) {
  10612. // decrypt using web crypto
  10613. if (!_this2.subtle) {
  10614. return Promise.reject(new Error('web crypto not initialized'));
  10615. }
  10616. _this2.logOnce('WebCrypto AES decrypt');
  10617. var crypto = new AESCrypto(_this2.subtle, new Uint8Array(iv), aesMode);
  10618. return crypto.decrypt(data.buffer, aesKey);
  10619. }).catch(function (err) {
  10620. logger.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, " + err.name + ": " + err.message);
  10621. return _this2.onWebCryptoError(data, key, iv, aesMode);
  10622. });
  10623. };
  10624. _proto.onWebCryptoError = function onWebCryptoError(data, key, iv, aesMode) {
  10625. var enableSoftwareAES = this.enableSoftwareAES;
  10626. if (enableSoftwareAES) {
  10627. this.useSoftware = true;
  10628. this.logEnabled = true;
  10629. this.softwareDecrypt(data, key, iv, aesMode);
  10630. var decryptResult = this.flush();
  10631. if (decryptResult) {
  10632. return decryptResult.buffer;
  10633. }
  10634. }
  10635. throw new Error('WebCrypto' + (enableSoftwareAES ? ' and softwareDecrypt' : '') + ': failed to decrypt data');
  10636. };
  10637. _proto.getValidChunk = function getValidChunk(data) {
  10638. var currentChunk = data;
  10639. var splitPoint = data.length - data.length % CHUNK_SIZE;
  10640. if (splitPoint !== data.length) {
  10641. currentChunk = data.slice(0, splitPoint);
  10642. this.remainderData = data.slice(splitPoint);
  10643. }
  10644. return currentChunk;
  10645. };
  10646. _proto.logOnce = function logOnce(msg) {
  10647. if (!this.logEnabled) {
  10648. return;
  10649. }
  10650. logger.log("[decrypter]: " + msg);
  10651. this.logEnabled = false;
  10652. };
  10653. return Decrypter;
  10654. }();
  10655. var emsgSchemePattern = /\/emsg[-/]ID3/i;
  10656. var MP4Demuxer = /*#__PURE__*/function () {
  10657. function MP4Demuxer(observer, config) {
  10658. this.remainderData = null;
  10659. this.timeOffset = 0;
  10660. this.config = void 0;
  10661. this.videoTrack = void 0;
  10662. this.audioTrack = void 0;
  10663. this.id3Track = void 0;
  10664. this.txtTrack = void 0;
  10665. this.config = config;
  10666. }
  10667. var _proto = MP4Demuxer.prototype;
  10668. _proto.resetTimeStamp = function resetTimeStamp() {};
  10669. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  10670. var videoTrack = this.videoTrack = dummyTrack('video', 1);
  10671. var audioTrack = this.audioTrack = dummyTrack('audio', 1);
  10672. var captionTrack = this.txtTrack = dummyTrack('text', 1);
  10673. this.id3Track = dummyTrack('id3', 1);
  10674. this.timeOffset = 0;
  10675. if (!(initSegment != null && initSegment.byteLength)) {
  10676. return;
  10677. }
  10678. var initData = parseInitSegment(initSegment);
  10679. if (initData.video) {
  10680. var _initData$video = initData.video,
  10681. id = _initData$video.id,
  10682. timescale = _initData$video.timescale,
  10683. codec = _initData$video.codec,
  10684. supplemental = _initData$video.supplemental;
  10685. videoTrack.id = id;
  10686. videoTrack.timescale = captionTrack.timescale = timescale;
  10687. videoTrack.codec = codec;
  10688. videoTrack.supplemental = supplemental;
  10689. }
  10690. if (initData.audio) {
  10691. var _initData$audio = initData.audio,
  10692. _id = _initData$audio.id,
  10693. _timescale = _initData$audio.timescale,
  10694. _codec = _initData$audio.codec;
  10695. audioTrack.id = _id;
  10696. audioTrack.timescale = _timescale;
  10697. audioTrack.codec = _codec;
  10698. }
  10699. captionTrack.id = RemuxerTrackIdConfig.text;
  10700. videoTrack.sampleDuration = 0;
  10701. videoTrack.duration = audioTrack.duration = trackDuration;
  10702. };
  10703. _proto.resetContiguity = function resetContiguity() {
  10704. this.remainderData = null;
  10705. };
  10706. MP4Demuxer.probe = function probe(data) {
  10707. return hasMoofData(data);
  10708. };
  10709. _proto.demux = function demux(data, timeOffset) {
  10710. this.timeOffset = timeOffset;
  10711. // 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
  10712. var videoSamples = data;
  10713. var videoTrack = this.videoTrack;
  10714. var textTrack = this.txtTrack;
  10715. if (this.config.progressive) {
  10716. // Split the bytestream into two ranges: one encompassing all data up until the start of the last moof, and everything else.
  10717. // This is done to guarantee that we're sending valid data to MSE - when demuxing progressively, we have no guarantee
  10718. // that the fetch loader gives us flush moof+mdat pairs. If we push jagged data to MSE, it will throw an exception.
  10719. if (this.remainderData) {
  10720. videoSamples = appendUint8Array(this.remainderData, data);
  10721. }
  10722. var segmentedData = segmentValidRange(videoSamples);
  10723. this.remainderData = segmentedData.remainder;
  10724. videoTrack.samples = segmentedData.valid || new Uint8Array();
  10725. } else {
  10726. videoTrack.samples = videoSamples;
  10727. }
  10728. var id3Track = this.extractID3Track(videoTrack, timeOffset);
  10729. textTrack.samples = parseSamples(timeOffset, videoTrack);
  10730. return {
  10731. videoTrack: videoTrack,
  10732. audioTrack: this.audioTrack,
  10733. id3Track: id3Track,
  10734. textTrack: this.txtTrack
  10735. };
  10736. };
  10737. _proto.flush = function flush() {
  10738. var timeOffset = this.timeOffset;
  10739. var videoTrack = this.videoTrack;
  10740. var textTrack = this.txtTrack;
  10741. videoTrack.samples = this.remainderData || new Uint8Array();
  10742. this.remainderData = null;
  10743. var id3Track = this.extractID3Track(videoTrack, this.timeOffset);
  10744. textTrack.samples = parseSamples(timeOffset, videoTrack);
  10745. return {
  10746. videoTrack: videoTrack,
  10747. audioTrack: dummyTrack(),
  10748. id3Track: id3Track,
  10749. textTrack: dummyTrack()
  10750. };
  10751. };
  10752. _proto.extractID3Track = function extractID3Track(videoTrack, timeOffset) {
  10753. var _this = this;
  10754. var id3Track = this.id3Track;
  10755. if (videoTrack.samples.length) {
  10756. var emsgs = findBox(videoTrack.samples, ['emsg']);
  10757. if (emsgs) {
  10758. emsgs.forEach(function (data) {
  10759. var emsgInfo = parseEmsg(data);
  10760. if (emsgSchemePattern.test(emsgInfo.schemeIdUri)) {
  10761. var pts = getEmsgStartTime(emsgInfo, timeOffset);
  10762. var duration = emsgInfo.eventDuration === 0xffffffff ? Number.POSITIVE_INFINITY : emsgInfo.eventDuration / emsgInfo.timeScale;
  10763. // Safari takes anything <= 0.001 seconds and maps it to Infinity
  10764. if (duration <= 0.001) {
  10765. duration = Number.POSITIVE_INFINITY;
  10766. }
  10767. var payload = emsgInfo.payload;
  10768. id3Track.samples.push({
  10769. data: payload,
  10770. len: payload.byteLength,
  10771. dts: pts,
  10772. pts: pts,
  10773. type: MetadataSchema.emsg,
  10774. duration: duration
  10775. });
  10776. } else if (_this.config.enableEmsgKLVMetadata && emsgInfo.schemeIdUri.startsWith('urn:misb:KLV:bin:1910.1')) {
  10777. var _pts = getEmsgStartTime(emsgInfo, timeOffset);
  10778. id3Track.samples.push({
  10779. data: emsgInfo.payload,
  10780. len: emsgInfo.payload.byteLength,
  10781. dts: _pts,
  10782. pts: _pts,
  10783. type: MetadataSchema.misbklv,
  10784. duration: Number.POSITIVE_INFINITY
  10785. });
  10786. }
  10787. });
  10788. }
  10789. }
  10790. return id3Track;
  10791. };
  10792. _proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
  10793. return Promise.reject(new Error('The MP4 demuxer does not support SAMPLE-AES decryption'));
  10794. };
  10795. _proto.destroy = function destroy() {
  10796. // @ts-ignore
  10797. this.config = null;
  10798. this.remainderData = null;
  10799. this.videoTrack = this.audioTrack = this.id3Track = this.txtTrack = undefined;
  10800. };
  10801. return MP4Demuxer;
  10802. }();
  10803. function getEmsgStartTime(emsgInfo, timeOffset) {
  10804. return isFiniteNumber(emsgInfo.presentationTime) ? emsgInfo.presentationTime / emsgInfo.timeScale : timeOffset + emsgInfo.presentationTimeDelta / emsgInfo.timeScale;
  10805. }
  10806. /**
  10807. * SAMPLE-AES decrypter
  10808. */
  10809. var SampleAesDecrypter = /*#__PURE__*/function () {
  10810. function SampleAesDecrypter(observer, config, keyData) {
  10811. this.keyData = void 0;
  10812. this.decrypter = void 0;
  10813. this.keyData = keyData;
  10814. this.decrypter = new Decrypter(config, {
  10815. removePKCS7Padding: false
  10816. });
  10817. }
  10818. var _proto = SampleAesDecrypter.prototype;
  10819. _proto.decryptBuffer = function decryptBuffer(encryptedData) {
  10820. return this.decrypter.decrypt(encryptedData, this.keyData.key.buffer, this.keyData.iv.buffer, DecrypterAesMode.cbc);
  10821. }
  10822. // AAC - encrypt all full 16 bytes blocks starting from offset 16
  10823. ;
  10824. _proto.decryptAacSample = function decryptAacSample(samples, sampleIndex, callback) {
  10825. var _this = this;
  10826. var curUnit = samples[sampleIndex].unit;
  10827. if (curUnit.length <= 16) {
  10828. // No encrypted portion in this sample (first 16 bytes is not
  10829. // encrypted, see https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/HLS_Sample_Encryption/Encryption/Encryption.html),
  10830. return;
  10831. }
  10832. var encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
  10833. var encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
  10834. this.decryptBuffer(encryptedBuffer).then(function (decryptedBuffer) {
  10835. var decryptedData = new Uint8Array(decryptedBuffer);
  10836. curUnit.set(decryptedData, 16);
  10837. if (!_this.decrypter.isSync()) {
  10838. _this.decryptAacSamples(samples, sampleIndex + 1, callback);
  10839. }
  10840. });
  10841. };
  10842. _proto.decryptAacSamples = function decryptAacSamples(samples, sampleIndex, callback) {
  10843. for (;; sampleIndex++) {
  10844. if (sampleIndex >= samples.length) {
  10845. callback();
  10846. return;
  10847. }
  10848. if (samples[sampleIndex].unit.length < 32) {
  10849. continue;
  10850. }
  10851. this.decryptAacSample(samples, sampleIndex, callback);
  10852. if (!this.decrypter.isSync()) {
  10853. return;
  10854. }
  10855. }
  10856. }
  10857. // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
  10858. ;
  10859. _proto.getAvcEncryptedData = function getAvcEncryptedData(decodedData) {
  10860. var encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
  10861. var encryptedData = new Int8Array(encryptedDataLen);
  10862. var outputPos = 0;
  10863. for (var inputPos = 32; inputPos < decodedData.length - 16; inputPos += 160, outputPos += 16) {
  10864. encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
  10865. }
  10866. return encryptedData;
  10867. };
  10868. _proto.getAvcDecryptedUnit = function getAvcDecryptedUnit(decodedData, decryptedData) {
  10869. var uint8DecryptedData = new Uint8Array(decryptedData);
  10870. var inputPos = 0;
  10871. for (var outputPos = 32; outputPos < decodedData.length - 16; outputPos += 160, inputPos += 16) {
  10872. decodedData.set(uint8DecryptedData.subarray(inputPos, inputPos + 16), outputPos);
  10873. }
  10874. return decodedData;
  10875. };
  10876. _proto.decryptAvcSample = function decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit) {
  10877. var _this2 = this;
  10878. var decodedData = discardEPB(curUnit.data);
  10879. var encryptedData = this.getAvcEncryptedData(decodedData);
  10880. this.decryptBuffer(encryptedData.buffer).then(function (decryptedBuffer) {
  10881. curUnit.data = _this2.getAvcDecryptedUnit(decodedData, decryptedBuffer);
  10882. if (!_this2.decrypter.isSync()) {
  10883. _this2.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
  10884. }
  10885. });
  10886. };
  10887. _proto.decryptAvcSamples = function decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
  10888. if (samples instanceof Uint8Array) {
  10889. throw new Error('Cannot decrypt samples of type Uint8Array');
  10890. }
  10891. for (;; sampleIndex++, unitIndex = 0) {
  10892. if (sampleIndex >= samples.length) {
  10893. callback();
  10894. return;
  10895. }
  10896. var curUnits = samples[sampleIndex].units;
  10897. for (;; unitIndex++) {
  10898. if (unitIndex >= curUnits.length) {
  10899. break;
  10900. }
  10901. var curUnit = curUnits[unitIndex];
  10902. if (curUnit.data.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
  10903. continue;
  10904. }
  10905. this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit);
  10906. if (!this.decrypter.isSync()) {
  10907. return;
  10908. }
  10909. }
  10910. }
  10911. };
  10912. return SampleAesDecrypter;
  10913. }();
  10914. var BaseVideoParser = /*#__PURE__*/function () {
  10915. function BaseVideoParser() {
  10916. this.VideoSample = null;
  10917. }
  10918. var _proto = BaseVideoParser.prototype;
  10919. _proto.createVideoSample = function createVideoSample(key, pts, dts) {
  10920. return {
  10921. key: key,
  10922. frame: false,
  10923. pts: pts,
  10924. dts: dts,
  10925. units: [],
  10926. length: 0
  10927. };
  10928. };
  10929. _proto.getLastNalUnit = function getLastNalUnit(samples) {
  10930. var _VideoSample;
  10931. var VideoSample = this.VideoSample;
  10932. var lastUnit;
  10933. // try to fallback to previous sample if current one is empty
  10934. if (!VideoSample || VideoSample.units.length === 0) {
  10935. VideoSample = samples[samples.length - 1];
  10936. }
  10937. if ((_VideoSample = VideoSample) != null && _VideoSample.units) {
  10938. var units = VideoSample.units;
  10939. lastUnit = units[units.length - 1];
  10940. }
  10941. return lastUnit;
  10942. };
  10943. _proto.pushAccessUnit = function pushAccessUnit(VideoSample, videoTrack) {
  10944. if (VideoSample.units.length && VideoSample.frame) {
  10945. // if sample does not have PTS/DTS, patch with last sample PTS/DTS
  10946. if (VideoSample.pts === undefined) {
  10947. var samples = videoTrack.samples;
  10948. var nbSamples = samples.length;
  10949. if (nbSamples) {
  10950. var lastSample = samples[nbSamples - 1];
  10951. VideoSample.pts = lastSample.pts;
  10952. VideoSample.dts = lastSample.dts;
  10953. } else {
  10954. // dropping samples, no timestamp found
  10955. videoTrack.dropped++;
  10956. return;
  10957. }
  10958. }
  10959. videoTrack.samples.push(VideoSample);
  10960. }
  10961. };
  10962. _proto.parseNALu = function parseNALu(track, array, endOfSegment) {
  10963. var len = array.byteLength;
  10964. var state = track.naluState || 0;
  10965. var lastState = state;
  10966. var units = [];
  10967. var i = 0;
  10968. var value;
  10969. var overflow;
  10970. var unitType;
  10971. var lastUnitStart = -1;
  10972. var lastUnitType = 0;
  10973. // logger.log('PES:' + Hex.hexDump(array));
  10974. if (state === -1) {
  10975. // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet
  10976. lastUnitStart = 0;
  10977. // NALu type is value read from offset 0
  10978. lastUnitType = this.getNALuType(array, 0);
  10979. state = 0;
  10980. i = 1;
  10981. }
  10982. while (i < len) {
  10983. value = array[i++];
  10984. // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case
  10985. if (!state) {
  10986. state = value ? 0 : 1;
  10987. continue;
  10988. }
  10989. if (state === 1) {
  10990. state = value ? 0 : 2;
  10991. continue;
  10992. }
  10993. // here we have state either equal to 2 or 3
  10994. if (!value) {
  10995. state = 3;
  10996. } else if (value === 1) {
  10997. overflow = i - state - 1;
  10998. if (lastUnitStart >= 0) {
  10999. var unit = {
  11000. data: array.subarray(lastUnitStart, overflow),
  11001. type: lastUnitType
  11002. };
  11003. // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
  11004. units.push(unit);
  11005. } else {
  11006. // lastUnitStart is undefined => this is the first start code found in this PES packet
  11007. // first check if start code delimiter is overlapping between 2 PES packets,
  11008. // ie it started in last packet (lastState not zero)
  11009. // and ended at the beginning of this PES packet (i <= 4 - lastState)
  11010. var lastUnit = this.getLastNalUnit(track.samples);
  11011. if (lastUnit) {
  11012. if (lastState && i <= 4 - lastState) {
  11013. // start delimiter overlapping between PES packets
  11014. // strip start delimiter bytes from the end of last NAL unit
  11015. // check if lastUnit had a state different from zero
  11016. if (lastUnit.state) {
  11017. // strip last bytes
  11018. lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
  11019. }
  11020. }
  11021. // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.
  11022. if (overflow > 0) {
  11023. // logger.log('first NALU found with overflow:' + overflow);
  11024. lastUnit.data = appendUint8Array(lastUnit.data, array.subarray(0, overflow));
  11025. lastUnit.state = 0;
  11026. }
  11027. }
  11028. }
  11029. // check if we can read unit type
  11030. if (i < len) {
  11031. unitType = this.getNALuType(array, i);
  11032. // logger.log('find NALU @ offset:' + i + ',type:' + unitType);
  11033. lastUnitStart = i;
  11034. lastUnitType = unitType;
  11035. state = 0;
  11036. } else {
  11037. // not enough byte to read unit type. let's read it on next PES parsing
  11038. state = -1;
  11039. }
  11040. } else {
  11041. state = 0;
  11042. }
  11043. }
  11044. if (lastUnitStart >= 0 && state >= 0) {
  11045. var _unit = {
  11046. data: array.subarray(lastUnitStart, len),
  11047. type: lastUnitType,
  11048. state: state
  11049. };
  11050. units.push(_unit);
  11051. // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);
  11052. }
  11053. // no NALu found
  11054. if (units.length === 0) {
  11055. // append pes.data to previous NAL unit
  11056. var _lastUnit = this.getLastNalUnit(track.samples);
  11057. if (_lastUnit) {
  11058. _lastUnit.data = appendUint8Array(_lastUnit.data, array);
  11059. }
  11060. }
  11061. track.naluState = state;
  11062. return units;
  11063. };
  11064. return BaseVideoParser;
  11065. }();
  11066. /**
  11067. * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
  11068. */
  11069. var ExpGolomb = /*#__PURE__*/function () {
  11070. function ExpGolomb(data) {
  11071. this.data = void 0;
  11072. this.bytesAvailable = void 0;
  11073. this.word = void 0;
  11074. this.bitsAvailable = void 0;
  11075. this.data = data;
  11076. // the number of bytes left to examine in this.data
  11077. this.bytesAvailable = data.byteLength;
  11078. // the current word being examined
  11079. this.word = 0; // :uint
  11080. // the number of bits left to examine in the current word
  11081. this.bitsAvailable = 0; // :uint
  11082. }
  11083. // ():void
  11084. var _proto = ExpGolomb.prototype;
  11085. _proto.loadWord = function loadWord() {
  11086. var data = this.data;
  11087. var bytesAvailable = this.bytesAvailable;
  11088. var position = data.byteLength - bytesAvailable;
  11089. var workingBytes = new Uint8Array(4);
  11090. var availableBytes = Math.min(4, bytesAvailable);
  11091. if (availableBytes === 0) {
  11092. throw new Error('no bytes available');
  11093. }
  11094. workingBytes.set(data.subarray(position, position + availableBytes));
  11095. this.word = new DataView(workingBytes.buffer).getUint32(0);
  11096. // track the amount of this.data that has been processed
  11097. this.bitsAvailable = availableBytes * 8;
  11098. this.bytesAvailable -= availableBytes;
  11099. }
  11100. // (count:int):void
  11101. ;
  11102. _proto.skipBits = function skipBits(count) {
  11103. var skipBytes; // :int
  11104. count = Math.min(count, this.bytesAvailable * 8 + this.bitsAvailable);
  11105. if (this.bitsAvailable > count) {
  11106. this.word <<= count;
  11107. this.bitsAvailable -= count;
  11108. } else {
  11109. count -= this.bitsAvailable;
  11110. skipBytes = count >> 3;
  11111. count -= skipBytes << 3;
  11112. this.bytesAvailable -= skipBytes;
  11113. this.loadWord();
  11114. this.word <<= count;
  11115. this.bitsAvailable -= count;
  11116. }
  11117. }
  11118. // (size:int):uint
  11119. ;
  11120. _proto.readBits = function readBits(size) {
  11121. var bits = Math.min(this.bitsAvailable, size); // :uint
  11122. var valu = this.word >>> 32 - bits; // :uint
  11123. if (size > 32) {
  11124. logger.error('Cannot read more than 32 bits at a time');
  11125. }
  11126. this.bitsAvailable -= bits;
  11127. if (this.bitsAvailable > 0) {
  11128. this.word <<= bits;
  11129. } else if (this.bytesAvailable > 0) {
  11130. this.loadWord();
  11131. } else {
  11132. throw new Error('no bits available');
  11133. }
  11134. bits = size - bits;
  11135. if (bits > 0 && this.bitsAvailable) {
  11136. return valu << bits | this.readBits(bits);
  11137. } else {
  11138. return valu;
  11139. }
  11140. }
  11141. // ():uint
  11142. ;
  11143. _proto.skipLZ = function skipLZ() {
  11144. var leadingZeroCount; // :uint
  11145. for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
  11146. if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) {
  11147. // the first bit of working word is 1
  11148. this.word <<= leadingZeroCount;
  11149. this.bitsAvailable -= leadingZeroCount;
  11150. return leadingZeroCount;
  11151. }
  11152. }
  11153. // we exhausted word and still have not found a 1
  11154. this.loadWord();
  11155. return leadingZeroCount + this.skipLZ();
  11156. }
  11157. // ():void
  11158. ;
  11159. _proto.skipUEG = function skipUEG() {
  11160. this.skipBits(1 + this.skipLZ());
  11161. }
  11162. // ():void
  11163. ;
  11164. _proto.skipEG = function skipEG() {
  11165. this.skipBits(1 + this.skipLZ());
  11166. }
  11167. // ():uint
  11168. ;
  11169. _proto.readUEG = function readUEG() {
  11170. var clz = this.skipLZ(); // :uint
  11171. return this.readBits(clz + 1) - 1;
  11172. }
  11173. // ():int
  11174. ;
  11175. _proto.readEG = function readEG() {
  11176. var valu = this.readUEG(); // :int
  11177. if (0x01 & valu) {
  11178. // the number is odd if the low order bit is set
  11179. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  11180. } else {
  11181. return -1 * (valu >>> 1); // divide by two then make it negative
  11182. }
  11183. }
  11184. // Some convenience functions
  11185. // :Boolean
  11186. ;
  11187. _proto.readBoolean = function readBoolean() {
  11188. return this.readBits(1) === 1;
  11189. }
  11190. // ():int
  11191. ;
  11192. _proto.readUByte = function readUByte() {
  11193. return this.readBits(8);
  11194. }
  11195. // ():int
  11196. ;
  11197. _proto.readUShort = function readUShort() {
  11198. return this.readBits(16);
  11199. }
  11200. // ():int
  11201. ;
  11202. _proto.readUInt = function readUInt() {
  11203. return this.readBits(32);
  11204. };
  11205. return ExpGolomb;
  11206. }();
  11207. var AvcVideoParser = /*#__PURE__*/function (_BaseVideoParser) {
  11208. function AvcVideoParser() {
  11209. return _BaseVideoParser.apply(this, arguments) || this;
  11210. }
  11211. _inheritsLoose(AvcVideoParser, _BaseVideoParser);
  11212. var _proto = AvcVideoParser.prototype;
  11213. _proto.parsePES = function parsePES(track, textTrack, pes, endOfSegment) {
  11214. var _this = this;
  11215. var units = this.parseNALu(track, pes.data, endOfSegment);
  11216. var VideoSample = this.VideoSample;
  11217. var push;
  11218. var spsfound = false;
  11219. // free pes.data to save up some memory
  11220. pes.data = null;
  11221. // if new NAL units found and last sample still there, let's push ...
  11222. // this helps parsing streams with missing AUD (only do this if AUD never found)
  11223. if (VideoSample && units.length && !track.audFound) {
  11224. this.pushAccessUnit(VideoSample, track);
  11225. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  11226. }
  11227. units.forEach(function (unit) {
  11228. var _VideoSample2, _VideoSample3;
  11229. switch (unit.type) {
  11230. // NDR
  11231. case 1:
  11232. {
  11233. var iskey = false;
  11234. push = true;
  11235. var data = unit.data;
  11236. // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)
  11237. if (spsfound && data.length > 4) {
  11238. // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR
  11239. var sliceType = _this.readSliceType(data);
  11240. // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice
  11241. // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.
  11242. // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.
  11243. // I slice: A slice that is not an SI slice that is decoded using intra prediction only.
  11244. // if (sliceType === 2 || sliceType === 7) {
  11245. if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
  11246. iskey = true;
  11247. }
  11248. }
  11249. if (iskey) {
  11250. var _VideoSample;
  11251. // if we have non-keyframe data already, that cannot belong to the same frame as a keyframe, so force a push
  11252. if ((_VideoSample = VideoSample) != null && _VideoSample.frame && !VideoSample.key) {
  11253. _this.pushAccessUnit(VideoSample, track);
  11254. VideoSample = _this.VideoSample = null;
  11255. }
  11256. }
  11257. if (!VideoSample) {
  11258. VideoSample = _this.VideoSample = _this.createVideoSample(true, pes.pts, pes.dts);
  11259. }
  11260. VideoSample.frame = true;
  11261. VideoSample.key = iskey;
  11262. break;
  11263. // IDR
  11264. }
  11265. case 5:
  11266. push = true;
  11267. // handle PES not starting with AUD
  11268. // if we have frame data already, that cannot belong to the same frame, so force a push
  11269. if ((_VideoSample2 = VideoSample) != null && _VideoSample2.frame && !VideoSample.key) {
  11270. _this.pushAccessUnit(VideoSample, track);
  11271. VideoSample = _this.VideoSample = null;
  11272. }
  11273. if (!VideoSample) {
  11274. VideoSample = _this.VideoSample = _this.createVideoSample(true, pes.pts, pes.dts);
  11275. }
  11276. VideoSample.key = true;
  11277. VideoSample.frame = true;
  11278. break;
  11279. // SEI
  11280. case 6:
  11281. {
  11282. push = true;
  11283. parseSEIMessageFromNALu(unit.data, 1, pes.pts, textTrack.samples);
  11284. break;
  11285. // SPS
  11286. }
  11287. case 7:
  11288. {
  11289. var _track$pixelRatio, _track$pixelRatio2;
  11290. push = true;
  11291. spsfound = true;
  11292. var sps = unit.data;
  11293. var config = _this.readSPS(sps);
  11294. if (!track.sps || track.width !== config.width || track.height !== config.height || ((_track$pixelRatio = track.pixelRatio) == null ? void 0 : _track$pixelRatio[0]) !== config.pixelRatio[0] || ((_track$pixelRatio2 = track.pixelRatio) == null ? void 0 : _track$pixelRatio2[1]) !== config.pixelRatio[1]) {
  11295. track.width = config.width;
  11296. track.height = config.height;
  11297. track.pixelRatio = config.pixelRatio;
  11298. track.sps = [sps];
  11299. var codecarray = sps.subarray(1, 4);
  11300. var codecstring = 'avc1.';
  11301. for (var i = 0; i < 3; i++) {
  11302. var h = codecarray[i].toString(16);
  11303. if (h.length < 2) {
  11304. h = '0' + h;
  11305. }
  11306. codecstring += h;
  11307. }
  11308. track.codec = codecstring;
  11309. }
  11310. break;
  11311. }
  11312. // PPS
  11313. case 8:
  11314. push = true;
  11315. track.pps = [unit.data];
  11316. break;
  11317. // AUD
  11318. case 9:
  11319. push = true;
  11320. track.audFound = true;
  11321. if ((_VideoSample3 = VideoSample) != null && _VideoSample3.frame) {
  11322. _this.pushAccessUnit(VideoSample, track);
  11323. VideoSample = null;
  11324. }
  11325. if (!VideoSample) {
  11326. VideoSample = _this.VideoSample = _this.createVideoSample(false, pes.pts, pes.dts);
  11327. }
  11328. break;
  11329. // Filler Data
  11330. case 12:
  11331. push = true;
  11332. break;
  11333. default:
  11334. push = false;
  11335. break;
  11336. }
  11337. if (VideoSample && push) {
  11338. var _units = VideoSample.units;
  11339. _units.push(unit);
  11340. }
  11341. });
  11342. // if last PES packet, push samples
  11343. if (endOfSegment && VideoSample) {
  11344. this.pushAccessUnit(VideoSample, track);
  11345. this.VideoSample = null;
  11346. }
  11347. };
  11348. _proto.getNALuType = function getNALuType(data, offset) {
  11349. return data[offset] & 0x1f;
  11350. };
  11351. _proto.readSliceType = function readSliceType(data) {
  11352. var eg = new ExpGolomb(data);
  11353. // skip NALu type
  11354. eg.readUByte();
  11355. // discard first_mb_in_slice
  11356. eg.readUEG();
  11357. // return slice_type
  11358. return eg.readUEG();
  11359. }
  11360. /**
  11361. * The scaling list is optionally transmitted as part of a sequence parameter
  11362. * set and is not relevant to transmuxing.
  11363. * @param count the number of entries in this scaling list
  11364. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  11365. */;
  11366. _proto.skipScalingList = function skipScalingList(count, reader) {
  11367. var lastScale = 8;
  11368. var nextScale = 8;
  11369. var deltaScale;
  11370. for (var j = 0; j < count; j++) {
  11371. if (nextScale !== 0) {
  11372. deltaScale = reader.readEG();
  11373. nextScale = (lastScale + deltaScale + 256) % 256;
  11374. }
  11375. lastScale = nextScale === 0 ? lastScale : nextScale;
  11376. }
  11377. }
  11378. /**
  11379. * Read a sequence parameter set and return some interesting video
  11380. * properties. A sequence parameter set is the H264 metadata that
  11381. * describes the properties of upcoming video frames.
  11382. * @returns an object with configuration parsed from the
  11383. * sequence parameter set, including the dimensions of the
  11384. * associated video frames.
  11385. */;
  11386. _proto.readSPS = function readSPS(sps) {
  11387. var eg = new ExpGolomb(sps);
  11388. var frameCropLeftOffset = 0;
  11389. var frameCropRightOffset = 0;
  11390. var frameCropTopOffset = 0;
  11391. var frameCropBottomOffset = 0;
  11392. var numRefFramesInPicOrderCntCycle;
  11393. var scalingListCount;
  11394. var i;
  11395. var readUByte = eg.readUByte.bind(eg);
  11396. var readBits = eg.readBits.bind(eg);
  11397. var readUEG = eg.readUEG.bind(eg);
  11398. var readBoolean = eg.readBoolean.bind(eg);
  11399. var skipBits = eg.skipBits.bind(eg);
  11400. var skipEG = eg.skipEG.bind(eg);
  11401. var skipUEG = eg.skipUEG.bind(eg);
  11402. var skipScalingList = this.skipScalingList.bind(this);
  11403. readUByte();
  11404. var profileIdc = readUByte(); // profile_idc
  11405. readBits(5); // profileCompat constraint_set[0-4]_flag, u(5)
  11406. skipBits(3); // reserved_zero_3bits u(3),
  11407. readUByte(); // level_idc u(8)
  11408. skipUEG(); // seq_parameter_set_id
  11409. // some profiles have more optional data we don't need
  11410. if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
  11411. var chromaFormatIdc = readUEG();
  11412. if (chromaFormatIdc === 3) {
  11413. skipBits(1);
  11414. } // separate_colour_plane_flag
  11415. skipUEG(); // bit_depth_luma_minus8
  11416. skipUEG(); // bit_depth_chroma_minus8
  11417. skipBits(1); // qpprime_y_zero_transform_bypass_flag
  11418. if (readBoolean()) {
  11419. // seq_scaling_matrix_present_flag
  11420. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  11421. for (i = 0; i < scalingListCount; i++) {
  11422. if (readBoolean()) {
  11423. // seq_scaling_list_present_flag[ i ]
  11424. if (i < 6) {
  11425. skipScalingList(16, eg);
  11426. } else {
  11427. skipScalingList(64, eg);
  11428. }
  11429. }
  11430. }
  11431. }
  11432. }
  11433. skipUEG(); // log2_max_frame_num_minus4
  11434. var picOrderCntType = readUEG();
  11435. if (picOrderCntType === 0) {
  11436. readUEG(); // log2_max_pic_order_cnt_lsb_minus4
  11437. } else if (picOrderCntType === 1) {
  11438. skipBits(1); // delta_pic_order_always_zero_flag
  11439. skipEG(); // offset_for_non_ref_pic
  11440. skipEG(); // offset_for_top_to_bottom_field
  11441. numRefFramesInPicOrderCntCycle = readUEG();
  11442. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  11443. skipEG();
  11444. } // offset_for_ref_frame[ i ]
  11445. }
  11446. skipUEG(); // max_num_ref_frames
  11447. skipBits(1); // gaps_in_frame_num_value_allowed_flag
  11448. var picWidthInMbsMinus1 = readUEG();
  11449. var picHeightInMapUnitsMinus1 = readUEG();
  11450. var frameMbsOnlyFlag = readBits(1);
  11451. if (frameMbsOnlyFlag === 0) {
  11452. skipBits(1);
  11453. } // mb_adaptive_frame_field_flag
  11454. skipBits(1); // direct_8x8_inference_flag
  11455. if (readBoolean()) {
  11456. // frame_cropping_flag
  11457. frameCropLeftOffset = readUEG();
  11458. frameCropRightOffset = readUEG();
  11459. frameCropTopOffset = readUEG();
  11460. frameCropBottomOffset = readUEG();
  11461. }
  11462. var pixelRatio = [1, 1];
  11463. if (readBoolean()) {
  11464. // vui_parameters_present_flag
  11465. if (readBoolean()) {
  11466. // aspect_ratio_info_present_flag
  11467. var aspectRatioIdc = readUByte();
  11468. switch (aspectRatioIdc) {
  11469. case 1:
  11470. pixelRatio = [1, 1];
  11471. break;
  11472. case 2:
  11473. pixelRatio = [12, 11];
  11474. break;
  11475. case 3:
  11476. pixelRatio = [10, 11];
  11477. break;
  11478. case 4:
  11479. pixelRatio = [16, 11];
  11480. break;
  11481. case 5:
  11482. pixelRatio = [40, 33];
  11483. break;
  11484. case 6:
  11485. pixelRatio = [24, 11];
  11486. break;
  11487. case 7:
  11488. pixelRatio = [20, 11];
  11489. break;
  11490. case 8:
  11491. pixelRatio = [32, 11];
  11492. break;
  11493. case 9:
  11494. pixelRatio = [80, 33];
  11495. break;
  11496. case 10:
  11497. pixelRatio = [18, 11];
  11498. break;
  11499. case 11:
  11500. pixelRatio = [15, 11];
  11501. break;
  11502. case 12:
  11503. pixelRatio = [64, 33];
  11504. break;
  11505. case 13:
  11506. pixelRatio = [160, 99];
  11507. break;
  11508. case 14:
  11509. pixelRatio = [4, 3];
  11510. break;
  11511. case 15:
  11512. pixelRatio = [3, 2];
  11513. break;
  11514. case 16:
  11515. pixelRatio = [2, 1];
  11516. break;
  11517. case 255:
  11518. {
  11519. pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
  11520. break;
  11521. }
  11522. }
  11523. }
  11524. }
  11525. return {
  11526. width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
  11527. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
  11528. pixelRatio: pixelRatio
  11529. };
  11530. };
  11531. return AvcVideoParser;
  11532. }(BaseVideoParser);
  11533. var PACKET_LENGTH = 188;
  11534. var TSDemuxer = /*#__PURE__*/function () {
  11535. function TSDemuxer(observer, config, typeSupported, logger) {
  11536. this.logger = void 0;
  11537. this.observer = void 0;
  11538. this.config = void 0;
  11539. this.typeSupported = void 0;
  11540. this.sampleAes = null;
  11541. this.pmtParsed = false;
  11542. this.audioCodec = void 0;
  11543. this.videoCodec = void 0;
  11544. this._pmtId = -1;
  11545. this._videoTrack = void 0;
  11546. this._audioTrack = void 0;
  11547. this._id3Track = void 0;
  11548. this._txtTrack = void 0;
  11549. this.aacOverFlow = null;
  11550. this.remainderData = null;
  11551. this.videoParser = void 0;
  11552. this.observer = observer;
  11553. this.config = config;
  11554. this.typeSupported = typeSupported;
  11555. this.logger = logger;
  11556. this.videoParser = null;
  11557. }
  11558. TSDemuxer.probe = function probe(data, logger) {
  11559. var syncOffset = TSDemuxer.syncOffset(data);
  11560. if (syncOffset > 0) {
  11561. logger.warn("MPEG2-TS detected but first sync word found @ offset " + syncOffset);
  11562. }
  11563. return syncOffset !== -1;
  11564. };
  11565. TSDemuxer.syncOffset = function syncOffset(data) {
  11566. var length = data.length;
  11567. var scanwindow = Math.min(PACKET_LENGTH * 5, length - PACKET_LENGTH) + 1;
  11568. var i = 0;
  11569. while (i < scanwindow) {
  11570. // a TS init segment should contain at least 2 TS packets: PAT and PMT, each starting with 0x47
  11571. var foundPat = false;
  11572. var packetStart = -1;
  11573. var tsPackets = 0;
  11574. for (var j = i; j < length; j += PACKET_LENGTH) {
  11575. if (data[j] === 0x47 && (length - j === PACKET_LENGTH || data[j + PACKET_LENGTH] === 0x47)) {
  11576. tsPackets++;
  11577. if (packetStart === -1) {
  11578. packetStart = j;
  11579. // First sync word found at offset, increase scan length (#5251)
  11580. if (packetStart !== 0) {
  11581. scanwindow = Math.min(packetStart + PACKET_LENGTH * 99, data.length - PACKET_LENGTH) + 1;
  11582. }
  11583. }
  11584. if (!foundPat) {
  11585. foundPat = parsePID(data, j) === 0;
  11586. }
  11587. // Sync word found at 0 with 3 packets, or found at offset least 2 packets up to scanwindow (#5501)
  11588. if (foundPat && tsPackets > 1 && (packetStart === 0 && tsPackets > 2 || j + PACKET_LENGTH > scanwindow)) {
  11589. return packetStart;
  11590. }
  11591. } else if (tsPackets) {
  11592. // Exit if sync word found, but does not contain contiguous packets
  11593. return -1;
  11594. } else {
  11595. break;
  11596. }
  11597. }
  11598. i++;
  11599. }
  11600. return -1;
  11601. }
  11602. /**
  11603. * Creates a track model internal to demuxer used to drive remuxing input
  11604. */;
  11605. TSDemuxer.createTrack = function createTrack(type, duration) {
  11606. return {
  11607. container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,
  11608. type: type,
  11609. id: RemuxerTrackIdConfig[type],
  11610. pid: -1,
  11611. inputTimeScale: 90000,
  11612. sequenceNumber: 0,
  11613. samples: [],
  11614. dropped: 0,
  11615. duration: type === 'audio' ? duration : undefined
  11616. };
  11617. }
  11618. /**
  11619. * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
  11620. * Resets all internal track instances of the demuxer.
  11621. */;
  11622. var _proto = TSDemuxer.prototype;
  11623. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  11624. this.pmtParsed = false;
  11625. this._pmtId = -1;
  11626. this._videoTrack = TSDemuxer.createTrack('video');
  11627. this._videoTrack.duration = trackDuration;
  11628. this._audioTrack = TSDemuxer.createTrack('audio', trackDuration);
  11629. this._id3Track = TSDemuxer.createTrack('id3');
  11630. this._txtTrack = TSDemuxer.createTrack('text');
  11631. this._audioTrack.segmentCodec = 'aac';
  11632. // flush any partial content
  11633. this.aacOverFlow = null;
  11634. this.remainderData = null;
  11635. this.audioCodec = audioCodec;
  11636. this.videoCodec = videoCodec;
  11637. };
  11638. _proto.resetTimeStamp = function resetTimeStamp() {};
  11639. _proto.resetContiguity = function resetContiguity() {
  11640. var _audioTrack = this._audioTrack,
  11641. _videoTrack = this._videoTrack,
  11642. _id3Track = this._id3Track;
  11643. if (_audioTrack) {
  11644. _audioTrack.pesData = null;
  11645. }
  11646. if (_videoTrack) {
  11647. _videoTrack.pesData = null;
  11648. }
  11649. if (_id3Track) {
  11650. _id3Track.pesData = null;
  11651. }
  11652. this.aacOverFlow = null;
  11653. this.remainderData = null;
  11654. };
  11655. _proto.demux = function demux(data, timeOffset, isSampleAes, flush) {
  11656. if (isSampleAes === void 0) {
  11657. isSampleAes = false;
  11658. }
  11659. if (flush === void 0) {
  11660. flush = false;
  11661. }
  11662. if (!isSampleAes) {
  11663. this.sampleAes = null;
  11664. }
  11665. var pes;
  11666. var videoTrack = this._videoTrack;
  11667. var audioTrack = this._audioTrack;
  11668. var id3Track = this._id3Track;
  11669. var textTrack = this._txtTrack;
  11670. var videoPid = videoTrack.pid;
  11671. var videoData = videoTrack.pesData;
  11672. var audioPid = audioTrack.pid;
  11673. var id3Pid = id3Track.pid;
  11674. var audioData = audioTrack.pesData;
  11675. var id3Data = id3Track.pesData;
  11676. var unknownPID = null;
  11677. var pmtParsed = this.pmtParsed;
  11678. var pmtId = this._pmtId;
  11679. var len = data.length;
  11680. if (this.remainderData) {
  11681. data = appendUint8Array(this.remainderData, data);
  11682. len = data.length;
  11683. this.remainderData = null;
  11684. }
  11685. if (len < PACKET_LENGTH && !flush) {
  11686. this.remainderData = data;
  11687. return {
  11688. audioTrack: audioTrack,
  11689. videoTrack: videoTrack,
  11690. id3Track: id3Track,
  11691. textTrack: textTrack
  11692. };
  11693. }
  11694. var syncOffset = Math.max(0, TSDemuxer.syncOffset(data));
  11695. len -= (len - syncOffset) % PACKET_LENGTH;
  11696. if (len < data.byteLength && !flush) {
  11697. this.remainderData = new Uint8Array(data.buffer, len, data.buffer.byteLength - len);
  11698. }
  11699. // loop through TS packets
  11700. var tsPacketErrors = 0;
  11701. for (var start = syncOffset; start < len; start += PACKET_LENGTH) {
  11702. if (data[start] === 0x47) {
  11703. var stt = !!(data[start + 1] & 0x40);
  11704. var pid = parsePID(data, start);
  11705. var atf = (data[start + 3] & 0x30) >> 4;
  11706. // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.
  11707. var offset = void 0;
  11708. if (atf > 1) {
  11709. offset = start + 5 + data[start + 4];
  11710. // continue if there is only adaptation field
  11711. if (offset === start + PACKET_LENGTH) {
  11712. continue;
  11713. }
  11714. } else {
  11715. offset = start + 4;
  11716. }
  11717. switch (pid) {
  11718. case videoPid:
  11719. if (stt) {
  11720. if (videoData && (pes = parsePES(videoData, this.logger))) {
  11721. if (this.videoParser === null) {
  11722. switch (videoTrack.segmentCodec) {
  11723. case 'avc':
  11724. this.videoParser = new AvcVideoParser();
  11725. break;
  11726. }
  11727. }
  11728. if (this.videoParser !== null) {
  11729. this.videoParser.parsePES(videoTrack, textTrack, pes, false);
  11730. }
  11731. }
  11732. videoData = {
  11733. data: [],
  11734. size: 0
  11735. };
  11736. }
  11737. if (videoData) {
  11738. videoData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  11739. videoData.size += start + PACKET_LENGTH - offset;
  11740. }
  11741. break;
  11742. case audioPid:
  11743. if (stt) {
  11744. if (audioData && (pes = parsePES(audioData, this.logger))) {
  11745. switch (audioTrack.segmentCodec) {
  11746. case 'aac':
  11747. this.parseAACPES(audioTrack, pes);
  11748. break;
  11749. case 'mp3':
  11750. this.parseMPEGPES(audioTrack, pes);
  11751. break;
  11752. }
  11753. }
  11754. audioData = {
  11755. data: [],
  11756. size: 0
  11757. };
  11758. }
  11759. if (audioData) {
  11760. audioData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  11761. audioData.size += start + PACKET_LENGTH - offset;
  11762. }
  11763. break;
  11764. case id3Pid:
  11765. if (stt) {
  11766. if (id3Data && (pes = parsePES(id3Data, this.logger))) {
  11767. this.parseID3PES(id3Track, pes);
  11768. }
  11769. id3Data = {
  11770. data: [],
  11771. size: 0
  11772. };
  11773. }
  11774. if (id3Data) {
  11775. id3Data.data.push(data.subarray(offset, start + PACKET_LENGTH));
  11776. id3Data.size += start + PACKET_LENGTH - offset;
  11777. }
  11778. break;
  11779. case 0:
  11780. if (stt) {
  11781. offset += data[offset] + 1;
  11782. }
  11783. pmtId = this._pmtId = parsePAT(data, offset);
  11784. // this.logger.log('PMT PID:' + this._pmtId);
  11785. break;
  11786. case pmtId:
  11787. {
  11788. if (stt) {
  11789. offset += data[offset] + 1;
  11790. }
  11791. var parsedPIDs = parsePMT(data, offset, this.typeSupported, isSampleAes, this.observer, this.logger);
  11792. // only update track id if track PID found while parsing PMT
  11793. // this is to avoid resetting the PID to -1 in case
  11794. // track PID transiently disappears from the stream
  11795. // this could happen in case of transient missing audio samples for example
  11796. // NOTE this is only the PID of the track as found in TS,
  11797. // but we are not using this for MP4 track IDs.
  11798. videoPid = parsedPIDs.videoPid;
  11799. if (videoPid > 0) {
  11800. videoTrack.pid = videoPid;
  11801. videoTrack.segmentCodec = parsedPIDs.segmentVideoCodec;
  11802. }
  11803. audioPid = parsedPIDs.audioPid;
  11804. if (audioPid > 0) {
  11805. audioTrack.pid = audioPid;
  11806. audioTrack.segmentCodec = parsedPIDs.segmentAudioCodec;
  11807. }
  11808. id3Pid = parsedPIDs.id3Pid;
  11809. if (id3Pid > 0) {
  11810. id3Track.pid = id3Pid;
  11811. }
  11812. if (unknownPID !== null && !pmtParsed) {
  11813. this.logger.warn("MPEG-TS PMT found at " + start + " after unknown PID '" + unknownPID + "'. Backtracking to sync byte @" + syncOffset + " to parse all TS packets.");
  11814. unknownPID = null;
  11815. // we set it to -188, the += 188 in the for loop will reset start to 0
  11816. start = syncOffset - 188;
  11817. }
  11818. pmtParsed = this.pmtParsed = true;
  11819. break;
  11820. }
  11821. case 0x11:
  11822. case 0x1fff:
  11823. break;
  11824. default:
  11825. unknownPID = pid;
  11826. break;
  11827. }
  11828. } else {
  11829. tsPacketErrors++;
  11830. }
  11831. }
  11832. if (tsPacketErrors > 0) {
  11833. emitParsingError(this.observer, new Error("Found " + tsPacketErrors + " TS packet/s that do not start with 0x47"), undefined, this.logger);
  11834. }
  11835. videoTrack.pesData = videoData;
  11836. audioTrack.pesData = audioData;
  11837. id3Track.pesData = id3Data;
  11838. var demuxResult = {
  11839. audioTrack: audioTrack,
  11840. videoTrack: videoTrack,
  11841. id3Track: id3Track,
  11842. textTrack: textTrack
  11843. };
  11844. if (flush) {
  11845. this.extractRemainingSamples(demuxResult);
  11846. }
  11847. return demuxResult;
  11848. };
  11849. _proto.flush = function flush() {
  11850. var remainderData = this.remainderData;
  11851. this.remainderData = null;
  11852. var result;
  11853. if (remainderData) {
  11854. result = this.demux(remainderData, -1, false, true);
  11855. } else {
  11856. result = {
  11857. videoTrack: this._videoTrack,
  11858. audioTrack: this._audioTrack,
  11859. id3Track: this._id3Track,
  11860. textTrack: this._txtTrack
  11861. };
  11862. }
  11863. this.extractRemainingSamples(result);
  11864. if (this.sampleAes) {
  11865. return this.decrypt(result, this.sampleAes);
  11866. }
  11867. return result;
  11868. };
  11869. _proto.extractRemainingSamples = function extractRemainingSamples(demuxResult) {
  11870. var audioTrack = demuxResult.audioTrack,
  11871. videoTrack = demuxResult.videoTrack,
  11872. id3Track = demuxResult.id3Track,
  11873. textTrack = demuxResult.textTrack;
  11874. var videoData = videoTrack.pesData;
  11875. var audioData = audioTrack.pesData;
  11876. var id3Data = id3Track.pesData;
  11877. // try to parse last PES packets
  11878. var pes;
  11879. if (videoData && (pes = parsePES(videoData, this.logger))) {
  11880. if (this.videoParser === null) {
  11881. switch (videoTrack.segmentCodec) {
  11882. case 'avc':
  11883. this.videoParser = new AvcVideoParser();
  11884. break;
  11885. }
  11886. }
  11887. if (this.videoParser !== null) {
  11888. this.videoParser.parsePES(videoTrack, textTrack, pes, true);
  11889. videoTrack.pesData = null;
  11890. }
  11891. } else {
  11892. // either avcData null or PES truncated, keep it for next frag parsing
  11893. videoTrack.pesData = videoData;
  11894. }
  11895. if (audioData && (pes = parsePES(audioData, this.logger))) {
  11896. switch (audioTrack.segmentCodec) {
  11897. case 'aac':
  11898. this.parseAACPES(audioTrack, pes);
  11899. break;
  11900. case 'mp3':
  11901. this.parseMPEGPES(audioTrack, pes);
  11902. break;
  11903. }
  11904. audioTrack.pesData = null;
  11905. } else {
  11906. if (audioData != null && audioData.size) {
  11907. this.logger.log('last AAC PES packet truncated,might overlap between fragments');
  11908. }
  11909. // either audioData null or PES truncated, keep it for next frag parsing
  11910. audioTrack.pesData = audioData;
  11911. }
  11912. if (id3Data && (pes = parsePES(id3Data, this.logger))) {
  11913. this.parseID3PES(id3Track, pes);
  11914. id3Track.pesData = null;
  11915. } else {
  11916. // either id3Data null or PES truncated, keep it for next frag parsing
  11917. id3Track.pesData = id3Data;
  11918. }
  11919. };
  11920. _proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
  11921. var demuxResult = this.demux(data, timeOffset, true, !this.config.progressive);
  11922. var sampleAes = this.sampleAes = new SampleAesDecrypter(this.observer, this.config, keyData);
  11923. return this.decrypt(demuxResult, sampleAes);
  11924. };
  11925. _proto.decrypt = function decrypt(demuxResult, sampleAes) {
  11926. return new Promise(function (resolve) {
  11927. var audioTrack = demuxResult.audioTrack,
  11928. videoTrack = demuxResult.videoTrack;
  11929. if (audioTrack.samples && audioTrack.segmentCodec === 'aac') {
  11930. sampleAes.decryptAacSamples(audioTrack.samples, 0, function () {
  11931. if (videoTrack.samples) {
  11932. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, function () {
  11933. resolve(demuxResult);
  11934. });
  11935. } else {
  11936. resolve(demuxResult);
  11937. }
  11938. });
  11939. } else if (videoTrack.samples) {
  11940. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, function () {
  11941. resolve(demuxResult);
  11942. });
  11943. }
  11944. });
  11945. };
  11946. _proto.destroy = function destroy() {
  11947. if (this.observer) {
  11948. this.observer.removeAllListeners();
  11949. }
  11950. // @ts-ignore
  11951. this.config = this.logger = this.observer = null;
  11952. this.aacOverFlow = this.videoParser = this.remainderData = this.sampleAes = null;
  11953. this._videoTrack = this._audioTrack = this._id3Track = this._txtTrack = undefined;
  11954. };
  11955. _proto.parseAACPES = function parseAACPES(track, pes) {
  11956. var startOffset = 0;
  11957. var aacOverFlow = this.aacOverFlow;
  11958. var data = pes.data;
  11959. if (aacOverFlow) {
  11960. this.aacOverFlow = null;
  11961. var frameMissingBytes = aacOverFlow.missing;
  11962. var sampleLength = aacOverFlow.sample.unit.byteLength;
  11963. // logger.log(`AAC: append overflowing ${sampleLength} bytes to beginning of new PES`);
  11964. if (frameMissingBytes === -1) {
  11965. data = appendUint8Array(aacOverFlow.sample.unit, data);
  11966. } else {
  11967. var frameOverflowBytes = sampleLength - frameMissingBytes;
  11968. aacOverFlow.sample.unit.set(data.subarray(0, frameMissingBytes), frameOverflowBytes);
  11969. track.samples.push(aacOverFlow.sample);
  11970. startOffset = aacOverFlow.missing;
  11971. }
  11972. }
  11973. // look for ADTS header (0xFFFx)
  11974. var offset;
  11975. var len;
  11976. for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
  11977. if (isHeader$1(data, offset)) {
  11978. break;
  11979. }
  11980. }
  11981. // if ADTS header does not start straight from the beginning of the PES payload, raise an error
  11982. if (offset !== startOffset) {
  11983. var reason;
  11984. var recoverable = offset < len - 1;
  11985. if (recoverable) {
  11986. reason = "AAC PES did not start with ADTS header,offset:" + offset;
  11987. } else {
  11988. reason = 'No ADTS header found in AAC PES';
  11989. }
  11990. emitParsingError(this.observer, new Error(reason), recoverable, this.logger);
  11991. if (!recoverable) {
  11992. return;
  11993. }
  11994. }
  11995. initTrackConfig(track, this.observer, data, offset, this.audioCodec);
  11996. var pts;
  11997. if (pes.pts !== undefined) {
  11998. pts = pes.pts;
  11999. } else if (aacOverFlow) {
  12000. // if last AAC frame is overflowing, we should ensure timestamps are contiguous:
  12001. // first sample PTS should be equal to last sample PTS + frameDuration
  12002. var frameDuration = getFrameDuration(track.samplerate);
  12003. pts = aacOverFlow.sample.pts + frameDuration;
  12004. } else {
  12005. this.logger.warn('[tsdemuxer]: AAC PES unknown PTS');
  12006. return;
  12007. }
  12008. // scan for aac samples
  12009. var frameIndex = 0;
  12010. var frame;
  12011. while (offset < len) {
  12012. frame = appendFrame$1(track, data, offset, pts, frameIndex);
  12013. offset += frame.length;
  12014. if (!frame.missing) {
  12015. frameIndex++;
  12016. for (; offset < len - 1; offset++) {
  12017. if (isHeader$1(data, offset)) {
  12018. break;
  12019. }
  12020. }
  12021. } else {
  12022. this.aacOverFlow = frame;
  12023. break;
  12024. }
  12025. }
  12026. };
  12027. _proto.parseMPEGPES = function parseMPEGPES(track, pes) {
  12028. var data = pes.data;
  12029. var length = data.length;
  12030. var frameIndex = 0;
  12031. var offset = 0;
  12032. var pts = pes.pts;
  12033. if (pts === undefined) {
  12034. this.logger.warn('[tsdemuxer]: MPEG PES unknown PTS');
  12035. return;
  12036. }
  12037. while (offset < length) {
  12038. if (isHeader(data, offset)) {
  12039. var frame = appendFrame(track, data, offset, pts, frameIndex);
  12040. if (frame) {
  12041. offset += frame.length;
  12042. frameIndex++;
  12043. } else {
  12044. // logger.log('Unable to parse Mpeg audio frame');
  12045. break;
  12046. }
  12047. } else {
  12048. // nothing found, keep looking
  12049. offset++;
  12050. }
  12051. }
  12052. };
  12053. _proto.parseAC3PES = function parseAC3PES(track, pes) {
  12054. };
  12055. _proto.parseID3PES = function parseID3PES(id3Track, pes) {
  12056. if (pes.pts === undefined) {
  12057. this.logger.warn('[tsdemuxer]: ID3 PES unknown PTS');
  12058. return;
  12059. }
  12060. var id3Sample = _extends({}, pes, {
  12061. type: this._videoTrack ? MetadataSchema.emsg : MetadataSchema.audioId3,
  12062. duration: Number.POSITIVE_INFINITY
  12063. });
  12064. id3Track.samples.push(id3Sample);
  12065. };
  12066. return TSDemuxer;
  12067. }();
  12068. function parsePID(data, offset) {
  12069. // pid is a 13-bit field starting at the last bit of TS[1]
  12070. return ((data[offset + 1] & 0x1f) << 8) + data[offset + 2];
  12071. }
  12072. function parsePAT(data, offset) {
  12073. // skip the PSI header and parse the first PMT entry
  12074. return (data[offset + 10] & 0x1f) << 8 | data[offset + 11];
  12075. }
  12076. function parsePMT(data, offset, typeSupported, isSampleAes, observer, logger) {
  12077. var result = {
  12078. audioPid: -1,
  12079. videoPid: -1,
  12080. id3Pid: -1,
  12081. segmentVideoCodec: 'avc',
  12082. segmentAudioCodec: 'aac'
  12083. };
  12084. var sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
  12085. var tableEnd = offset + 3 + sectionLength - 4;
  12086. // to determine where the table is, we have to figure out how
  12087. // long the program info descriptors are
  12088. var programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11];
  12089. // advance the offset to the first entry in the mapping table
  12090. offset += 12 + programInfoLength;
  12091. while (offset < tableEnd) {
  12092. var pid = parsePID(data, offset);
  12093. var esInfoLength = (data[offset + 3] & 0x0f) << 8 | data[offset + 4];
  12094. switch (data[offset]) {
  12095. case 0xcf:
  12096. // SAMPLE-AES AAC
  12097. if (!isSampleAes) {
  12098. logEncryptedSamplesFoundInUnencryptedStream('ADTS AAC', logger);
  12099. break;
  12100. }
  12101. /* falls through */
  12102. case 0x0f:
  12103. // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
  12104. // logger.log('AAC PID:' + pid);
  12105. if (result.audioPid === -1) {
  12106. result.audioPid = pid;
  12107. }
  12108. break;
  12109. // Packetized metadata (ID3)
  12110. case 0x15:
  12111. // logger.log('ID3 PID:' + pid);
  12112. if (result.id3Pid === -1) {
  12113. result.id3Pid = pid;
  12114. }
  12115. break;
  12116. case 0xdb:
  12117. // SAMPLE-AES AVC
  12118. if (!isSampleAes) {
  12119. logEncryptedSamplesFoundInUnencryptedStream('H.264', logger);
  12120. break;
  12121. }
  12122. /* falls through */
  12123. case 0x1b:
  12124. // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
  12125. // logger.log('AVC PID:' + pid);
  12126. if (result.videoPid === -1) {
  12127. result.videoPid = pid;
  12128. }
  12129. break;
  12130. // ISO/IEC 11172-3 (MPEG-1 audio)
  12131. // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)
  12132. case 0x03:
  12133. case 0x04:
  12134. // logger.log('MPEG PID:' + pid);
  12135. if (!typeSupported.mpeg && !typeSupported.mp3) {
  12136. logger.log('MPEG audio found, not supported in this browser');
  12137. } else if (result.audioPid === -1) {
  12138. result.audioPid = pid;
  12139. result.segmentAudioCodec = 'mp3';
  12140. }
  12141. break;
  12142. case 0xc1:
  12143. // SAMPLE-AES AC3
  12144. if (!isSampleAes) {
  12145. logEncryptedSamplesFoundInUnencryptedStream('AC-3', logger);
  12146. break;
  12147. }
  12148. /* falls through */
  12149. case 0x81:
  12150. {
  12151. logger.warn('AC-3 in M2TS support not included in build');
  12152. }
  12153. break;
  12154. case 0x06:
  12155. // stream_type 6 can mean a lot of different things in case of DVB.
  12156. // We need to look at the descriptors. Right now, we're only interested
  12157. // in AC-3 audio, so we do the descriptor parsing only when we don't have
  12158. // an audio PID yet.
  12159. if (result.audioPid === -1 && esInfoLength > 0) {
  12160. var parsePos = offset + 5;
  12161. var remaining = esInfoLength;
  12162. while (remaining > 2) {
  12163. var descriptorId = data[parsePos];
  12164. switch (descriptorId) {
  12165. case 0x6a:
  12166. // DVB Descriptor for AC-3
  12167. {
  12168. logger.warn('AC-3 in M2TS support not included in build');
  12169. }
  12170. break;
  12171. }
  12172. var descriptorLen = data[parsePos + 1] + 2;
  12173. parsePos += descriptorLen;
  12174. remaining -= descriptorLen;
  12175. }
  12176. }
  12177. break;
  12178. case 0xc2: // SAMPLE-AES EC3
  12179. /* falls through */
  12180. case 0x87:
  12181. emitParsingError(observer, new Error('Unsupported EC-3 in M2TS found'), undefined, logger);
  12182. return result;
  12183. case 0x24:
  12184. // ITU-T Rec. H.265 and ISO/IEC 23008-2 (HEVC)
  12185. {
  12186. emitParsingError(observer, new Error('Unsupported HEVC in M2TS found'), undefined, logger);
  12187. return result;
  12188. }
  12189. }
  12190. // move to the next table entry
  12191. // skip past the elementary stream descriptors, if present
  12192. offset += esInfoLength + 5;
  12193. }
  12194. return result;
  12195. }
  12196. function emitParsingError(observer, error, levelRetry, logger) {
  12197. logger.warn("parsing error: " + error.message);
  12198. observer.emit(Events.ERROR, Events.ERROR, {
  12199. type: ErrorTypes.MEDIA_ERROR,
  12200. details: ErrorDetails.FRAG_PARSING_ERROR,
  12201. fatal: false,
  12202. levelRetry: levelRetry,
  12203. error: error,
  12204. reason: error.message
  12205. });
  12206. }
  12207. function logEncryptedSamplesFoundInUnencryptedStream(type, logger) {
  12208. logger.log(type + " with AES-128-CBC encryption found in unencrypted stream");
  12209. }
  12210. function parsePES(stream, logger) {
  12211. var i = 0;
  12212. var frag;
  12213. var pesLen;
  12214. var pesHdrLen;
  12215. var pesPts;
  12216. var pesDts;
  12217. var data = stream.data;
  12218. // safety check
  12219. if (!stream || stream.size === 0) {
  12220. return null;
  12221. }
  12222. // we might need up to 19 bytes to read PES header
  12223. // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes
  12224. // usually only one merge is needed (and this is rare ...)
  12225. while (data[0].length < 19 && data.length > 1) {
  12226. data[0] = appendUint8Array(data[0], data[1]);
  12227. data.splice(1, 1);
  12228. }
  12229. // retrieve PTS/DTS from first fragment
  12230. frag = data[0];
  12231. var pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
  12232. if (pesPrefix === 1) {
  12233. pesLen = (frag[4] << 8) + frag[5];
  12234. // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated
  12235. // minus 6 : PES header size
  12236. if (pesLen && pesLen > stream.size - 6) {
  12237. return null;
  12238. }
  12239. var pesFlags = frag[7];
  12240. if (pesFlags & 0xc0) {
  12241. /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  12242. as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
  12243. as Bitwise operators treat their operands as a sequence of 32 bits */
  12244. pesPts = (frag[9] & 0x0e) * 536870912 +
  12245. // 1 << 29
  12246. (frag[10] & 0xff) * 4194304 +
  12247. // 1 << 22
  12248. (frag[11] & 0xfe) * 16384 +
  12249. // 1 << 14
  12250. (frag[12] & 0xff) * 128 +
  12251. // 1 << 7
  12252. (frag[13] & 0xfe) / 2;
  12253. if (pesFlags & 0x40) {
  12254. pesDts = (frag[14] & 0x0e) * 536870912 +
  12255. // 1 << 29
  12256. (frag[15] & 0xff) * 4194304 +
  12257. // 1 << 22
  12258. (frag[16] & 0xfe) * 16384 +
  12259. // 1 << 14
  12260. (frag[17] & 0xff) * 128 +
  12261. // 1 << 7
  12262. (frag[18] & 0xfe) / 2;
  12263. if (pesPts - pesDts > 60 * 90000) {
  12264. logger.warn(Math.round((pesPts - pesDts) / 90000) + "s delta between PTS and DTS, align them");
  12265. pesPts = pesDts;
  12266. }
  12267. } else {
  12268. pesDts = pesPts;
  12269. }
  12270. }
  12271. pesHdrLen = frag[8];
  12272. // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension
  12273. var payloadStartOffset = pesHdrLen + 9;
  12274. if (stream.size <= payloadStartOffset) {
  12275. return null;
  12276. }
  12277. stream.size -= payloadStartOffset;
  12278. // reassemble PES packet
  12279. var pesData = new Uint8Array(stream.size);
  12280. for (var j = 0, dataLen = data.length; j < dataLen; j++) {
  12281. frag = data[j];
  12282. var len = frag.byteLength;
  12283. if (payloadStartOffset) {
  12284. if (payloadStartOffset > len) {
  12285. // trim full frag if PES header bigger than frag
  12286. payloadStartOffset -= len;
  12287. continue;
  12288. } else {
  12289. // trim partial frag if PES header smaller than frag
  12290. frag = frag.subarray(payloadStartOffset);
  12291. len -= payloadStartOffset;
  12292. payloadStartOffset = 0;
  12293. }
  12294. }
  12295. pesData.set(frag, i);
  12296. i += len;
  12297. }
  12298. if (pesLen) {
  12299. // payload size : remove PES header + PES extension
  12300. pesLen -= pesHdrLen + 3;
  12301. }
  12302. return {
  12303. data: pesData,
  12304. pts: pesPts,
  12305. dts: pesDts,
  12306. len: pesLen
  12307. };
  12308. }
  12309. return null;
  12310. }
  12311. /**
  12312. * AAC helper
  12313. */
  12314. var AAC = /*#__PURE__*/function () {
  12315. function AAC() {}
  12316. AAC.getSilentFrame = function getSilentFrame(codec, channelCount) {
  12317. switch (codec) {
  12318. case 'mp4a.40.2':
  12319. if (channelCount === 1) {
  12320. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
  12321. } else if (channelCount === 2) {
  12322. return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
  12323. } else if (channelCount === 3) {
  12324. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
  12325. } else if (channelCount === 4) {
  12326. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
  12327. } else if (channelCount === 5) {
  12328. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
  12329. } else if (channelCount === 6) {
  12330. 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]);
  12331. }
  12332. break;
  12333. // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)
  12334. default:
  12335. if (channelCount === 1) {
  12336. // 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
  12337. 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]);
  12338. } else if (channelCount === 2) {
  12339. // 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
  12340. 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]);
  12341. } else if (channelCount === 3) {
  12342. // 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
  12343. 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]);
  12344. }
  12345. break;
  12346. }
  12347. return undefined;
  12348. };
  12349. return AAC;
  12350. }();
  12351. /**
  12352. * Generate MP4 Box
  12353. */
  12354. var UINT32_MAX = Math.pow(2, 32) - 1;
  12355. var MP4 = /*#__PURE__*/function () {
  12356. function MP4() {}
  12357. MP4.init = function init() {
  12358. MP4.types = {
  12359. avc1: [],
  12360. // codingname
  12361. avcC: [],
  12362. hvc1: [],
  12363. hvcC: [],
  12364. btrt: [],
  12365. dinf: [],
  12366. dref: [],
  12367. esds: [],
  12368. ftyp: [],
  12369. hdlr: [],
  12370. mdat: [],
  12371. mdhd: [],
  12372. mdia: [],
  12373. mfhd: [],
  12374. minf: [],
  12375. moof: [],
  12376. moov: [],
  12377. mp4a: [],
  12378. '.mp3': [],
  12379. dac3: [],
  12380. 'ac-3': [],
  12381. mvex: [],
  12382. mvhd: [],
  12383. pasp: [],
  12384. sdtp: [],
  12385. stbl: [],
  12386. stco: [],
  12387. stsc: [],
  12388. stsd: [],
  12389. stsz: [],
  12390. stts: [],
  12391. tfdt: [],
  12392. tfhd: [],
  12393. traf: [],
  12394. trak: [],
  12395. trun: [],
  12396. trex: [],
  12397. tkhd: [],
  12398. vmhd: [],
  12399. smhd: []
  12400. };
  12401. var i;
  12402. for (i in MP4.types) {
  12403. if (MP4.types.hasOwnProperty(i)) {
  12404. MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  12405. }
  12406. }
  12407. var videoHdlr = new Uint8Array([0x00,
  12408. // version 0
  12409. 0x00, 0x00, 0x00,
  12410. // flags
  12411. 0x00, 0x00, 0x00, 0x00,
  12412. // pre_defined
  12413. 0x76, 0x69, 0x64, 0x65,
  12414. // handler_type: 'vide'
  12415. 0x00, 0x00, 0x00, 0x00,
  12416. // reserved
  12417. 0x00, 0x00, 0x00, 0x00,
  12418. // reserved
  12419. 0x00, 0x00, 0x00, 0x00,
  12420. // reserved
  12421. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  12422. ]);
  12423. var audioHdlr = new Uint8Array([0x00,
  12424. // version 0
  12425. 0x00, 0x00, 0x00,
  12426. // flags
  12427. 0x00, 0x00, 0x00, 0x00,
  12428. // pre_defined
  12429. 0x73, 0x6f, 0x75, 0x6e,
  12430. // handler_type: 'soun'
  12431. 0x00, 0x00, 0x00, 0x00,
  12432. // reserved
  12433. 0x00, 0x00, 0x00, 0x00,
  12434. // reserved
  12435. 0x00, 0x00, 0x00, 0x00,
  12436. // reserved
  12437. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  12438. ]);
  12439. MP4.HDLR_TYPES = {
  12440. video: videoHdlr,
  12441. audio: audioHdlr
  12442. };
  12443. var dref = new Uint8Array([0x00,
  12444. // version 0
  12445. 0x00, 0x00, 0x00,
  12446. // flags
  12447. 0x00, 0x00, 0x00, 0x01,
  12448. // entry_count
  12449. 0x00, 0x00, 0x00, 0x0c,
  12450. // entry_size
  12451. 0x75, 0x72, 0x6c, 0x20,
  12452. // 'url' type
  12453. 0x00,
  12454. // version 0
  12455. 0x00, 0x00, 0x01 // entry_flags
  12456. ]);
  12457. var stco = new Uint8Array([0x00,
  12458. // version
  12459. 0x00, 0x00, 0x00,
  12460. // flags
  12461. 0x00, 0x00, 0x00, 0x00 // entry_count
  12462. ]);
  12463. MP4.STTS = MP4.STSC = MP4.STCO = stco;
  12464. MP4.STSZ = new Uint8Array([0x00,
  12465. // version
  12466. 0x00, 0x00, 0x00,
  12467. // flags
  12468. 0x00, 0x00, 0x00, 0x00,
  12469. // sample_size
  12470. 0x00, 0x00, 0x00, 0x00 // sample_count
  12471. ]);
  12472. MP4.VMHD = new Uint8Array([0x00,
  12473. // version
  12474. 0x00, 0x00, 0x01,
  12475. // flags
  12476. 0x00, 0x00,
  12477. // graphicsmode
  12478. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  12479. ]);
  12480. MP4.SMHD = new Uint8Array([0x00,
  12481. // version
  12482. 0x00, 0x00, 0x00,
  12483. // flags
  12484. 0x00, 0x00,
  12485. // balance
  12486. 0x00, 0x00 // reserved
  12487. ]);
  12488. MP4.STSD = new Uint8Array([0x00,
  12489. // version 0
  12490. 0x00, 0x00, 0x00,
  12491. // flags
  12492. 0x00, 0x00, 0x00, 0x01]); // entry_count
  12493. var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom
  12494. var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1
  12495. var minorVersion = new Uint8Array([0, 0, 0, 1]);
  12496. MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
  12497. MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
  12498. };
  12499. MP4.box = function box(type) {
  12500. var size = 8;
  12501. for (var _len = arguments.length, payload = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  12502. payload[_key - 1] = arguments[_key];
  12503. }
  12504. var i = payload.length;
  12505. var len = i;
  12506. // calculate the total size we need to allocate
  12507. while (i--) {
  12508. size += payload[i].byteLength;
  12509. }
  12510. var result = new Uint8Array(size);
  12511. result[0] = size >> 24 & 0xff;
  12512. result[1] = size >> 16 & 0xff;
  12513. result[2] = size >> 8 & 0xff;
  12514. result[3] = size & 0xff;
  12515. result.set(type, 4);
  12516. // copy the payload into the result
  12517. for (i = 0, size = 8; i < len; i++) {
  12518. // copy payload[i] array @ offset size
  12519. result.set(payload[i], size);
  12520. size += payload[i].byteLength;
  12521. }
  12522. return result;
  12523. };
  12524. MP4.hdlr = function hdlr(type) {
  12525. return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
  12526. };
  12527. MP4.mdat = function mdat(data) {
  12528. return MP4.box(MP4.types.mdat, data);
  12529. };
  12530. MP4.mdhd = function mdhd(timescale, duration) {
  12531. duration *= timescale;
  12532. var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  12533. var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  12534. return MP4.box(MP4.types.mdhd, new Uint8Array([0x01,
  12535. // version 1
  12536. 0x00, 0x00, 0x00,
  12537. // flags
  12538. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  12539. // creation_time
  12540. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  12541. // modification_time
  12542. timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff,
  12543. // timescale
  12544. upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x55, 0xc4,
  12545. // 'und' language (undetermined)
  12546. 0x00, 0x00]));
  12547. };
  12548. MP4.mdia = function mdia(track) {
  12549. return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale || 0, track.duration || 0), MP4.hdlr(track.type), MP4.minf(track));
  12550. };
  12551. MP4.mfhd = function mfhd(sequenceNumber) {
  12552. return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00,
  12553. // flags
  12554. sequenceNumber >> 24, sequenceNumber >> 16 & 0xff, sequenceNumber >> 8 & 0xff, sequenceNumber & 0xff // sequence_number
  12555. ]));
  12556. };
  12557. MP4.minf = function minf(track) {
  12558. if (track.type === 'audio') {
  12559. return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
  12560. } else {
  12561. return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
  12562. }
  12563. };
  12564. MP4.moof = function moof(sn, baseMediaDecodeTime, track) {
  12565. return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
  12566. };
  12567. MP4.moov = function moov(tracks) {
  12568. var i = tracks.length;
  12569. var boxes = [];
  12570. while (i--) {
  12571. boxes[i] = MP4.trak(tracks[i]);
  12572. }
  12573. return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale || 0, tracks[0].duration || 0)].concat(boxes).concat(MP4.mvex(tracks)));
  12574. };
  12575. MP4.mvex = function mvex(tracks) {
  12576. var i = tracks.length;
  12577. var boxes = [];
  12578. while (i--) {
  12579. boxes[i] = MP4.trex(tracks[i]);
  12580. }
  12581. return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));
  12582. };
  12583. MP4.mvhd = function mvhd(timescale, duration) {
  12584. duration *= timescale;
  12585. var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  12586. var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  12587. var bytes = new Uint8Array([0x01,
  12588. // version 1
  12589. 0x00, 0x00, 0x00,
  12590. // flags
  12591. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  12592. // creation_time
  12593. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  12594. // modification_time
  12595. timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff,
  12596. // timescale
  12597. upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x00, 0x01, 0x00, 0x00,
  12598. // 1.0 rate
  12599. 0x01, 0x00,
  12600. // 1.0 volume
  12601. 0x00, 0x00,
  12602. // reserved
  12603. 0x00, 0x00, 0x00, 0x00,
  12604. // reserved
  12605. 0x00, 0x00, 0x00, 0x00,
  12606. // reserved
  12607. 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,
  12608. // transformation: unity matrix
  12609. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  12610. // pre_defined
  12611. 0xff, 0xff, 0xff, 0xff // next_track_ID
  12612. ]);
  12613. return MP4.box(MP4.types.mvhd, bytes);
  12614. };
  12615. MP4.sdtp = function sdtp(track) {
  12616. var samples = track.samples || [];
  12617. var bytes = new Uint8Array(4 + samples.length);
  12618. var i;
  12619. var flags;
  12620. // leave the full box header (4 bytes) all zero
  12621. // write the sample table
  12622. for (i = 0; i < samples.length; i++) {
  12623. flags = samples[i].flags;
  12624. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  12625. }
  12626. return MP4.box(MP4.types.sdtp, bytes);
  12627. };
  12628. MP4.stbl = function stbl(track) {
  12629. 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));
  12630. };
  12631. MP4.avc1 = function avc1(track) {
  12632. var sps = [];
  12633. var pps = [];
  12634. var i;
  12635. var data;
  12636. var len;
  12637. // assemble the SPSs
  12638. for (i = 0; i < track.sps.length; i++) {
  12639. data = track.sps[i];
  12640. len = data.byteLength;
  12641. sps.push(len >>> 8 & 0xff);
  12642. sps.push(len & 0xff);
  12643. // SPS
  12644. sps = sps.concat(Array.prototype.slice.call(data));
  12645. }
  12646. // assemble the PPSs
  12647. for (i = 0; i < track.pps.length; i++) {
  12648. data = track.pps[i];
  12649. len = data.byteLength;
  12650. pps.push(len >>> 8 & 0xff);
  12651. pps.push(len & 0xff);
  12652. pps = pps.concat(Array.prototype.slice.call(data));
  12653. }
  12654. var avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01,
  12655. // version
  12656. sps[3],
  12657. // profile
  12658. sps[4],
  12659. // profile compat
  12660. sps[5],
  12661. // level
  12662. 0xfc | 3,
  12663. // lengthSizeMinusOne, hard-coded to 4 bytes
  12664. 0xe0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets
  12665. ].concat(sps).concat([track.pps.length // numOfPictureParameterSets
  12666. ]).concat(pps))); // "PPS"
  12667. var width = track.width;
  12668. var height = track.height;
  12669. var hSpacing = track.pixelRatio[0];
  12670. var vSpacing = track.pixelRatio[1];
  12671. return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00,
  12672. // reserved
  12673. 0x00, 0x00, 0x00,
  12674. // reserved
  12675. 0x00, 0x01,
  12676. // data_reference_index
  12677. 0x00, 0x00,
  12678. // pre_defined
  12679. 0x00, 0x00,
  12680. // reserved
  12681. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  12682. // pre_defined
  12683. width >> 8 & 0xff, width & 0xff,
  12684. // width
  12685. height >> 8 & 0xff, height & 0xff,
  12686. // height
  12687. 0x00, 0x48, 0x00, 0x00,
  12688. // horizresolution
  12689. 0x00, 0x48, 0x00, 0x00,
  12690. // vertresolution
  12691. 0x00, 0x00, 0x00, 0x00,
  12692. // reserved
  12693. 0x00, 0x01,
  12694. // frame_count
  12695. 0x12, 0x64, 0x61, 0x69, 0x6c,
  12696. // dailymotion/hls.js
  12697. 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,
  12698. // compressorname
  12699. 0x00, 0x18,
  12700. // depth = 24
  12701. 0x11, 0x11]),
  12702. // pre_defined = -1
  12703. avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80,
  12704. // bufferSizeDB
  12705. 0x00, 0x2d, 0xc6, 0xc0,
  12706. // maxBitrate
  12707. 0x00, 0x2d, 0xc6, 0xc0])),
  12708. // avgBitrate
  12709. MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24,
  12710. // hSpacing
  12711. hSpacing >> 16 & 0xff, hSpacing >> 8 & 0xff, hSpacing & 0xff, vSpacing >> 24,
  12712. // vSpacing
  12713. vSpacing >> 16 & 0xff, vSpacing >> 8 & 0xff, vSpacing & 0xff])));
  12714. };
  12715. MP4.esds = function esds(track) {
  12716. var config = track.config;
  12717. return new Uint8Array([0x00,
  12718. // version 0
  12719. 0x00, 0x00, 0x00,
  12720. // flags
  12721. 0x03,
  12722. // descriptor_type
  12723. 0x19,
  12724. // length
  12725. 0x00, 0x01,
  12726. // es_id
  12727. 0x00,
  12728. // stream_priority
  12729. 0x04,
  12730. // descriptor_type
  12731. 0x11,
  12732. // length
  12733. 0x40,
  12734. // codec : mpeg4_audio
  12735. 0x15,
  12736. // stream_type
  12737. 0x00, 0x00, 0x00,
  12738. // buffer_size
  12739. 0x00, 0x00, 0x00, 0x00,
  12740. // maxBitrate
  12741. 0x00, 0x00, 0x00, 0x00,
  12742. // avgBitrate
  12743. 0x05,
  12744. // descriptor_type
  12745. 0x02].concat(config, [0x06, 0x01, 0x02 // GASpecificConfig)); // length + audio config descriptor
  12746. ]));
  12747. };
  12748. MP4.audioStsd = function audioStsd(track) {
  12749. var samplerate = track.samplerate || 0;
  12750. return new Uint8Array([0x00, 0x00, 0x00,
  12751. // reserved
  12752. 0x00, 0x00, 0x00,
  12753. // reserved
  12754. 0x00, 0x01,
  12755. // data_reference_index
  12756. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  12757. // reserved
  12758. 0x00, track.channelCount || 0,
  12759. // channelcount
  12760. 0x00, 0x10,
  12761. // sampleSize:16bits
  12762. 0x00, 0x00, 0x00, 0x00,
  12763. // reserved2
  12764. samplerate >> 8 & 0xff, samplerate & 0xff,
  12765. //
  12766. 0x00, 0x00]);
  12767. };
  12768. MP4.mp4a = function mp4a(track) {
  12769. return MP4.box(MP4.types.mp4a, MP4.audioStsd(track), MP4.box(MP4.types.esds, MP4.esds(track)));
  12770. };
  12771. MP4.mp3 = function mp3(track) {
  12772. return MP4.box(MP4.types['.mp3'], MP4.audioStsd(track));
  12773. };
  12774. MP4.ac3 = function ac3(track) {
  12775. return MP4.box(MP4.types['ac-3'], MP4.audioStsd(track), MP4.box(MP4.types.dac3, track.config));
  12776. };
  12777. MP4.stsd = function stsd(track) {
  12778. var segmentCodec = track.segmentCodec;
  12779. if (track.type === 'audio') {
  12780. if (segmentCodec === 'aac') {
  12781. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
  12782. }
  12783. if (segmentCodec === 'mp3' && track.codec === 'mp3') {
  12784. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));
  12785. }
  12786. } else {
  12787. if (track.pps && track.sps) {
  12788. if (segmentCodec === 'avc') {
  12789. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
  12790. }
  12791. } else {
  12792. throw new Error("video track missing pps or sps");
  12793. }
  12794. }
  12795. throw new Error("unsupported " + track.type + " segment codec (" + segmentCodec + "/" + track.codec + ")");
  12796. };
  12797. MP4.tkhd = function tkhd(track) {
  12798. var id = track.id;
  12799. var duration = (track.duration || 0) * (track.timescale || 0);
  12800. var width = track.width || 0;
  12801. var height = track.height || 0;
  12802. var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  12803. var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  12804. return MP4.box(MP4.types.tkhd, new Uint8Array([0x01,
  12805. // version 1
  12806. 0x00, 0x00, 0x07,
  12807. // flags
  12808. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  12809. // creation_time
  12810. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  12811. // modification_time
  12812. id >> 24 & 0xff, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff,
  12813. // track_ID
  12814. 0x00, 0x00, 0x00, 0x00,
  12815. // reserved
  12816. 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,
  12817. // reserved
  12818. 0x00, 0x00,
  12819. // layer
  12820. 0x00, 0x00,
  12821. // alternate_group
  12822. 0x00, 0x00,
  12823. // non-audio track volume
  12824. 0x00, 0x00,
  12825. // reserved
  12826. 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,
  12827. // transformation: unity matrix
  12828. width >> 8 & 0xff, width & 0xff, 0x00, 0x00,
  12829. // width
  12830. height >> 8 & 0xff, height & 0xff, 0x00, 0x00 // height
  12831. ]));
  12832. };
  12833. MP4.traf = function traf(track, baseMediaDecodeTime) {
  12834. var sampleDependencyTable = MP4.sdtp(track);
  12835. var id = track.id;
  12836. var upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
  12837. var lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
  12838. return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00,
  12839. // version 0
  12840. 0x00, 0x00, 0x00,
  12841. // flags
  12842. id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff // track_ID
  12843. ])), MP4.box(MP4.types.tfdt, new Uint8Array([0x01,
  12844. // version 1
  12845. 0x00, 0x00, 0x00,
  12846. // flags
  12847. 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 +
  12848. // tfhd
  12849. 20 +
  12850. // tfdt
  12851. 8 +
  12852. // traf header
  12853. 16 +
  12854. // mfhd
  12855. 8 +
  12856. // moof header
  12857. 8),
  12858. // mdat header
  12859. sampleDependencyTable);
  12860. }
  12861. /**
  12862. * Generate a track box.
  12863. * @param track a track definition
  12864. */;
  12865. MP4.trak = function trak(track) {
  12866. track.duration = track.duration || 0xffffffff;
  12867. return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
  12868. };
  12869. MP4.trex = function trex(track) {
  12870. var id = track.id;
  12871. return MP4.box(MP4.types.trex, new Uint8Array([0x00,
  12872. // version 0
  12873. 0x00, 0x00, 0x00,
  12874. // flags
  12875. id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff,
  12876. // track_ID
  12877. 0x00, 0x00, 0x00, 0x01,
  12878. // default_sample_description_index
  12879. 0x00, 0x00, 0x00, 0x00,
  12880. // default_sample_duration
  12881. 0x00, 0x00, 0x00, 0x00,
  12882. // default_sample_size
  12883. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  12884. ]));
  12885. };
  12886. MP4.trun = function trun(track, offset) {
  12887. var samples = track.samples || [];
  12888. var len = samples.length;
  12889. var arraylen = 12 + 16 * len;
  12890. var array = new Uint8Array(arraylen);
  12891. var i;
  12892. var sample;
  12893. var duration;
  12894. var size;
  12895. var flags;
  12896. var cts;
  12897. offset += 8 + arraylen;
  12898. array.set([track.type === 'video' ? 0x01 : 0x00,
  12899. // version 1 for video with signed-int sample_composition_time_offset
  12900. 0x00, 0x0f, 0x01,
  12901. // flags
  12902. len >>> 24 & 0xff, len >>> 16 & 0xff, len >>> 8 & 0xff, len & 0xff,
  12903. // sample_count
  12904. offset >>> 24 & 0xff, offset >>> 16 & 0xff, offset >>> 8 & 0xff, offset & 0xff // data_offset
  12905. ], 0);
  12906. for (i = 0; i < len; i++) {
  12907. sample = samples[i];
  12908. duration = sample.duration;
  12909. size = sample.size;
  12910. flags = sample.flags;
  12911. cts = sample.cts;
  12912. array.set([duration >>> 24 & 0xff, duration >>> 16 & 0xff, duration >>> 8 & 0xff, duration & 0xff,
  12913. // sample_duration
  12914. size >>> 24 & 0xff, size >>> 16 & 0xff, size >>> 8 & 0xff, size & 0xff,
  12915. // sample_size
  12916. flags.isLeading << 2 | flags.dependsOn, flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync, flags.degradPrio & 0xf0 << 8, flags.degradPrio & 0x0f,
  12917. // sample_flags
  12918. cts >>> 24 & 0xff, cts >>> 16 & 0xff, cts >>> 8 & 0xff, cts & 0xff // sample_composition_time_offset
  12919. ], 12 + 16 * i);
  12920. }
  12921. return MP4.box(MP4.types.trun, array);
  12922. };
  12923. MP4.initSegment = function initSegment(tracks) {
  12924. if (!MP4.types) {
  12925. MP4.init();
  12926. }
  12927. var movie = MP4.moov(tracks);
  12928. var result = appendUint8Array(MP4.FTYP, movie);
  12929. return result;
  12930. };
  12931. MP4.hvc1 = function hvc1(track) {
  12932. {
  12933. return new Uint8Array();
  12934. }
  12935. };
  12936. return MP4;
  12937. }();
  12938. MP4.types = void 0;
  12939. MP4.HDLR_TYPES = void 0;
  12940. MP4.STTS = void 0;
  12941. MP4.STSC = void 0;
  12942. MP4.STCO = void 0;
  12943. MP4.STSZ = void 0;
  12944. MP4.VMHD = void 0;
  12945. MP4.SMHD = void 0;
  12946. MP4.STSD = void 0;
  12947. MP4.FTYP = void 0;
  12948. MP4.DINF = void 0;
  12949. var MPEG_TS_CLOCK_FREQ_HZ = 90000;
  12950. function toTimescaleFromBase(baseTime, destScale, srcBase, round) {
  12951. var result = baseTime * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)`
  12952. return Math.round(result) ;
  12953. }
  12954. function toMsFromMpegTsClock(baseTime, round) {
  12955. return toTimescaleFromBase(baseTime, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ);
  12956. }
  12957. var MAX_SILENT_FRAME_DURATION = 10 * 1000; // 10 seconds
  12958. var AAC_SAMPLES_PER_FRAME = 1024;
  12959. var MPEG_AUDIO_SAMPLE_PER_FRAME = 1152;
  12960. var AC3_SAMPLES_PER_FRAME = 1536;
  12961. var chromeVersion = null;
  12962. var safariWebkitVersion = null;
  12963. function createMp4Sample(isKeyframe, duration, size, cts) {
  12964. return {
  12965. duration: duration,
  12966. size: size,
  12967. cts: cts,
  12968. flags: {
  12969. isLeading: 0,
  12970. isDependedOn: 0,
  12971. hasRedundancy: 0,
  12972. degradPrio: 0,
  12973. dependsOn: isKeyframe ? 2 : 1,
  12974. isNonSync: isKeyframe ? 0 : 1
  12975. }
  12976. };
  12977. }
  12978. var MP4Remuxer = /*#__PURE__*/function (_Logger) {
  12979. function MP4Remuxer(observer, config, typeSupported, logger) {
  12980. var _this;
  12981. _this = _Logger.call(this, 'mp4-remuxer', logger) || this;
  12982. _this.observer = void 0;
  12983. _this.config = void 0;
  12984. _this.typeSupported = void 0;
  12985. _this.ISGenerated = false;
  12986. _this._initPTS = null;
  12987. _this._initDTS = null;
  12988. _this.nextVideoTs = null;
  12989. _this.nextAudioTs = null;
  12990. _this.videoSampleDuration = null;
  12991. _this.isAudioContiguous = false;
  12992. _this.isVideoContiguous = false;
  12993. _this.videoTrackConfig = void 0;
  12994. _this.observer = observer;
  12995. _this.config = config;
  12996. _this.typeSupported = typeSupported;
  12997. _this.ISGenerated = false;
  12998. if (chromeVersion === null) {
  12999. var userAgent = navigator.userAgent || '';
  13000. var result = userAgent.match(/Chrome\/(\d+)/i);
  13001. chromeVersion = result ? parseInt(result[1]) : 0;
  13002. }
  13003. if (safariWebkitVersion === null) {
  13004. var _result = navigator.userAgent.match(/Safari\/(\d+)/i);
  13005. safariWebkitVersion = _result ? parseInt(_result[1]) : 0;
  13006. }
  13007. return _this;
  13008. }
  13009. _inheritsLoose(MP4Remuxer, _Logger);
  13010. var _proto = MP4Remuxer.prototype;
  13011. _proto.destroy = function destroy() {
  13012. // @ts-ignore
  13013. this.config = this.videoTrackConfig = this._initPTS = this._initDTS = null;
  13014. };
  13015. _proto.resetTimeStamp = function resetTimeStamp(defaultTimeStamp) {
  13016. this.log('initPTS & initDTS reset');
  13017. this._initPTS = this._initDTS = defaultTimeStamp;
  13018. };
  13019. _proto.resetNextTimestamp = function resetNextTimestamp() {
  13020. this.log('reset next timestamp');
  13021. this.isVideoContiguous = false;
  13022. this.isAudioContiguous = false;
  13023. };
  13024. _proto.resetInitSegment = function resetInitSegment() {
  13025. this.log('ISGenerated flag reset');
  13026. this.ISGenerated = false;
  13027. this.videoTrackConfig = undefined;
  13028. };
  13029. _proto.getVideoStartPts = function getVideoStartPts(videoSamples) {
  13030. // Get the minimum PTS value relative to the first sample's PTS, normalized for 33-bit wrapping
  13031. var rolloverDetected = false;
  13032. var firstPts = videoSamples[0].pts;
  13033. var startPTS = videoSamples.reduce(function (minPTS, sample) {
  13034. var pts = sample.pts;
  13035. var delta = pts - minPTS;
  13036. if (delta < -4294967296) {
  13037. // 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation
  13038. rolloverDetected = true;
  13039. pts = normalizePts(pts, firstPts);
  13040. delta = pts - minPTS;
  13041. }
  13042. if (delta > 0) {
  13043. return minPTS;
  13044. }
  13045. return pts;
  13046. }, firstPts);
  13047. if (rolloverDetected) {
  13048. this.debug('PTS rollover detected');
  13049. }
  13050. return startPTS;
  13051. };
  13052. _proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, flush, playlistType) {
  13053. var video;
  13054. var audio;
  13055. var initSegment;
  13056. var text;
  13057. var id3;
  13058. var independent;
  13059. var audioTimeOffset = timeOffset;
  13060. var videoTimeOffset = timeOffset;
  13061. // If we're remuxing audio and video progressively, wait until we've received enough samples for each track before proceeding.
  13062. // This is done to synchronize the audio and video streams. We know if the current segment will have samples if the "pid"
  13063. // parameter is greater than -1. The pid is set when the PMT is parsed, which contains the tracks list.
  13064. // However, if the initSegment has already been generated, or we've reached the end of a segment (flush),
  13065. // then we can remux one track without waiting for the other.
  13066. var hasAudio = audioTrack.pid > -1;
  13067. var hasVideo = videoTrack.pid > -1;
  13068. var length = videoTrack.samples.length;
  13069. var enoughAudioSamples = audioTrack.samples.length > 0;
  13070. var enoughVideoSamples = flush && length > 0 || length > 1;
  13071. var canRemuxAvc = (!hasAudio || enoughAudioSamples) && (!hasVideo || enoughVideoSamples) || this.ISGenerated || flush;
  13072. if (canRemuxAvc) {
  13073. if (this.ISGenerated) {
  13074. var _videoTrack$pixelRati, _config$pixelRatio, _videoTrack$pixelRati2, _config$pixelRatio2;
  13075. var config = this.videoTrackConfig;
  13076. if (config && (videoTrack.width !== config.width || videoTrack.height !== config.height || ((_videoTrack$pixelRati = videoTrack.pixelRatio) == null ? void 0 : _videoTrack$pixelRati[0]) !== ((_config$pixelRatio = config.pixelRatio) == null ? void 0 : _config$pixelRatio[0]) || ((_videoTrack$pixelRati2 = videoTrack.pixelRatio) == null ? void 0 : _videoTrack$pixelRati2[1]) !== ((_config$pixelRatio2 = config.pixelRatio) == null ? void 0 : _config$pixelRatio2[1])) || !config && enoughVideoSamples || this.nextAudioTs === null && enoughAudioSamples) {
  13077. this.resetInitSegment();
  13078. }
  13079. }
  13080. if (!this.ISGenerated) {
  13081. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  13082. }
  13083. var isVideoContiguous = this.isVideoContiguous;
  13084. var firstKeyFrameIndex = -1;
  13085. var firstKeyFramePTS;
  13086. if (enoughVideoSamples) {
  13087. firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples);
  13088. if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) {
  13089. independent = true;
  13090. if (firstKeyFrameIndex > 0) {
  13091. this.warn("Dropped " + firstKeyFrameIndex + " out of " + length + " video samples due to a missing keyframe");
  13092. var startPTS = this.getVideoStartPts(videoTrack.samples);
  13093. videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex);
  13094. videoTrack.dropped += firstKeyFrameIndex;
  13095. videoTimeOffset += (videoTrack.samples[0].pts - startPTS) / videoTrack.inputTimeScale;
  13096. firstKeyFramePTS = videoTimeOffset;
  13097. } else if (firstKeyFrameIndex === -1) {
  13098. this.warn("No keyframe found out of " + length + " video samples");
  13099. independent = false;
  13100. }
  13101. }
  13102. }
  13103. if (this.ISGenerated) {
  13104. if (enoughAudioSamples && enoughVideoSamples) {
  13105. // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)
  13106. // if first audio DTS is not aligned with first video DTS then we need to take that into account
  13107. // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small
  13108. // drift between audio and video streams
  13109. var _startPTS = this.getVideoStartPts(videoTrack.samples);
  13110. var tsDelta = normalizePts(audioTrack.samples[0].pts, _startPTS) - _startPTS;
  13111. var audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;
  13112. audioTimeOffset += Math.max(0, audiovideoTimestampDelta);
  13113. videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);
  13114. }
  13115. // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is calculated in remuxAudio.
  13116. if (enoughAudioSamples) {
  13117. // if initSegment was generated without audio samples, regenerate it again
  13118. if (!audioTrack.samplerate) {
  13119. this.warn('regenerate InitSegment as audio detected');
  13120. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  13121. }
  13122. audio = this.remuxAudio(audioTrack, audioTimeOffset, this.isAudioContiguous, accurateTimeOffset, hasVideo || enoughVideoSamples || playlistType === PlaylistLevelType.AUDIO ? videoTimeOffset : undefined);
  13123. if (enoughVideoSamples) {
  13124. var audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0;
  13125. // if initSegment was generated without video samples, regenerate it again
  13126. if (!videoTrack.inputTimeScale) {
  13127. this.warn('regenerate InitSegment as video detected');
  13128. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  13129. }
  13130. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, audioTrackLength);
  13131. }
  13132. } else if (enoughVideoSamples) {
  13133. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, 0);
  13134. }
  13135. if (video) {
  13136. video.firstKeyFrame = firstKeyFrameIndex;
  13137. video.independent = firstKeyFrameIndex !== -1;
  13138. video.firstKeyFramePTS = firstKeyFramePTS;
  13139. }
  13140. }
  13141. }
  13142. // Allow ID3 and text to remux, even if more audio/video samples are required
  13143. if (this.ISGenerated && this._initPTS && this._initDTS) {
  13144. if (id3Track.samples.length) {
  13145. id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, this._initPTS, this._initDTS);
  13146. }
  13147. if (textTrack.samples.length) {
  13148. text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, this._initPTS);
  13149. }
  13150. }
  13151. return {
  13152. audio: audio,
  13153. video: video,
  13154. initSegment: initSegment,
  13155. independent: independent,
  13156. text: text,
  13157. id3: id3
  13158. };
  13159. };
  13160. _proto.generateIS = function generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset) {
  13161. var audioSamples = audioTrack.samples;
  13162. var videoSamples = videoTrack.samples;
  13163. var typeSupported = this.typeSupported;
  13164. var tracks = {};
  13165. var _initPTS = this._initPTS;
  13166. var computePTSDTS = !_initPTS || accurateTimeOffset;
  13167. var container = 'audio/mp4';
  13168. var initPTS;
  13169. var initDTS;
  13170. var timescale;
  13171. var trackId;
  13172. if (computePTSDTS) {
  13173. initPTS = initDTS = Infinity;
  13174. }
  13175. if (audioTrack.config && audioSamples.length) {
  13176. // let's use audio sampling rate as MP4 time scale.
  13177. // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)
  13178. // using audio sampling rate here helps having an integer MP4 frame duration
  13179. // this avoids potential rounding issue and AV sync issue
  13180. audioTrack.timescale = audioTrack.samplerate;
  13181. switch (audioTrack.segmentCodec) {
  13182. case 'mp3':
  13183. if (typeSupported.mpeg) {
  13184. // Chrome and Safari
  13185. container = 'audio/mpeg';
  13186. audioTrack.codec = '';
  13187. } else if (typeSupported.mp3) {
  13188. // Firefox
  13189. audioTrack.codec = 'mp3';
  13190. }
  13191. break;
  13192. case 'ac3':
  13193. audioTrack.codec = 'ac-3';
  13194. break;
  13195. }
  13196. tracks.audio = {
  13197. id: 'audio',
  13198. container: container,
  13199. codec: audioTrack.codec,
  13200. initSegment: audioTrack.segmentCodec === 'mp3' && typeSupported.mpeg ? new Uint8Array(0) : MP4.initSegment([audioTrack]),
  13201. metadata: {
  13202. channelCount: audioTrack.channelCount
  13203. }
  13204. };
  13205. if (computePTSDTS) {
  13206. trackId = audioTrack.id;
  13207. timescale = audioTrack.inputTimeScale;
  13208. if (!_initPTS || timescale !== _initPTS.timescale) {
  13209. // remember first PTS of this demuxing context. for audio, PTS = DTS
  13210. initPTS = initDTS = audioSamples[0].pts - Math.round(timescale * timeOffset);
  13211. } else {
  13212. computePTSDTS = false;
  13213. }
  13214. }
  13215. }
  13216. if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
  13217. // let's use input time scale as MP4 video timescale
  13218. // we use input time scale straight away to avoid rounding issues on frame duration / cts computation
  13219. videoTrack.timescale = videoTrack.inputTimeScale;
  13220. tracks.video = {
  13221. id: 'main',
  13222. container: 'video/mp4',
  13223. codec: videoTrack.codec,
  13224. initSegment: MP4.initSegment([videoTrack]),
  13225. metadata: {
  13226. width: videoTrack.width,
  13227. height: videoTrack.height
  13228. }
  13229. };
  13230. if (computePTSDTS) {
  13231. trackId = videoTrack.id;
  13232. timescale = videoTrack.inputTimeScale;
  13233. if (!_initPTS || timescale !== _initPTS.timescale) {
  13234. var startPTS = this.getVideoStartPts(videoSamples);
  13235. var startOffset = Math.round(timescale * timeOffset);
  13236. initDTS = Math.min(initDTS, normalizePts(videoSamples[0].dts, startPTS) - startOffset);
  13237. initPTS = Math.min(initPTS, startPTS - startOffset);
  13238. } else {
  13239. computePTSDTS = false;
  13240. }
  13241. }
  13242. this.videoTrackConfig = {
  13243. width: videoTrack.width,
  13244. height: videoTrack.height,
  13245. pixelRatio: videoTrack.pixelRatio
  13246. };
  13247. }
  13248. if (Object.keys(tracks).length) {
  13249. this.ISGenerated = true;
  13250. if (computePTSDTS) {
  13251. this._initPTS = {
  13252. baseTime: initPTS,
  13253. timescale: timescale
  13254. };
  13255. this._initDTS = {
  13256. baseTime: initDTS,
  13257. timescale: timescale
  13258. };
  13259. } else {
  13260. initPTS = timescale = undefined;
  13261. }
  13262. return {
  13263. tracks: tracks,
  13264. initPTS: initPTS,
  13265. timescale: timescale,
  13266. trackId: trackId
  13267. };
  13268. }
  13269. };
  13270. _proto.remuxVideo = function remuxVideo(track, timeOffset, contiguous, audioTrackLength) {
  13271. var timeScale = track.inputTimeScale;
  13272. var inputSamples = track.samples;
  13273. var outputSamples = [];
  13274. var nbSamples = inputSamples.length;
  13275. var initPTS = this._initPTS;
  13276. var initTime = initPTS.baseTime * timeScale / initPTS.timescale;
  13277. var nextVideoTs = this.nextVideoTs;
  13278. var offset = 8;
  13279. var mp4SampleDuration = this.videoSampleDuration;
  13280. var firstDTS;
  13281. var lastDTS;
  13282. var minPTS = Number.POSITIVE_INFINITY;
  13283. var maxPTS = Number.NEGATIVE_INFINITY;
  13284. var sortSamples = false;
  13285. // if parsed fragment is contiguous with last one, let's use last DTS value as reference
  13286. if (!contiguous || nextVideoTs === null) {
  13287. var pts = initTime + timeOffset * timeScale;
  13288. var cts = inputSamples[0].pts - normalizePts(inputSamples[0].dts, inputSamples[0].pts);
  13289. if (chromeVersion && nextVideoTs !== null && Math.abs(pts - cts - (nextVideoTs + initTime)) < 15000) {
  13290. // treat as contigous to adjust samples that would otherwise produce video buffer gaps in Chrome
  13291. contiguous = true;
  13292. } else {
  13293. // if not contiguous, let's use target timeOffset
  13294. nextVideoTs = pts - cts - initTime;
  13295. }
  13296. }
  13297. // PTS is coded on 33bits, and can loop from -2^32 to 2^32
  13298. // PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value
  13299. var nextVideoPts = nextVideoTs + initTime;
  13300. for (var i = 0; i < nbSamples; i++) {
  13301. var sample = inputSamples[i];
  13302. sample.pts = normalizePts(sample.pts, nextVideoPts);
  13303. sample.dts = normalizePts(sample.dts, nextVideoPts);
  13304. if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {
  13305. sortSamples = true;
  13306. }
  13307. }
  13308. // sort video samples by DTS then PTS then demux id order
  13309. if (sortSamples) {
  13310. inputSamples.sort(function (a, b) {
  13311. var deltadts = a.dts - b.dts;
  13312. var deltapts = a.pts - b.pts;
  13313. return deltadts || deltapts;
  13314. });
  13315. }
  13316. // Get first/last DTS
  13317. firstDTS = inputSamples[0].dts;
  13318. lastDTS = inputSamples[inputSamples.length - 1].dts;
  13319. // Sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS
  13320. // set this constant duration as being the avg delta between consecutive DTS.
  13321. var inputDuration = lastDTS - firstDTS;
  13322. var averageSampleDuration = inputDuration ? Math.round(inputDuration / (nbSamples - 1)) : mp4SampleDuration || track.inputTimeScale / 30;
  13323. // if fragment are contiguous, detect hole/overlapping between fragments
  13324. if (contiguous) {
  13325. // check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)
  13326. var delta = firstDTS - nextVideoPts;
  13327. var foundHole = delta > averageSampleDuration;
  13328. var foundOverlap = delta < -1;
  13329. if (foundHole || foundOverlap) {
  13330. if (foundHole) {
  13331. this.warn((track.segmentCodec || '').toUpperCase() + ": " + toMsFromMpegTsClock(delta) + " ms (" + delta + "dts) hole between fragments detected at " + timeOffset.toFixed(3));
  13332. } else {
  13333. this.warn((track.segmentCodec || '').toUpperCase() + ": " + toMsFromMpegTsClock(-delta) + " ms (" + delta + "dts) overlapping between fragments detected at " + timeOffset.toFixed(3));
  13334. }
  13335. if (!foundOverlap || nextVideoPts >= inputSamples[0].pts || chromeVersion) {
  13336. firstDTS = nextVideoPts;
  13337. var firstPTS = inputSamples[0].pts - delta;
  13338. if (foundHole) {
  13339. inputSamples[0].dts = firstDTS;
  13340. inputSamples[0].pts = firstPTS;
  13341. } else {
  13342. var isPTSOrderRetained = true;
  13343. for (var _i = 0; _i < inputSamples.length; _i++) {
  13344. if (inputSamples[_i].dts > firstPTS && isPTSOrderRetained) {
  13345. break;
  13346. }
  13347. var prevPTS = inputSamples[_i].pts;
  13348. inputSamples[_i].dts -= delta;
  13349. inputSamples[_i].pts -= delta;
  13350. // check to see if this sample's PTS order has changed
  13351. // relative to the next one
  13352. if (_i < inputSamples.length - 1) {
  13353. var nextSamplePTS = inputSamples[_i + 1].pts;
  13354. var currentSamplePTS = inputSamples[_i].pts;
  13355. var currentOrder = nextSamplePTS <= currentSamplePTS;
  13356. var prevOrder = nextSamplePTS <= prevPTS;
  13357. isPTSOrderRetained = currentOrder == prevOrder;
  13358. }
  13359. }
  13360. }
  13361. this.log("Video: Initial PTS/DTS adjusted: " + toMsFromMpegTsClock(firstPTS) + "/" + toMsFromMpegTsClock(firstDTS) + ", delta: " + toMsFromMpegTsClock(delta) + " ms");
  13362. }
  13363. }
  13364. }
  13365. firstDTS = Math.max(0, firstDTS);
  13366. var nbNalu = 0;
  13367. var naluLen = 0;
  13368. var dtsStep = firstDTS;
  13369. for (var _i2 = 0; _i2 < nbSamples; _i2++) {
  13370. // compute total/avc sample length and nb of NAL units
  13371. var _sample = inputSamples[_i2];
  13372. var units = _sample.units;
  13373. var nbUnits = units.length;
  13374. var sampleLen = 0;
  13375. for (var j = 0; j < nbUnits; j++) {
  13376. sampleLen += units[j].data.length;
  13377. }
  13378. naluLen += sampleLen;
  13379. nbNalu += nbUnits;
  13380. _sample.length = sampleLen;
  13381. // ensure sample monotonic DTS
  13382. if (_sample.dts < dtsStep) {
  13383. _sample.dts = dtsStep;
  13384. dtsStep += averageSampleDuration / 4 | 0 || 1;
  13385. } else {
  13386. dtsStep = _sample.dts;
  13387. }
  13388. minPTS = Math.min(_sample.pts, minPTS);
  13389. maxPTS = Math.max(_sample.pts, maxPTS);
  13390. }
  13391. lastDTS = inputSamples[nbSamples - 1].dts;
  13392. /* concatenate the video data and construct the mdat in place
  13393. (need 8 more bytes to fill length and mpdat type) */
  13394. var mdatSize = naluLen + 4 * nbNalu + 8;
  13395. var mdat;
  13396. try {
  13397. mdat = new Uint8Array(mdatSize);
  13398. } catch (err) {
  13399. this.observer.emit(Events.ERROR, Events.ERROR, {
  13400. type: ErrorTypes.MUX_ERROR,
  13401. details: ErrorDetails.REMUX_ALLOC_ERROR,
  13402. fatal: false,
  13403. error: err,
  13404. bytes: mdatSize,
  13405. reason: "fail allocating video mdat " + mdatSize
  13406. });
  13407. return;
  13408. }
  13409. var view = new DataView(mdat.buffer);
  13410. view.setUint32(0, mdatSize);
  13411. mdat.set(MP4.types.mdat, 4);
  13412. var stretchedLastFrame = false;
  13413. var minDtsDelta = Number.POSITIVE_INFINITY;
  13414. var minPtsDelta = Number.POSITIVE_INFINITY;
  13415. var maxDtsDelta = Number.NEGATIVE_INFINITY;
  13416. var maxPtsDelta = Number.NEGATIVE_INFINITY;
  13417. for (var _i3 = 0; _i3 < nbSamples; _i3++) {
  13418. var VideoSample = inputSamples[_i3];
  13419. var VideoSampleUnits = VideoSample.units;
  13420. var mp4SampleLength = 0;
  13421. // convert NALU bitstream to MP4 format (prepend NALU with size field)
  13422. for (var _j = 0, _nbUnits = VideoSampleUnits.length; _j < _nbUnits; _j++) {
  13423. var unit = VideoSampleUnits[_j];
  13424. var unitData = unit.data;
  13425. var unitDataLen = unit.data.byteLength;
  13426. view.setUint32(offset, unitDataLen);
  13427. offset += 4;
  13428. mdat.set(unitData, offset);
  13429. offset += unitDataLen;
  13430. mp4SampleLength += 4 + unitDataLen;
  13431. }
  13432. // expected sample duration is the Decoding Timestamp diff of consecutive samples
  13433. var ptsDelta = void 0;
  13434. if (_i3 < nbSamples - 1) {
  13435. mp4SampleDuration = inputSamples[_i3 + 1].dts - VideoSample.dts;
  13436. ptsDelta = inputSamples[_i3 + 1].pts - VideoSample.pts;
  13437. } else {
  13438. var config = this.config;
  13439. var lastFrameDuration = _i3 > 0 ? VideoSample.dts - inputSamples[_i3 - 1].dts : averageSampleDuration;
  13440. ptsDelta = _i3 > 0 ? VideoSample.pts - inputSamples[_i3 - 1].pts : averageSampleDuration;
  13441. if (config.stretchShortVideoTrack && this.nextAudioTs !== null) {
  13442. // In some cases, a segment's audio track duration may exceed the video track duration.
  13443. // Since we've already remuxed audio, and we know how long the audio track is, we look to
  13444. // see if the delta to the next segment is longer than maxBufferHole.
  13445. // If so, playback would potentially get stuck, so we artificially inflate
  13446. // the duration of the last frame to minimize any potential gap between segments.
  13447. var gapTolerance = Math.floor(config.maxBufferHole * timeScale);
  13448. var deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioTs + initTime) - VideoSample.pts;
  13449. if (deltaToFrameEnd > gapTolerance) {
  13450. // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video
  13451. // frame overlap. maxBufferHole should be >> lastFrameDuration anyway.
  13452. mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
  13453. if (mp4SampleDuration < 0) {
  13454. mp4SampleDuration = lastFrameDuration;
  13455. } else {
  13456. stretchedLastFrame = true;
  13457. }
  13458. this.log("It is approximately " + deltaToFrameEnd / 90 + " ms to the next segment; using duration " + mp4SampleDuration / 90 + " ms for the last video frame.");
  13459. } else {
  13460. mp4SampleDuration = lastFrameDuration;
  13461. }
  13462. } else {
  13463. mp4SampleDuration = lastFrameDuration;
  13464. }
  13465. }
  13466. var compositionTimeOffset = Math.round(VideoSample.pts - VideoSample.dts);
  13467. minDtsDelta = Math.min(minDtsDelta, mp4SampleDuration);
  13468. maxDtsDelta = Math.max(maxDtsDelta, mp4SampleDuration);
  13469. minPtsDelta = Math.min(minPtsDelta, ptsDelta);
  13470. maxPtsDelta = Math.max(maxPtsDelta, ptsDelta);
  13471. outputSamples.push(createMp4Sample(VideoSample.key, mp4SampleDuration, mp4SampleLength, compositionTimeOffset));
  13472. }
  13473. if (outputSamples.length) {
  13474. if (chromeVersion) {
  13475. if (chromeVersion < 70) {
  13476. // Chrome workaround, mark first sample as being a Random Access Point (keyframe) to avoid sourcebuffer append issue
  13477. // https://code.google.com/p/chromium/issues/detail?id=229412
  13478. var flags = outputSamples[0].flags;
  13479. flags.dependsOn = 2;
  13480. flags.isNonSync = 0;
  13481. }
  13482. } else if (safariWebkitVersion) {
  13483. // Fix for "CNN special report, with CC" in test-streams (Safari browser only)
  13484. // Ignore DTS when frame durations are irregular. Safari MSE does not handle this leading to gaps.
  13485. if (maxPtsDelta - minPtsDelta < maxDtsDelta - minDtsDelta && averageSampleDuration / maxDtsDelta < 0.025 && outputSamples[0].cts === 0) {
  13486. this.warn('Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.');
  13487. var dts = firstDTS;
  13488. for (var _i4 = 0, len = outputSamples.length; _i4 < len; _i4++) {
  13489. var nextDts = dts + outputSamples[_i4].duration;
  13490. var _pts = dts + outputSamples[_i4].cts;
  13491. if (_i4 < len - 1) {
  13492. var nextPts = nextDts + outputSamples[_i4 + 1].cts;
  13493. outputSamples[_i4].duration = nextPts - _pts;
  13494. } else {
  13495. outputSamples[_i4].duration = _i4 ? outputSamples[_i4 - 1].duration : averageSampleDuration;
  13496. }
  13497. outputSamples[_i4].cts = 0;
  13498. dts = nextDts;
  13499. }
  13500. }
  13501. }
  13502. }
  13503. // next AVC/HEVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)
  13504. mp4SampleDuration = stretchedLastFrame || !mp4SampleDuration ? averageSampleDuration : mp4SampleDuration;
  13505. var endDTS = lastDTS + mp4SampleDuration;
  13506. this.nextVideoTs = nextVideoTs = endDTS - initTime;
  13507. this.videoSampleDuration = mp4SampleDuration;
  13508. this.isVideoContiguous = true;
  13509. var moof = MP4.moof(track.sequenceNumber++, firstDTS, _extends(track, {
  13510. samples: outputSamples
  13511. }));
  13512. var type = 'video';
  13513. var data = {
  13514. data1: moof,
  13515. data2: mdat,
  13516. startPTS: (minPTS - initTime) / timeScale,
  13517. endPTS: (maxPTS + mp4SampleDuration - initTime) / timeScale,
  13518. startDTS: (firstDTS - initTime) / timeScale,
  13519. endDTS: nextVideoTs / timeScale,
  13520. type: type,
  13521. hasAudio: false,
  13522. hasVideo: true,
  13523. nb: outputSamples.length,
  13524. dropped: track.dropped
  13525. };
  13526. track.samples = [];
  13527. track.dropped = 0;
  13528. return data;
  13529. };
  13530. _proto.getSamplesPerFrame = function getSamplesPerFrame(track) {
  13531. switch (track.segmentCodec) {
  13532. case 'mp3':
  13533. return MPEG_AUDIO_SAMPLE_PER_FRAME;
  13534. case 'ac3':
  13535. return AC3_SAMPLES_PER_FRAME;
  13536. default:
  13537. return AAC_SAMPLES_PER_FRAME;
  13538. }
  13539. };
  13540. _proto.remuxAudio = function remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, videoTimeOffset) {
  13541. var inputTimeScale = track.inputTimeScale;
  13542. var mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
  13543. var scaleFactor = inputTimeScale / mp4timeScale;
  13544. var mp4SampleDuration = this.getSamplesPerFrame(track);
  13545. var inputSampleDuration = mp4SampleDuration * scaleFactor;
  13546. var initPTS = this._initPTS;
  13547. var rawMPEG = track.segmentCodec === 'mp3' && this.typeSupported.mpeg;
  13548. var outputSamples = [];
  13549. var alignedWithVideo = videoTimeOffset !== undefined;
  13550. var inputSamples = track.samples;
  13551. var offset = rawMPEG ? 0 : 8;
  13552. var nextAudioTs = this.nextAudioTs || -1;
  13553. // window.audioSamples ? window.audioSamples.push(inputSamples.map(s => s.pts)) : (window.audioSamples = [inputSamples.map(s => s.pts)]);
  13554. // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),
  13555. // for sake of clarity:
  13556. // consecutive fragments are frags with
  13557. // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
  13558. // - less than 20 audio frames distance
  13559. // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
  13560. // this helps ensuring audio continuity
  13561. // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame
  13562. var initTime = initPTS.baseTime * inputTimeScale / initPTS.timescale;
  13563. var timeOffsetMpegTS = initTime + timeOffset * inputTimeScale;
  13564. this.isAudioContiguous = contiguous = contiguous || inputSamples.length && nextAudioTs > 0 && (accurateTimeOffset && Math.abs(timeOffsetMpegTS - (nextAudioTs + initTime)) < 9000 || Math.abs(normalizePts(inputSamples[0].pts, timeOffsetMpegTS) - (nextAudioTs + initTime)) < 20 * inputSampleDuration);
  13565. // compute normalized PTS
  13566. inputSamples.forEach(function (sample) {
  13567. sample.pts = normalizePts(sample.pts, timeOffsetMpegTS);
  13568. });
  13569. if (!contiguous || nextAudioTs < 0) {
  13570. // filter out sample with negative PTS that are not playable anyway
  13571. // if we don't remove these negative samples, they will shift all audio samples forward.
  13572. // leading to audio overlap between current / next fragment
  13573. inputSamples = inputSamples.filter(function (sample) {
  13574. return sample.pts >= 0;
  13575. });
  13576. // in case all samples have negative PTS, and have been filtered out, return now
  13577. if (!inputSamples.length) {
  13578. return;
  13579. }
  13580. if (videoTimeOffset === 0) {
  13581. // Set the start to match video so that start gaps larger than inputSampleDuration are filled with silence
  13582. nextAudioTs = 0;
  13583. } else if (accurateTimeOffset && !alignedWithVideo) {
  13584. // When not seeking, not live, and LevelDetails.PTSKnown, use fragment start as predicted next audio PTS
  13585. nextAudioTs = Math.max(0, timeOffsetMpegTS - initTime);
  13586. } else {
  13587. // if frags are not contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS
  13588. nextAudioTs = inputSamples[0].pts - initTime;
  13589. }
  13590. }
  13591. // If the audio track is missing samples, the frames seem to get "left-shifted" within the
  13592. // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.
  13593. // In an effort to prevent this from happening, we inject frames here where there are gaps.
  13594. // When possible, we inject a silent frame; when that's not possible, we duplicate the last
  13595. // frame.
  13596. if (track.segmentCodec === 'aac') {
  13597. var maxAudioFramesDrift = this.config.maxAudioFramesDrift;
  13598. for (var i = 0, nextPts = nextAudioTs + initTime; i < inputSamples.length; i++) {
  13599. // First, let's see how far off this frame is from where we expect it to be
  13600. var sample = inputSamples[i];
  13601. var pts = sample.pts;
  13602. var delta = pts - nextPts;
  13603. var duration = Math.abs(1000 * delta / inputTimeScale);
  13604. // When remuxing with video, if we're overlapping by more than a duration, drop this sample to stay in sync
  13605. if (delta <= -maxAudioFramesDrift * inputSampleDuration && alignedWithVideo) {
  13606. if (i === 0) {
  13607. this.warn("Audio frame @ " + (pts / inputTimeScale).toFixed(3) + "s overlaps marker by " + Math.round(1000 * delta / inputTimeScale) + " ms.");
  13608. this.nextAudioTs = nextAudioTs = pts - initTime;
  13609. nextPts = pts;
  13610. }
  13611. } // eslint-disable-line brace-style
  13612. // Insert missing frames if:
  13613. // 1: We're more than maxAudioFramesDrift frame away
  13614. // 2: Not more than MAX_SILENT_FRAME_DURATION away
  13615. // 3: currentTime (aka nextPtsNorm) is not 0
  13616. // 4: remuxing with video (videoTimeOffset !== undefined)
  13617. else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && alignedWithVideo) {
  13618. var missing = Math.round(delta / inputSampleDuration);
  13619. // Adjust nextPts so that silent samples are aligned with media pts. This will prevent media samples from
  13620. // later being shifted if nextPts is based on timeOffset and delta is not a multiple of inputSampleDuration.
  13621. nextPts = pts - missing * inputSampleDuration;
  13622. while (nextPts < 0 && missing && inputSampleDuration) {
  13623. missing--;
  13624. nextPts += inputSampleDuration;
  13625. }
  13626. if (i === 0) {
  13627. this.nextAudioTs = nextAudioTs = nextPts - initTime;
  13628. }
  13629. this.warn("Injecting " + missing + " audio frames @ " + ((nextPts - initTime) / inputTimeScale).toFixed(3) + "s due to " + Math.round(1000 * delta / inputTimeScale) + " ms gap.");
  13630. for (var j = 0; j < missing; j++) {
  13631. var fillFrame = AAC.getSilentFrame(track.parsedCodec || track.manifestCodec || track.codec, track.channelCount);
  13632. if (!fillFrame) {
  13633. this.log('Unable to get silent frame for given audio codec; duplicating last frame instead.');
  13634. fillFrame = sample.unit.subarray();
  13635. }
  13636. inputSamples.splice(i, 0, {
  13637. unit: fillFrame,
  13638. pts: nextPts
  13639. });
  13640. nextPts += inputSampleDuration;
  13641. i++;
  13642. }
  13643. }
  13644. sample.pts = nextPts;
  13645. nextPts += inputSampleDuration;
  13646. }
  13647. }
  13648. var firstPTS = null;
  13649. var lastPTS = null;
  13650. var mdat;
  13651. var mdatSize = 0;
  13652. var sampleLength = inputSamples.length;
  13653. while (sampleLength--) {
  13654. mdatSize += inputSamples[sampleLength].unit.byteLength;
  13655. }
  13656. for (var _j2 = 0, _nbSamples = inputSamples.length; _j2 < _nbSamples; _j2++) {
  13657. var audioSample = inputSamples[_j2];
  13658. var unit = audioSample.unit;
  13659. var _pts2 = audioSample.pts;
  13660. if (lastPTS !== null) {
  13661. // If we have more than one sample, set the duration of the sample to the "real" duration; the PTS diff with
  13662. // the previous sample
  13663. var prevSample = outputSamples[_j2 - 1];
  13664. prevSample.duration = Math.round((_pts2 - lastPTS) / scaleFactor);
  13665. } else {
  13666. if (contiguous && track.segmentCodec === 'aac') {
  13667. // set PTS/DTS to expected PTS/DTS
  13668. _pts2 = nextAudioTs + initTime;
  13669. }
  13670. // remember first PTS of our audioSamples
  13671. firstPTS = _pts2;
  13672. if (mdatSize > 0) {
  13673. /* concatenate the audio data and construct the mdat in place
  13674. (need 8 more bytes to fill length and mdat type) */
  13675. mdatSize += offset;
  13676. try {
  13677. mdat = new Uint8Array(mdatSize);
  13678. } catch (err) {
  13679. this.observer.emit(Events.ERROR, Events.ERROR, {
  13680. type: ErrorTypes.MUX_ERROR,
  13681. details: ErrorDetails.REMUX_ALLOC_ERROR,
  13682. fatal: false,
  13683. error: err,
  13684. bytes: mdatSize,
  13685. reason: "fail allocating audio mdat " + mdatSize
  13686. });
  13687. return;
  13688. }
  13689. if (!rawMPEG) {
  13690. var view = new DataView(mdat.buffer);
  13691. view.setUint32(0, mdatSize);
  13692. mdat.set(MP4.types.mdat, 4);
  13693. }
  13694. } else {
  13695. // no audio samples
  13696. return;
  13697. }
  13698. }
  13699. mdat.set(unit, offset);
  13700. var unitLen = unit.byteLength;
  13701. offset += unitLen;
  13702. // Default the sample's duration to the computed mp4SampleDuration, which will either be 1024 for AAC or 1152 for MPEG
  13703. // In the case that we have 1 sample, this will be the duration. If we have more than one sample, the duration
  13704. // becomes the PTS diff with the previous sample
  13705. outputSamples.push(createMp4Sample(true, mp4SampleDuration, unitLen, 0));
  13706. lastPTS = _pts2;
  13707. }
  13708. // We could end up with no audio samples if all input samples were overlapping with the previously remuxed ones
  13709. var nbSamples = outputSamples.length;
  13710. if (!nbSamples) {
  13711. return;
  13712. }
  13713. // The next audio sample PTS should be equal to last sample PTS + duration
  13714. var lastSample = outputSamples[outputSamples.length - 1];
  13715. nextAudioTs = lastPTS - initTime;
  13716. this.nextAudioTs = nextAudioTs + scaleFactor * lastSample.duration;
  13717. // Set the track samples from inputSamples to outputSamples before remuxing
  13718. var moof = rawMPEG ? new Uint8Array(0) : MP4.moof(track.sequenceNumber++, firstPTS / scaleFactor, _extends({}, track, {
  13719. samples: outputSamples
  13720. }));
  13721. // Clear the track samples. This also clears the samples array in the demuxer, since the reference is shared
  13722. track.samples = [];
  13723. var start = (firstPTS - initTime) / inputTimeScale;
  13724. var end = nextAudioTs / inputTimeScale;
  13725. var type = 'audio';
  13726. var audioData = {
  13727. data1: moof,
  13728. data2: mdat,
  13729. startPTS: start,
  13730. endPTS: end,
  13731. startDTS: start,
  13732. endDTS: end,
  13733. type: type,
  13734. hasAudio: true,
  13735. hasVideo: false,
  13736. nb: nbSamples
  13737. };
  13738. this.isAudioContiguous = true;
  13739. return audioData;
  13740. };
  13741. return MP4Remuxer;
  13742. }(Logger);
  13743. function normalizePts(value, reference) {
  13744. var offset;
  13745. if (reference === null) {
  13746. return value;
  13747. }
  13748. if (reference < value) {
  13749. // - 2^33
  13750. offset = -8589934592;
  13751. } else {
  13752. // + 2^33
  13753. offset = 8589934592;
  13754. }
  13755. /* PTS is 33bit (from 0 to 2^33 -1)
  13756. if diff between value and reference is bigger than half of the amplitude (2^32) then it means that
  13757. PTS looping occured. fill the gap */
  13758. while (Math.abs(value - reference) > 4294967296) {
  13759. value += offset;
  13760. }
  13761. return value;
  13762. }
  13763. function findKeyframeIndex(samples) {
  13764. for (var i = 0; i < samples.length; i++) {
  13765. if (samples[i].key) {
  13766. return i;
  13767. }
  13768. }
  13769. return -1;
  13770. }
  13771. function flushTextTrackMetadataCueSamples(track, timeOffset, initPTS, initDTS) {
  13772. var length = track.samples.length;
  13773. if (!length) {
  13774. return;
  13775. }
  13776. var inputTimeScale = track.inputTimeScale;
  13777. for (var index = 0; index < length; index++) {
  13778. var sample = track.samples[index];
  13779. // setting id3 pts, dts to relative time
  13780. // using this._initPTS and this._initDTS to calculate relative time
  13781. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  13782. sample.dts = normalizePts(sample.dts - initDTS.baseTime * inputTimeScale / initDTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  13783. }
  13784. var samples = track.samples;
  13785. track.samples = [];
  13786. return {
  13787. samples: samples
  13788. };
  13789. }
  13790. function flushTextTrackUserdataCueSamples(track, timeOffset, initPTS) {
  13791. var length = track.samples.length;
  13792. if (!length) {
  13793. return;
  13794. }
  13795. var inputTimeScale = track.inputTimeScale;
  13796. for (var index = 0; index < length; index++) {
  13797. var sample = track.samples[index];
  13798. // setting text pts, dts to relative time
  13799. // using this._initPTS and this._initDTS to calculate relative time
  13800. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  13801. }
  13802. track.samples.sort(function (a, b) {
  13803. return a.pts - b.pts;
  13804. });
  13805. var samples = track.samples;
  13806. track.samples = [];
  13807. return {
  13808. samples: samples
  13809. };
  13810. }
  13811. var PassThroughRemuxer = /*#__PURE__*/function (_Logger) {
  13812. function PassThroughRemuxer(observer, config, typeSupported, logger) {
  13813. var _this;
  13814. _this = _Logger.call(this, 'passthrough-remuxer', logger) || this;
  13815. _this.emitInitSegment = false;
  13816. _this.audioCodec = void 0;
  13817. _this.videoCodec = void 0;
  13818. _this.initData = void 0;
  13819. _this.initPTS = null;
  13820. _this.initTracks = void 0;
  13821. _this.lastEndTime = null;
  13822. _this.isVideoContiguous = false;
  13823. return _this;
  13824. }
  13825. _inheritsLoose(PassThroughRemuxer, _Logger);
  13826. var _proto = PassThroughRemuxer.prototype;
  13827. _proto.destroy = function destroy() {};
  13828. _proto.resetTimeStamp = function resetTimeStamp(defaultInitPTS) {
  13829. this.lastEndTime = null;
  13830. var initPTS = this.initPTS;
  13831. if (initPTS && defaultInitPTS) {
  13832. if (initPTS.baseTime === defaultInitPTS.baseTime && initPTS.timescale === defaultInitPTS.timescale) {
  13833. return;
  13834. }
  13835. }
  13836. this.initPTS = defaultInitPTS;
  13837. };
  13838. _proto.resetNextTimestamp = function resetNextTimestamp() {
  13839. this.isVideoContiguous = false;
  13840. this.lastEndTime = null;
  13841. };
  13842. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, decryptdata) {
  13843. this.audioCodec = audioCodec;
  13844. this.videoCodec = videoCodec;
  13845. this.generateInitSegment(patchEncyptionData(initSegment, decryptdata));
  13846. this.emitInitSegment = true;
  13847. };
  13848. _proto.generateInitSegment = function generateInitSegment(initSegment) {
  13849. var audioCodec = this.audioCodec,
  13850. videoCodec = this.videoCodec;
  13851. if (!(initSegment != null && initSegment.byteLength)) {
  13852. this.initTracks = undefined;
  13853. this.initData = undefined;
  13854. return;
  13855. }
  13856. var initData = this.initData = parseInitSegment(initSegment);
  13857. // Get codec from initSegment
  13858. if (initData.audio) {
  13859. audioCodec = getParsedTrackCodec(initData.audio, ElementaryStreamTypes.AUDIO, this);
  13860. }
  13861. if (initData.video) {
  13862. videoCodec = getParsedTrackCodec(initData.video, ElementaryStreamTypes.VIDEO, this);
  13863. }
  13864. var tracks = {};
  13865. if (initData.audio && initData.video) {
  13866. tracks.audiovideo = {
  13867. container: 'video/mp4',
  13868. codec: audioCodec + ',' + videoCodec,
  13869. supplemental: initData.video.supplemental,
  13870. initSegment: initSegment,
  13871. id: 'main'
  13872. };
  13873. } else if (initData.audio) {
  13874. tracks.audio = {
  13875. container: 'audio/mp4',
  13876. codec: audioCodec,
  13877. initSegment: initSegment,
  13878. id: 'audio'
  13879. };
  13880. } else if (initData.video) {
  13881. tracks.video = {
  13882. container: 'video/mp4',
  13883. codec: videoCodec,
  13884. supplemental: initData.video.supplemental,
  13885. initSegment: initSegment,
  13886. id: 'main'
  13887. };
  13888. } else {
  13889. this.warn('initSegment does not contain moov or trak boxes.');
  13890. }
  13891. this.initTracks = tracks;
  13892. };
  13893. _proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset) {
  13894. var _initData, _initData2;
  13895. var initPTS = this.initPTS,
  13896. lastEndTime = this.lastEndTime;
  13897. var result = {
  13898. audio: undefined,
  13899. video: undefined,
  13900. text: textTrack,
  13901. id3: id3Track,
  13902. initSegment: undefined
  13903. };
  13904. // If we haven't yet set a lastEndDTS, or it was reset, set it to the provided timeOffset. We want to use the
  13905. // lastEndDTS over timeOffset whenever possible; during progressive playback, the media source will not update
  13906. // the media duration (which is what timeOffset is provided as) before we need to process the next chunk.
  13907. if (!isFiniteNumber(lastEndTime)) {
  13908. lastEndTime = this.lastEndTime = timeOffset || 0;
  13909. }
  13910. // The binary segment data is added to the videoTrack in the mp4demuxer. We don't check to see if the data is only
  13911. // audio or video (or both); adding it to video was an arbitrary choice.
  13912. var data = videoTrack.samples;
  13913. if (!(data != null && data.length)) {
  13914. return result;
  13915. }
  13916. var initSegment = {
  13917. initPTS: undefined,
  13918. timescale: undefined,
  13919. trackId: undefined
  13920. };
  13921. var initData = this.initData;
  13922. if (!((_initData = initData) != null && _initData.length)) {
  13923. this.generateInitSegment(data);
  13924. initData = this.initData;
  13925. }
  13926. if (!((_initData2 = initData) != null && _initData2.length)) {
  13927. // We can't remux if the initSegment could not be generated
  13928. this.warn('Failed to generate initSegment.');
  13929. return result;
  13930. }
  13931. if (this.emitInitSegment) {
  13932. initSegment.tracks = this.initTracks;
  13933. this.emitInitSegment = false;
  13934. }
  13935. var trackSampleData = getSampleData(data, initData, this);
  13936. var audioSampleTimestamps = initData.audio ? trackSampleData[initData.audio.id] : null;
  13937. var videoSampleTimestamps = initData.video ? trackSampleData[initData.video.id] : null;
  13938. var videoStartTime = toStartEndOrDefault(videoSampleTimestamps, Infinity);
  13939. var audioStartTime = toStartEndOrDefault(audioSampleTimestamps, Infinity);
  13940. var videoEndTime = toStartEndOrDefault(videoSampleTimestamps, 0, true);
  13941. var audioEndTime = toStartEndOrDefault(audioSampleTimestamps, 0, true);
  13942. var baseOffsetSamples;
  13943. var decodeTime = timeOffset;
  13944. var duration = 0;
  13945. if (audioSampleTimestamps && (!videoSampleTimestamps || !initPTS && audioStartTime < videoStartTime || initPTS && initPTS.trackId === initData.audio.id)) {
  13946. initSegment.trackId = initData.audio.id;
  13947. baseOffsetSamples = audioSampleTimestamps;
  13948. duration = audioEndTime - audioStartTime;
  13949. } else if (videoSampleTimestamps) {
  13950. initSegment.trackId = initData.video.id;
  13951. baseOffsetSamples = videoSampleTimestamps;
  13952. duration = videoEndTime - videoStartTime;
  13953. }
  13954. if (baseOffsetSamples) {
  13955. var timescale = baseOffsetSamples.timescale;
  13956. decodeTime = baseOffsetSamples.start / timescale;
  13957. initSegment.initPTS = baseOffsetSamples.start - timeOffset * timescale;
  13958. initSegment.timescale = timescale;
  13959. if (!initPTS) {
  13960. this.initPTS = initPTS = {
  13961. baseTime: initSegment.initPTS,
  13962. timescale: timescale,
  13963. trackId: initSegment.trackId
  13964. };
  13965. }
  13966. }
  13967. if ((accurateTimeOffset || !initPTS) && (isInvalidInitPts(initPTS, decodeTime, timeOffset, duration) || initSegment.timescale !== initPTS.timescale)) {
  13968. initSegment.initPTS = decodeTime - timeOffset;
  13969. initSegment.timescale = 1;
  13970. if (initPTS && initPTS.timescale === 1) {
  13971. this.warn("Adjusting initPTS @" + timeOffset + " from " + initPTS.baseTime / initPTS.timescale + " to " + initSegment.initPTS);
  13972. }
  13973. this.initPTS = initPTS = {
  13974. baseTime: initSegment.initPTS,
  13975. timescale: 1
  13976. };
  13977. }
  13978. var startTime = audioTrack ? decodeTime - initPTS.baseTime / initPTS.timescale : lastEndTime;
  13979. var endTime = startTime + duration;
  13980. if (duration > 0) {
  13981. this.lastEndTime = endTime;
  13982. } else {
  13983. this.warn('Duration parsed from mp4 should be greater than zero');
  13984. this.resetNextTimestamp();
  13985. }
  13986. var hasAudio = !!initData.audio;
  13987. var hasVideo = !!initData.video;
  13988. var type = '';
  13989. if (hasAudio) {
  13990. type += 'audio';
  13991. }
  13992. if (hasVideo) {
  13993. type += 'video';
  13994. }
  13995. var track = {
  13996. data1: data,
  13997. startPTS: startTime,
  13998. startDTS: startTime,
  13999. endPTS: endTime,
  14000. endDTS: endTime,
  14001. type: type,
  14002. hasAudio: hasAudio,
  14003. hasVideo: hasVideo,
  14004. nb: 1,
  14005. dropped: 0
  14006. };
  14007. result.audio = hasAudio && !hasVideo ? track : undefined;
  14008. result.video = hasVideo ? track : undefined;
  14009. var videoSampleCount = videoSampleTimestamps == null ? void 0 : videoSampleTimestamps.sampleCount;
  14010. if (videoSampleCount) {
  14011. var firstKeyFrame = videoSampleTimestamps.keyFrameIndex;
  14012. var independent = firstKeyFrame !== -1;
  14013. track.nb = videoSampleCount;
  14014. track.dropped = firstKeyFrame === 0 || this.isVideoContiguous ? 0 : independent ? firstKeyFrame : videoSampleCount;
  14015. track.independent = independent;
  14016. track.firstKeyFrame = firstKeyFrame;
  14017. if (independent && videoSampleTimestamps.keyFrameStart) {
  14018. track.firstKeyFramePTS = (videoSampleTimestamps.keyFrameStart - initPTS.baseTime) / initPTS.timescale;
  14019. }
  14020. if (!this.isVideoContiguous) {
  14021. result.independent = independent;
  14022. }
  14023. this.isVideoContiguous || (this.isVideoContiguous = independent);
  14024. if (track.dropped) {
  14025. this.warn("fmp4 does not start with IDR: firstIDR " + firstKeyFrame + "/" + videoSampleCount + " dropped: " + track.dropped + " start: " + (track.firstKeyFramePTS || 'NA'));
  14026. }
  14027. }
  14028. result.initSegment = initSegment;
  14029. result.id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, initPTS, initPTS);
  14030. if (textTrack.samples.length) {
  14031. result.text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, initPTS);
  14032. }
  14033. return result;
  14034. };
  14035. return PassThroughRemuxer;
  14036. }(Logger);
  14037. function toStartEndOrDefault(trackTimes, defaultValue, end) {
  14038. if (end === void 0) {
  14039. end = false;
  14040. }
  14041. return (trackTimes == null ? void 0 : trackTimes.start) !== undefined ? (trackTimes.start + (end ? trackTimes.duration : 0)) / trackTimes.timescale : defaultValue;
  14042. }
  14043. function isInvalidInitPts(initPTS, startDTS, timeOffset, duration) {
  14044. if (initPTS === null) {
  14045. return true;
  14046. }
  14047. // InitPTS is invalid when distance from program would be more than segment duration or a minimum of one second
  14048. var minDuration = Math.max(duration, 1);
  14049. var startTime = startDTS - initPTS.baseTime / initPTS.timescale;
  14050. return Math.abs(startTime - timeOffset) > minDuration;
  14051. }
  14052. function getParsedTrackCodec(track, type, logger) {
  14053. var parsedCodec = track == null ? void 0 : track.codec;
  14054. if (parsedCodec && parsedCodec.length > 4) {
  14055. return parsedCodec;
  14056. }
  14057. if (type === ElementaryStreamTypes.AUDIO) {
  14058. if (parsedCodec === 'ec-3' || parsedCodec === 'ac-3' || parsedCodec === 'alac') {
  14059. return parsedCodec;
  14060. }
  14061. if (parsedCodec === 'fLaC' || parsedCodec === 'Opus') {
  14062. // Opting not to get `preferManagedMediaSource` from player config for isSupported() check for simplicity
  14063. var preferManagedMediaSource = false;
  14064. return getCodecCompatibleName(parsedCodec, preferManagedMediaSource);
  14065. }
  14066. logger.warn("Unhandled audio codec \"" + parsedCodec + "\" in mp4 MAP");
  14067. return parsedCodec || 'mp4a';
  14068. }
  14069. // Provide defaults based on codec type
  14070. // This allows for some playback of some fmp4 playlists without CODECS defined in manifest
  14071. logger.warn("Unhandled video codec \"" + parsedCodec + "\" in mp4 MAP");
  14072. return parsedCodec || 'avc1';
  14073. }
  14074. var now;
  14075. // performance.now() not available on WebWorker, at least on Safari Desktop
  14076. try {
  14077. now = self.performance.now.bind(self.performance);
  14078. } catch (err) {
  14079. now = Date.now;
  14080. }
  14081. var muxConfig = [{
  14082. demux: MP4Demuxer,
  14083. remux: PassThroughRemuxer
  14084. }, {
  14085. demux: TSDemuxer,
  14086. remux: MP4Remuxer
  14087. }, {
  14088. demux: AACDemuxer,
  14089. remux: MP4Remuxer
  14090. }, {
  14091. demux: MP3Demuxer,
  14092. remux: MP4Remuxer
  14093. }];
  14094. var Transmuxer = /*#__PURE__*/function () {
  14095. function Transmuxer(observer, typeSupported, config, vendor, id, logger) {
  14096. this.asyncResult = false;
  14097. this.logger = void 0;
  14098. this.observer = void 0;
  14099. this.typeSupported = void 0;
  14100. this.config = void 0;
  14101. this.id = void 0;
  14102. this.demuxer = void 0;
  14103. this.remuxer = void 0;
  14104. this.decrypter = void 0;
  14105. this.probe = void 0;
  14106. this.decryptionPromise = null;
  14107. this.transmuxConfig = void 0;
  14108. this.currentTransmuxState = void 0;
  14109. this.observer = observer;
  14110. this.typeSupported = typeSupported;
  14111. this.config = config;
  14112. this.id = id;
  14113. this.logger = logger;
  14114. }
  14115. var _proto = Transmuxer.prototype;
  14116. _proto.configure = function configure(transmuxConfig) {
  14117. this.transmuxConfig = transmuxConfig;
  14118. if (this.decrypter) {
  14119. this.decrypter.reset();
  14120. }
  14121. };
  14122. _proto.push = function push(data, decryptdata, chunkMeta, state) {
  14123. var _this = this;
  14124. var stats = chunkMeta.transmuxing;
  14125. stats.executeStart = now();
  14126. var uintData = new Uint8Array(data);
  14127. var currentTransmuxState = this.currentTransmuxState,
  14128. transmuxConfig = this.transmuxConfig;
  14129. if (state) {
  14130. this.currentTransmuxState = state;
  14131. }
  14132. var _ref = state || currentTransmuxState,
  14133. contiguous = _ref.contiguous,
  14134. discontinuity = _ref.discontinuity,
  14135. trackSwitch = _ref.trackSwitch,
  14136. accurateTimeOffset = _ref.accurateTimeOffset,
  14137. timeOffset = _ref.timeOffset,
  14138. initSegmentChange = _ref.initSegmentChange;
  14139. var audioCodec = transmuxConfig.audioCodec,
  14140. videoCodec = transmuxConfig.videoCodec,
  14141. defaultInitPts = transmuxConfig.defaultInitPts,
  14142. duration = transmuxConfig.duration,
  14143. initSegmentData = transmuxConfig.initSegmentData;
  14144. var keyData = getEncryptionType(uintData, decryptdata);
  14145. if (keyData && isFullSegmentEncryption(keyData.method)) {
  14146. var decrypter = this.getDecrypter();
  14147. var aesMode = getAesModeFromFullSegmentMethod(keyData.method);
  14148. // Software decryption is synchronous; webCrypto is not
  14149. if (decrypter.isSync()) {
  14150. // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
  14151. // data is handled in the flush() call
  14152. var decryptedData = decrypter.softwareDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer, aesMode);
  14153. // For Low-Latency HLS Parts, decrypt in place, since part parsing is expected on push progress
  14154. var loadingParts = chunkMeta.part > -1;
  14155. if (loadingParts) {
  14156. var _data = decrypter.flush();
  14157. decryptedData = _data ? _data.buffer : _data;
  14158. }
  14159. if (!decryptedData) {
  14160. stats.executeEnd = now();
  14161. return emptyResult(chunkMeta);
  14162. }
  14163. uintData = new Uint8Array(decryptedData);
  14164. } else {
  14165. this.asyncResult = true;
  14166. this.decryptionPromise = decrypter.webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer, aesMode).then(function (decryptedData) {
  14167. // Calling push here is important; if flush() is called while this is still resolving, this ensures that
  14168. // the decrypted data has been transmuxed
  14169. var result = _this.push(decryptedData, null, chunkMeta);
  14170. _this.decryptionPromise = null;
  14171. return result;
  14172. });
  14173. return this.decryptionPromise;
  14174. }
  14175. }
  14176. var resetMuxers = this.needsProbing(discontinuity, trackSwitch);
  14177. if (resetMuxers) {
  14178. var error = this.configureTransmuxer(uintData);
  14179. if (error) {
  14180. this.logger.warn("[transmuxer] " + error.message);
  14181. this.observer.emit(Events.ERROR, Events.ERROR, {
  14182. type: ErrorTypes.MEDIA_ERROR,
  14183. details: ErrorDetails.FRAG_PARSING_ERROR,
  14184. fatal: false,
  14185. error: error,
  14186. reason: error.message
  14187. });
  14188. stats.executeEnd = now();
  14189. return emptyResult(chunkMeta);
  14190. }
  14191. }
  14192. if (discontinuity || trackSwitch || initSegmentChange || resetMuxers) {
  14193. this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration, decryptdata);
  14194. }
  14195. if (discontinuity || initSegmentChange || resetMuxers) {
  14196. this.resetInitialTimestamp(defaultInitPts);
  14197. }
  14198. if (!contiguous) {
  14199. this.resetContiguity();
  14200. }
  14201. var result = this.transmux(uintData, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  14202. this.asyncResult = isPromise(result);
  14203. var currentState = this.currentTransmuxState;
  14204. currentState.contiguous = true;
  14205. currentState.discontinuity = false;
  14206. currentState.trackSwitch = false;
  14207. stats.executeEnd = now();
  14208. return result;
  14209. }
  14210. // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type)
  14211. ;
  14212. _proto.flush = function flush(chunkMeta) {
  14213. var _this2 = this;
  14214. var stats = chunkMeta.transmuxing;
  14215. stats.executeStart = now();
  14216. var decrypter = this.decrypter,
  14217. currentTransmuxState = this.currentTransmuxState,
  14218. decryptionPromise = this.decryptionPromise;
  14219. if (decryptionPromise) {
  14220. this.asyncResult = true;
  14221. // Upon resolution, the decryption promise calls push() and returns its TransmuxerResult up the stack. Therefore
  14222. // only flushing is required for async decryption
  14223. return decryptionPromise.then(function () {
  14224. return _this2.flush(chunkMeta);
  14225. });
  14226. }
  14227. var transmuxResults = [];
  14228. var timeOffset = currentTransmuxState.timeOffset;
  14229. if (decrypter) {
  14230. // The decrypter may have data cached, which needs to be demuxed. In this case we'll have two TransmuxResults
  14231. // This happens in the case that we receive only 1 push call for a segment (either for non-progressive downloads,
  14232. // or for progressive downloads with small segments)
  14233. var decryptedData = decrypter.flush();
  14234. if (decryptedData) {
  14235. // Push always returns a TransmuxerResult if decryptdata is null
  14236. transmuxResults.push(this.push(decryptedData.buffer, null, chunkMeta));
  14237. }
  14238. }
  14239. var demuxer = this.demuxer,
  14240. remuxer = this.remuxer;
  14241. if (!demuxer || !remuxer) {
  14242. // If probing failed, then Hls.js has been given content its not able to handle
  14243. stats.executeEnd = now();
  14244. var emptyResults = [emptyResult(chunkMeta)];
  14245. if (this.asyncResult) {
  14246. return Promise.resolve(emptyResults);
  14247. }
  14248. return emptyResults;
  14249. }
  14250. var demuxResultOrPromise = demuxer.flush(timeOffset);
  14251. if (isPromise(demuxResultOrPromise)) {
  14252. this.asyncResult = true;
  14253. // Decrypt final SAMPLE-AES samples
  14254. return demuxResultOrPromise.then(function (demuxResult) {
  14255. _this2.flushRemux(transmuxResults, demuxResult, chunkMeta);
  14256. return transmuxResults;
  14257. });
  14258. }
  14259. this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta);
  14260. if (this.asyncResult) {
  14261. return Promise.resolve(transmuxResults);
  14262. }
  14263. return transmuxResults;
  14264. };
  14265. _proto.flushRemux = function flushRemux(transmuxResults, demuxResult, chunkMeta) {
  14266. var audioTrack = demuxResult.audioTrack,
  14267. videoTrack = demuxResult.videoTrack,
  14268. id3Track = demuxResult.id3Track,
  14269. textTrack = demuxResult.textTrack;
  14270. var _this$currentTransmux = this.currentTransmuxState,
  14271. accurateTimeOffset = _this$currentTransmux.accurateTimeOffset,
  14272. timeOffset = _this$currentTransmux.timeOffset;
  14273. this.logger.log("[transmuxer.ts]: Flushed " + this.id + " sn: " + chunkMeta.sn + (chunkMeta.part > -1 ? ' part: ' + chunkMeta.part : '') + " of " + (this.id === PlaylistLevelType.MAIN ? 'level' : 'track') + " " + chunkMeta.level);
  14274. var remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, true, this.id);
  14275. transmuxResults.push({
  14276. remuxResult: remuxResult,
  14277. chunkMeta: chunkMeta
  14278. });
  14279. chunkMeta.transmuxing.executeEnd = now();
  14280. };
  14281. _proto.resetInitialTimestamp = function resetInitialTimestamp(defaultInitPts) {
  14282. var demuxer = this.demuxer,
  14283. remuxer = this.remuxer;
  14284. if (!demuxer || !remuxer) {
  14285. return;
  14286. }
  14287. demuxer.resetTimeStamp(defaultInitPts);
  14288. remuxer.resetTimeStamp(defaultInitPts);
  14289. };
  14290. _proto.resetContiguity = function resetContiguity() {
  14291. var demuxer = this.demuxer,
  14292. remuxer = this.remuxer;
  14293. if (!demuxer || !remuxer) {
  14294. return;
  14295. }
  14296. demuxer.resetContiguity();
  14297. remuxer.resetNextTimestamp();
  14298. };
  14299. _proto.resetInitSegment = function resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration, decryptdata) {
  14300. var demuxer = this.demuxer,
  14301. remuxer = this.remuxer;
  14302. if (!demuxer || !remuxer) {
  14303. return;
  14304. }
  14305. demuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration);
  14306. remuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, decryptdata);
  14307. };
  14308. _proto.destroy = function destroy() {
  14309. if (this.demuxer) {
  14310. this.demuxer.destroy();
  14311. this.demuxer = undefined;
  14312. }
  14313. if (this.remuxer) {
  14314. this.remuxer.destroy();
  14315. this.remuxer = undefined;
  14316. }
  14317. };
  14318. _proto.transmux = function transmux(data, keyData, timeOffset, accurateTimeOffset, chunkMeta) {
  14319. var result;
  14320. if (keyData && keyData.method === 'SAMPLE-AES') {
  14321. result = this.transmuxSampleAes(data, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  14322. } else {
  14323. result = this.transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta);
  14324. }
  14325. return result;
  14326. };
  14327. _proto.transmuxUnencrypted = function transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta) {
  14328. var _demux = this.demuxer.demux(data, timeOffset, false, !this.config.progressive),
  14329. audioTrack = _demux.audioTrack,
  14330. videoTrack = _demux.videoTrack,
  14331. id3Track = _demux.id3Track,
  14332. textTrack = _demux.textTrack;
  14333. var remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, false, this.id);
  14334. return {
  14335. remuxResult: remuxResult,
  14336. chunkMeta: chunkMeta
  14337. };
  14338. };
  14339. _proto.transmuxSampleAes = function transmuxSampleAes(data, decryptData, timeOffset, accurateTimeOffset, chunkMeta) {
  14340. var _this3 = this;
  14341. return this.demuxer.demuxSampleAes(data, decryptData, timeOffset).then(function (demuxResult) {
  14342. var remuxResult = _this3.remuxer.remux(demuxResult.audioTrack, demuxResult.videoTrack, demuxResult.id3Track, demuxResult.textTrack, timeOffset, accurateTimeOffset, false, _this3.id);
  14343. return {
  14344. remuxResult: remuxResult,
  14345. chunkMeta: chunkMeta
  14346. };
  14347. });
  14348. };
  14349. _proto.configureTransmuxer = function configureTransmuxer(data) {
  14350. var config = this.config,
  14351. observer = this.observer,
  14352. typeSupported = this.typeSupported;
  14353. // probe for content type
  14354. var mux;
  14355. for (var i = 0, len = muxConfig.length; i < len; i++) {
  14356. var _muxConfig$i$demux;
  14357. if ((_muxConfig$i$demux = muxConfig[i].demux) != null && _muxConfig$i$demux.probe(data, this.logger)) {
  14358. mux = muxConfig[i];
  14359. break;
  14360. }
  14361. }
  14362. if (!mux) {
  14363. return new Error('Failed to find demuxer by probing fragment data');
  14364. }
  14365. // so let's check that current remuxer and demuxer are still valid
  14366. var demuxer = this.demuxer;
  14367. var remuxer = this.remuxer;
  14368. var Remuxer = mux.remux;
  14369. var Demuxer = mux.demux;
  14370. if (!remuxer || !(remuxer instanceof Remuxer)) {
  14371. this.remuxer = new Remuxer(observer, config, typeSupported, this.logger);
  14372. }
  14373. if (!demuxer || !(demuxer instanceof Demuxer)) {
  14374. this.demuxer = new Demuxer(observer, config, typeSupported, this.logger);
  14375. this.probe = Demuxer.probe;
  14376. }
  14377. };
  14378. _proto.needsProbing = function needsProbing(discontinuity, trackSwitch) {
  14379. // in case of continuity change, or track switch
  14380. // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)
  14381. return !this.demuxer || !this.remuxer || discontinuity || trackSwitch;
  14382. };
  14383. _proto.getDecrypter = function getDecrypter() {
  14384. var decrypter = this.decrypter;
  14385. if (!decrypter) {
  14386. decrypter = this.decrypter = new Decrypter(this.config);
  14387. }
  14388. return decrypter;
  14389. };
  14390. return Transmuxer;
  14391. }();
  14392. function getEncryptionType(data, decryptData) {
  14393. var encryptionType = null;
  14394. if (data.byteLength > 0 && (decryptData == null ? void 0 : decryptData.key) != null && decryptData.iv !== null && decryptData.method != null) {
  14395. encryptionType = decryptData;
  14396. }
  14397. return encryptionType;
  14398. }
  14399. var emptyResult = function emptyResult(chunkMeta) {
  14400. return {
  14401. remuxResult: {},
  14402. chunkMeta: chunkMeta
  14403. };
  14404. };
  14405. function isPromise(p) {
  14406. return 'then' in p && p.then instanceof Function;
  14407. }
  14408. var TransmuxConfig = function TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPts) {
  14409. this.audioCodec = void 0;
  14410. this.videoCodec = void 0;
  14411. this.initSegmentData = void 0;
  14412. this.duration = void 0;
  14413. this.defaultInitPts = void 0;
  14414. this.audioCodec = audioCodec;
  14415. this.videoCodec = videoCodec;
  14416. this.initSegmentData = initSegmentData;
  14417. this.duration = duration;
  14418. this.defaultInitPts = defaultInitPts || null;
  14419. };
  14420. var TransmuxState = function TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange) {
  14421. this.discontinuity = void 0;
  14422. this.contiguous = void 0;
  14423. this.accurateTimeOffset = void 0;
  14424. this.trackSwitch = void 0;
  14425. this.timeOffset = void 0;
  14426. this.initSegmentChange = void 0;
  14427. this.discontinuity = discontinuity;
  14428. this.contiguous = contiguous;
  14429. this.accurateTimeOffset = accurateTimeOffset;
  14430. this.trackSwitch = trackSwitch;
  14431. this.timeOffset = timeOffset;
  14432. this.initSegmentChange = initSegmentChange;
  14433. };
  14434. function fetchSupported() {
  14435. if (
  14436. // @ts-ignore
  14437. self.fetch && self.AbortController && self.ReadableStream && self.Request) {
  14438. try {
  14439. new self.ReadableStream({}); // eslint-disable-line no-new
  14440. return true;
  14441. } catch (e) {
  14442. /* noop */
  14443. }
  14444. }
  14445. return false;
  14446. }
  14447. var BYTERANGE = /(\d+)-(\d+)\/(\d+)/;
  14448. var FetchLoader = /*#__PURE__*/function () {
  14449. function FetchLoader(config) {
  14450. this.fetchSetup = void 0;
  14451. this.requestTimeout = void 0;
  14452. this.request = null;
  14453. this.response = null;
  14454. this.controller = void 0;
  14455. this.context = null;
  14456. this.config = null;
  14457. this.callbacks = null;
  14458. this.stats = void 0;
  14459. this.loader = null;
  14460. this.fetchSetup = config.fetchSetup || getRequest;
  14461. this.controller = new self.AbortController();
  14462. this.stats = new LoadStats();
  14463. }
  14464. var _proto = FetchLoader.prototype;
  14465. _proto.destroy = function destroy() {
  14466. this.loader = this.callbacks = this.context = this.config = this.request = null;
  14467. this.abortInternal();
  14468. this.response = null;
  14469. // @ts-ignore
  14470. this.fetchSetup = this.controller = this.stats = null;
  14471. };
  14472. _proto.abortInternal = function abortInternal() {
  14473. if (this.controller && !this.stats.loading.end) {
  14474. this.stats.aborted = true;
  14475. this.controller.abort();
  14476. }
  14477. };
  14478. _proto.abort = function abort() {
  14479. var _this$callbacks;
  14480. this.abortInternal();
  14481. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  14482. this.callbacks.onAbort(this.stats, this.context, this.response);
  14483. }
  14484. };
  14485. _proto.load = function load(context, config, callbacks) {
  14486. var _this = this;
  14487. var stats = this.stats;
  14488. if (stats.loading.start) {
  14489. throw new Error('Loader can only be used once.');
  14490. }
  14491. stats.loading.start = self.performance.now();
  14492. var initParams = getRequestParameters(context, this.controller.signal);
  14493. var isArrayBuffer = context.responseType === 'arraybuffer';
  14494. var LENGTH = isArrayBuffer ? 'byteLength' : 'length';
  14495. var _config$loadPolicy = config.loadPolicy,
  14496. maxTimeToFirstByteMs = _config$loadPolicy.maxTimeToFirstByteMs,
  14497. maxLoadTimeMs = _config$loadPolicy.maxLoadTimeMs;
  14498. this.context = context;
  14499. this.config = config;
  14500. this.callbacks = callbacks;
  14501. this.request = this.fetchSetup(context, initParams);
  14502. self.clearTimeout(this.requestTimeout);
  14503. config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  14504. this.requestTimeout = self.setTimeout(function () {
  14505. if (_this.callbacks) {
  14506. _this.abortInternal();
  14507. _this.callbacks.onTimeout(stats, context, _this.response);
  14508. }
  14509. }, config.timeout);
  14510. var fetchPromise = isPromise(this.request) ? this.request.then(self.fetch) : self.fetch(this.request);
  14511. fetchPromise.then(function (response) {
  14512. var _this$callbacks2;
  14513. _this.response = _this.loader = response;
  14514. var first = Math.max(self.performance.now(), stats.loading.start);
  14515. self.clearTimeout(_this.requestTimeout);
  14516. config.timeout = maxLoadTimeMs;
  14517. _this.requestTimeout = self.setTimeout(function () {
  14518. if (_this.callbacks) {
  14519. _this.abortInternal();
  14520. _this.callbacks.onTimeout(stats, context, _this.response);
  14521. }
  14522. }, maxLoadTimeMs - (first - stats.loading.start));
  14523. if (!response.ok) {
  14524. var status = response.status,
  14525. statusText = response.statusText;
  14526. throw new FetchError(statusText || 'fetch, bad network response', status, response);
  14527. }
  14528. stats.loading.first = first;
  14529. stats.total = getContentLength(response.headers) || stats.total;
  14530. var onProgress = (_this$callbacks2 = _this.callbacks) == null ? void 0 : _this$callbacks2.onProgress;
  14531. if (onProgress && isFiniteNumber(config.highWaterMark)) {
  14532. return _this.loadProgressively(response, stats, context, config.highWaterMark, onProgress);
  14533. }
  14534. if (isArrayBuffer) {
  14535. return response.arrayBuffer();
  14536. }
  14537. if (context.responseType === 'json') {
  14538. return response.json();
  14539. }
  14540. return response.text();
  14541. }).then(function (responseData) {
  14542. var _this$callbacks3, _this$callbacks4;
  14543. var response = _this.response;
  14544. if (!response) {
  14545. throw new Error('loader destroyed');
  14546. }
  14547. self.clearTimeout(_this.requestTimeout);
  14548. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  14549. var total = responseData[LENGTH];
  14550. if (total) {
  14551. stats.loaded = stats.total = total;
  14552. }
  14553. var loaderResponse = {
  14554. url: response.url,
  14555. data: responseData,
  14556. code: response.status
  14557. };
  14558. var onProgress = (_this$callbacks3 = _this.callbacks) == null ? void 0 : _this$callbacks3.onProgress;
  14559. if (onProgress && !isFiniteNumber(config.highWaterMark)) {
  14560. onProgress(stats, context, responseData, response);
  14561. }
  14562. (_this$callbacks4 = _this.callbacks) == null ? void 0 : _this$callbacks4.onSuccess(loaderResponse, stats, context, response);
  14563. }).catch(function (error) {
  14564. var _this$callbacks5;
  14565. self.clearTimeout(_this.requestTimeout);
  14566. if (stats.aborted) {
  14567. return;
  14568. }
  14569. // CORS errors result in an undefined code. Set it to 0 here to align with XHR's behavior
  14570. // when destroying, 'error' itself can be undefined
  14571. var code = !error ? 0 : error.code || 0;
  14572. var text = !error ? null : error.message;
  14573. (_this$callbacks5 = _this.callbacks) == null ? void 0 : _this$callbacks5.onError({
  14574. code: code,
  14575. text: text
  14576. }, context, error ? error.details : null, stats);
  14577. });
  14578. };
  14579. _proto.getCacheAge = function getCacheAge() {
  14580. var result = null;
  14581. if (this.response) {
  14582. var ageHeader = this.response.headers.get('age');
  14583. result = ageHeader ? parseFloat(ageHeader) : null;
  14584. }
  14585. return result;
  14586. };
  14587. _proto.getResponseHeader = function getResponseHeader(name) {
  14588. return this.response ? this.response.headers.get(name) : null;
  14589. };
  14590. _proto.loadProgressively = function loadProgressively(response, stats, context, highWaterMark, onProgress) {
  14591. if (highWaterMark === void 0) {
  14592. highWaterMark = 0;
  14593. }
  14594. var chunkCache = new ChunkCache();
  14595. var reader = response.body.getReader();
  14596. var _pump = function pump() {
  14597. return reader.read().then(function (data) {
  14598. if (data.done) {
  14599. if (chunkCache.dataLength) {
  14600. onProgress(stats, context, chunkCache.flush().buffer, response);
  14601. }
  14602. return Promise.resolve(new ArrayBuffer(0));
  14603. }
  14604. var chunk = data.value;
  14605. var len = chunk.length;
  14606. stats.loaded += len;
  14607. if (len < highWaterMark || chunkCache.dataLength) {
  14608. // The current chunk is too small to to be emitted or the cache already has data
  14609. // Push it to the cache
  14610. chunkCache.push(chunk);
  14611. if (chunkCache.dataLength >= highWaterMark) {
  14612. // flush in order to join the typed arrays
  14613. onProgress(stats, context, chunkCache.flush().buffer, response);
  14614. }
  14615. } else {
  14616. // If there's nothing cached already, and the chache is large enough
  14617. // just emit the progress event
  14618. onProgress(stats, context, chunk.buffer, response);
  14619. }
  14620. return _pump();
  14621. }).catch(function () {
  14622. /* aborted */
  14623. return Promise.reject();
  14624. });
  14625. };
  14626. return _pump();
  14627. };
  14628. return FetchLoader;
  14629. }();
  14630. function getRequestParameters(context, signal) {
  14631. var initParams = {
  14632. method: 'GET',
  14633. mode: 'cors',
  14634. credentials: 'same-origin',
  14635. signal: signal,
  14636. headers: new self.Headers(_extends({}, context.headers))
  14637. };
  14638. if (context.rangeEnd) {
  14639. initParams.headers.set('Range', 'bytes=' + context.rangeStart + '-' + String(context.rangeEnd - 1));
  14640. }
  14641. return initParams;
  14642. }
  14643. function getByteRangeLength(byteRangeHeader) {
  14644. var result = BYTERANGE.exec(byteRangeHeader);
  14645. if (result) {
  14646. return parseInt(result[2]) - parseInt(result[1]) + 1;
  14647. }
  14648. }
  14649. function getContentLength(headers) {
  14650. var contentRange = headers.get('Content-Range');
  14651. if (contentRange) {
  14652. var byteRangeLength = getByteRangeLength(contentRange);
  14653. if (isFiniteNumber(byteRangeLength)) {
  14654. return byteRangeLength;
  14655. }
  14656. }
  14657. var contentLength = headers.get('Content-Length');
  14658. if (contentLength) {
  14659. return parseInt(contentLength);
  14660. }
  14661. }
  14662. function getRequest(context, initParams) {
  14663. return new self.Request(context.url, initParams);
  14664. }
  14665. var FetchError = /*#__PURE__*/function (_Error) {
  14666. function FetchError(message, code, details) {
  14667. var _this2;
  14668. _this2 = _Error.call(this, message) || this;
  14669. _this2.code = void 0;
  14670. _this2.details = void 0;
  14671. _this2.code = code;
  14672. _this2.details = details;
  14673. return _this2;
  14674. }
  14675. _inheritsLoose(FetchError, _Error);
  14676. return FetchError;
  14677. }(/*#__PURE__*/_wrapNativeSuper(Error));
  14678. var AGE_HEADER_LINE_REGEX = /^age:\s*[\d.]+\s*$/im;
  14679. var XhrLoader = /*#__PURE__*/function () {
  14680. function XhrLoader(config) {
  14681. this.xhrSetup = void 0;
  14682. this.requestTimeout = void 0;
  14683. this.retryTimeout = void 0;
  14684. this.retryDelay = void 0;
  14685. this.config = null;
  14686. this.callbacks = null;
  14687. this.context = null;
  14688. this.loader = null;
  14689. this.stats = void 0;
  14690. this.xhrSetup = config ? config.xhrSetup || null : null;
  14691. this.stats = new LoadStats();
  14692. this.retryDelay = 0;
  14693. }
  14694. var _proto = XhrLoader.prototype;
  14695. _proto.destroy = function destroy() {
  14696. this.callbacks = null;
  14697. this.abortInternal();
  14698. this.loader = null;
  14699. this.config = null;
  14700. this.context = null;
  14701. this.xhrSetup = null;
  14702. };
  14703. _proto.abortInternal = function abortInternal() {
  14704. var loader = this.loader;
  14705. self.clearTimeout(this.requestTimeout);
  14706. self.clearTimeout(this.retryTimeout);
  14707. if (loader) {
  14708. loader.onreadystatechange = null;
  14709. loader.onprogress = null;
  14710. if (loader.readyState !== 4) {
  14711. this.stats.aborted = true;
  14712. loader.abort();
  14713. }
  14714. }
  14715. };
  14716. _proto.abort = function abort() {
  14717. var _this$callbacks;
  14718. this.abortInternal();
  14719. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  14720. this.callbacks.onAbort(this.stats, this.context, this.loader);
  14721. }
  14722. };
  14723. _proto.load = function load(context, config, callbacks) {
  14724. if (this.stats.loading.start) {
  14725. throw new Error('Loader can only be used once.');
  14726. }
  14727. this.stats.loading.start = self.performance.now();
  14728. this.context = context;
  14729. this.config = config;
  14730. this.callbacks = callbacks;
  14731. this.loadInternal();
  14732. };
  14733. _proto.loadInternal = function loadInternal() {
  14734. var _this = this;
  14735. var config = this.config,
  14736. context = this.context;
  14737. if (!config || !context) {
  14738. return;
  14739. }
  14740. var xhr = this.loader = new self.XMLHttpRequest();
  14741. var stats = this.stats;
  14742. stats.loading.first = 0;
  14743. stats.loaded = 0;
  14744. stats.aborted = false;
  14745. var xhrSetup = this.xhrSetup;
  14746. if (xhrSetup) {
  14747. Promise.resolve().then(function () {
  14748. if (_this.loader !== xhr || _this.stats.aborted) return;
  14749. return xhrSetup(xhr, context.url);
  14750. }).catch(function (error) {
  14751. if (_this.loader !== xhr || _this.stats.aborted) return;
  14752. xhr.open('GET', context.url, true);
  14753. return xhrSetup(xhr, context.url);
  14754. }).then(function () {
  14755. if (_this.loader !== xhr || _this.stats.aborted) return;
  14756. _this.openAndSendXhr(xhr, context, config);
  14757. }).catch(function (error) {
  14758. var _this$callbacks2;
  14759. // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
  14760. (_this$callbacks2 = _this.callbacks) == null ? void 0 : _this$callbacks2.onError({
  14761. code: xhr.status,
  14762. text: error.message
  14763. }, context, xhr, stats);
  14764. return;
  14765. });
  14766. } else {
  14767. this.openAndSendXhr(xhr, context, config);
  14768. }
  14769. };
  14770. _proto.openAndSendXhr = function openAndSendXhr(xhr, context, config) {
  14771. if (!xhr.readyState) {
  14772. xhr.open('GET', context.url, true);
  14773. }
  14774. var headers = context.headers;
  14775. var _config$loadPolicy = config.loadPolicy,
  14776. maxTimeToFirstByteMs = _config$loadPolicy.maxTimeToFirstByteMs,
  14777. maxLoadTimeMs = _config$loadPolicy.maxLoadTimeMs;
  14778. if (headers) {
  14779. for (var header in headers) {
  14780. xhr.setRequestHeader(header, headers[header]);
  14781. }
  14782. }
  14783. if (context.rangeEnd) {
  14784. xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));
  14785. }
  14786. xhr.onreadystatechange = this.readystatechange.bind(this);
  14787. xhr.onprogress = this.loadprogress.bind(this);
  14788. xhr.responseType = context.responseType;
  14789. // setup timeout before we perform request
  14790. self.clearTimeout(this.requestTimeout);
  14791. config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  14792. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);
  14793. xhr.send();
  14794. };
  14795. _proto.readystatechange = function readystatechange() {
  14796. var context = this.context,
  14797. xhr = this.loader,
  14798. stats = this.stats;
  14799. if (!context || !xhr) {
  14800. return;
  14801. }
  14802. var readyState = xhr.readyState;
  14803. var config = this.config;
  14804. // don't proceed if xhr has been aborted
  14805. if (stats.aborted) {
  14806. return;
  14807. }
  14808. // >= HEADERS_RECEIVED
  14809. if (readyState >= 2) {
  14810. if (stats.loading.first === 0) {
  14811. stats.loading.first = Math.max(self.performance.now(), stats.loading.start);
  14812. // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet
  14813. if (config.timeout !== config.loadPolicy.maxLoadTimeMs) {
  14814. self.clearTimeout(this.requestTimeout);
  14815. config.timeout = config.loadPolicy.maxLoadTimeMs;
  14816. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.loadPolicy.maxLoadTimeMs - (stats.loading.first - stats.loading.start));
  14817. }
  14818. }
  14819. if (readyState === 4) {
  14820. self.clearTimeout(this.requestTimeout);
  14821. xhr.onreadystatechange = null;
  14822. xhr.onprogress = null;
  14823. var _status = xhr.status;
  14824. // http status between 200 to 299 are all successful
  14825. var useResponseText = xhr.responseType === 'text' ? xhr.responseText : null;
  14826. if (_status >= 200 && _status < 300) {
  14827. var data = useResponseText != null ? useResponseText : xhr.response;
  14828. if (data != null) {
  14829. var _this$callbacks3, _this$callbacks4;
  14830. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  14831. var len = xhr.responseType === 'arraybuffer' ? data.byteLength : data.length;
  14832. stats.loaded = stats.total = len;
  14833. stats.bwEstimate = stats.total * 8000 / (stats.loading.end - stats.loading.first);
  14834. var onProgress = (_this$callbacks3 = this.callbacks) == null ? void 0 : _this$callbacks3.onProgress;
  14835. if (onProgress) {
  14836. onProgress(stats, context, data, xhr);
  14837. }
  14838. var _response = {
  14839. url: xhr.responseURL,
  14840. data: data,
  14841. code: _status
  14842. };
  14843. (_this$callbacks4 = this.callbacks) == null ? void 0 : _this$callbacks4.onSuccess(_response, stats, context, xhr);
  14844. return;
  14845. }
  14846. }
  14847. // Handle bad status or nullish response
  14848. var retryConfig = config.loadPolicy.errorRetry;
  14849. var retryCount = stats.retry;
  14850. // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error
  14851. var response = {
  14852. url: context.url,
  14853. data: undefined,
  14854. code: _status
  14855. };
  14856. if (shouldRetry(retryConfig, retryCount, false, response)) {
  14857. this.retry(retryConfig);
  14858. } else {
  14859. var _this$callbacks5;
  14860. logger.error(_status + " while loading " + context.url);
  14861. (_this$callbacks5 = this.callbacks) == null ? void 0 : _this$callbacks5.onError({
  14862. code: _status,
  14863. text: xhr.statusText
  14864. }, context, xhr, stats);
  14865. }
  14866. }
  14867. }
  14868. };
  14869. _proto.loadtimeout = function loadtimeout() {
  14870. if (!this.config) return;
  14871. var retryConfig = this.config.loadPolicy.timeoutRetry;
  14872. var retryCount = this.stats.retry;
  14873. if (shouldRetry(retryConfig, retryCount, true)) {
  14874. this.retry(retryConfig);
  14875. } else {
  14876. var _this$context;
  14877. logger.warn("timeout while loading " + ((_this$context = this.context) == null ? void 0 : _this$context.url));
  14878. var callbacks = this.callbacks;
  14879. if (callbacks) {
  14880. this.abortInternal();
  14881. callbacks.onTimeout(this.stats, this.context, this.loader);
  14882. }
  14883. }
  14884. };
  14885. _proto.retry = function retry(retryConfig) {
  14886. var context = this.context,
  14887. stats = this.stats;
  14888. this.retryDelay = getRetryDelay(retryConfig, stats.retry);
  14889. stats.retry++;
  14890. logger.warn((status ? 'HTTP Status ' + status : 'Timeout') + " while loading " + (context == null ? void 0 : context.url) + ", retrying " + stats.retry + "/" + retryConfig.maxNumRetry + " in " + this.retryDelay + "ms");
  14891. // abort and reset internal state
  14892. this.abortInternal();
  14893. this.loader = null;
  14894. // schedule retry
  14895. self.clearTimeout(this.retryTimeout);
  14896. this.retryTimeout = self.setTimeout(this.loadInternal.bind(this), this.retryDelay);
  14897. };
  14898. _proto.loadprogress = function loadprogress(event) {
  14899. var stats = this.stats;
  14900. stats.loaded = event.loaded;
  14901. if (event.lengthComputable) {
  14902. stats.total = event.total;
  14903. }
  14904. };
  14905. _proto.getCacheAge = function getCacheAge() {
  14906. var result = null;
  14907. if (this.loader && AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())) {
  14908. var ageHeader = this.loader.getResponseHeader('age');
  14909. result = ageHeader ? parseFloat(ageHeader) : null;
  14910. }
  14911. return result;
  14912. };
  14913. _proto.getResponseHeader = function getResponseHeader(name) {
  14914. if (this.loader && new RegExp("^" + name + ":\\s*[\\d.]+\\s*$", 'im').test(this.loader.getAllResponseHeaders())) {
  14915. return this.loader.getResponseHeader(name);
  14916. }
  14917. return null;
  14918. };
  14919. return XhrLoader;
  14920. }();
  14921. /**
  14922. * @deprecated use fragLoadPolicy.default
  14923. */
  14924. /**
  14925. * @deprecated use manifestLoadPolicy.default and playlistLoadPolicy.default
  14926. */
  14927. var defaultLoadPolicy = {
  14928. maxTimeToFirstByteMs: 8000,
  14929. maxLoadTimeMs: 20000,
  14930. timeoutRetry: null,
  14931. errorRetry: null
  14932. };
  14933. /**
  14934. * @ignore
  14935. * If possible, keep hlsDefaultConfig shallow
  14936. * It is cloned whenever a new Hls instance is created, by keeping the config
  14937. * shallow the properties are cloned, and we don't end up manipulating the default
  14938. */
  14939. var hlsDefaultConfig = _objectSpread2(_objectSpread2({
  14940. autoStartLoad: true,
  14941. // used by stream-controller
  14942. startPosition: -1,
  14943. // used by stream-controller
  14944. defaultAudioCodec: undefined,
  14945. // used by stream-controller
  14946. debug: false,
  14947. // used by logger
  14948. capLevelOnFPSDrop: false,
  14949. // used by fps-controller
  14950. capLevelToPlayerSize: false,
  14951. // used by cap-level-controller
  14952. ignoreDevicePixelRatio: false,
  14953. // used by cap-level-controller
  14954. maxDevicePixelRatio: Number.POSITIVE_INFINITY,
  14955. // used by cap-level-controller
  14956. preferManagedMediaSource: true,
  14957. initialLiveManifestSize: 1,
  14958. // used by stream-controller
  14959. maxBufferLength: 30,
  14960. // used by stream-controller
  14961. backBufferLength: Infinity,
  14962. // used by buffer-controller
  14963. frontBufferFlushThreshold: Infinity,
  14964. startOnSegmentBoundary: false,
  14965. // used by stream-controller
  14966. maxBufferSize: 60 * 1000 * 1000,
  14967. // used by stream-controller
  14968. maxFragLookUpTolerance: 0.25,
  14969. // used by stream-controller
  14970. maxBufferHole: 0.1,
  14971. // used by stream-controller and gap-controller
  14972. detectStallWithCurrentTimeMs: 1250,
  14973. // used by gap-controller
  14974. highBufferWatchdogPeriod: 2,
  14975. // used by gap-controller
  14976. nudgeOffset: 0.1,
  14977. // used by gap-controller
  14978. nudgeMaxRetry: 3,
  14979. // used by gap-controller
  14980. nudgeOnVideoHole: true,
  14981. // used by gap-controller
  14982. liveSyncMode: 'edge',
  14983. // used by stream-controller
  14984. liveSyncDurationCount: 3,
  14985. // used by latency-controller
  14986. liveSyncOnStallIncrease: 1,
  14987. // used by latency-controller
  14988. liveMaxLatencyDurationCount: Infinity,
  14989. // used by latency-controller
  14990. liveSyncDuration: undefined,
  14991. // used by latency-controller
  14992. liveMaxLatencyDuration: undefined,
  14993. // used by latency-controller
  14994. maxLiveSyncPlaybackRate: 1,
  14995. // used by latency-controller
  14996. liveDurationInfinity: false,
  14997. // used by buffer-controller
  14998. /**
  14999. * @deprecated use backBufferLength
  15000. */
  15001. liveBackBufferLength: null,
  15002. // used by buffer-controller
  15003. maxMaxBufferLength: 600,
  15004. // used by stream-controller
  15005. enableWorker: true,
  15006. // used by transmuxer
  15007. workerPath: null,
  15008. // used by transmuxer
  15009. enableSoftwareAES: true,
  15010. // used by decrypter
  15011. startLevel: undefined,
  15012. // used by level-controller
  15013. startFragPrefetch: false,
  15014. // used by stream-controller
  15015. fpsDroppedMonitoringPeriod: 5000,
  15016. // used by fps-controller
  15017. fpsDroppedMonitoringThreshold: 0.2,
  15018. // used by fps-controller
  15019. appendErrorMaxRetry: 3,
  15020. // used by buffer-controller
  15021. ignorePlaylistParsingErrors: false,
  15022. loader: XhrLoader,
  15023. // loader: FetchLoader,
  15024. fLoader: undefined,
  15025. // used by fragment-loader
  15026. pLoader: undefined,
  15027. // used by playlist-loader
  15028. xhrSetup: undefined,
  15029. // used by xhr-loader
  15030. licenseXhrSetup: undefined,
  15031. // used by eme-controller
  15032. licenseResponseCallback: undefined,
  15033. // used by eme-controller
  15034. abrController: AbrController,
  15035. bufferController: BufferController,
  15036. capLevelController: CapLevelController,
  15037. errorController: ErrorController,
  15038. fpsController: FPSController,
  15039. stretchShortVideoTrack: false,
  15040. // used by mp4-remuxer
  15041. maxAudioFramesDrift: 1,
  15042. // used by mp4-remuxer
  15043. forceKeyFrameOnDiscontinuity: true,
  15044. // used by ts-demuxer
  15045. abrEwmaFastLive: 3,
  15046. // used by abr-controller
  15047. abrEwmaSlowLive: 9,
  15048. // used by abr-controller
  15049. abrEwmaFastVoD: 3,
  15050. // used by abr-controller
  15051. abrEwmaSlowVoD: 9,
  15052. // used by abr-controller
  15053. abrEwmaDefaultEstimate: 5e5,
  15054. // 500 kbps // used by abr-controller
  15055. abrEwmaDefaultEstimateMax: 5e6,
  15056. // 5 mbps
  15057. abrBandWidthFactor: 0.95,
  15058. // used by abr-controller
  15059. abrBandWidthUpFactor: 0.7,
  15060. // used by abr-controller
  15061. abrMaxWithRealBitrate: false,
  15062. // used by abr-controller
  15063. maxStarvationDelay: 4,
  15064. // used by abr-controller
  15065. maxLoadingDelay: 4,
  15066. // used by abr-controller
  15067. minAutoBitrate: 0,
  15068. // used by hls
  15069. emeEnabled: false,
  15070. // used by eme-controller
  15071. widevineLicenseUrl: undefined,
  15072. // used by eme-controller
  15073. drmSystems: {},
  15074. // used by eme-controller
  15075. drmSystemOptions: {},
  15076. // used by eme-controller
  15077. requestMediaKeySystemAccessFunc: null,
  15078. // used by eme-controller
  15079. requireKeySystemAccessOnStart: false,
  15080. // used by eme-controller
  15081. testBandwidth: true,
  15082. progressive: false,
  15083. lowLatencyMode: true,
  15084. cmcd: undefined,
  15085. enableDateRangeMetadataCues: true,
  15086. enableEmsgMetadataCues: true,
  15087. enableEmsgKLVMetadata: false,
  15088. enableID3MetadataCues: true,
  15089. enableInterstitialPlayback: false,
  15090. interstitialAppendInPlace: true,
  15091. interstitialLiveLookAhead: 10,
  15092. useMediaCapabilities: false,
  15093. preserveManualLevelOnError: false,
  15094. certLoadPolicy: {
  15095. default: defaultLoadPolicy
  15096. },
  15097. keyLoadPolicy: {
  15098. default: {
  15099. maxTimeToFirstByteMs: 8000,
  15100. maxLoadTimeMs: 20000,
  15101. timeoutRetry: {
  15102. maxNumRetry: 1,
  15103. retryDelayMs: 1000,
  15104. maxRetryDelayMs: 20000,
  15105. backoff: 'linear'
  15106. },
  15107. errorRetry: {
  15108. maxNumRetry: 8,
  15109. retryDelayMs: 1000,
  15110. maxRetryDelayMs: 20000,
  15111. backoff: 'linear'
  15112. }
  15113. }
  15114. },
  15115. manifestLoadPolicy: {
  15116. default: {
  15117. maxTimeToFirstByteMs: Infinity,
  15118. maxLoadTimeMs: 20000,
  15119. timeoutRetry: {
  15120. maxNumRetry: 2,
  15121. retryDelayMs: 0,
  15122. maxRetryDelayMs: 0
  15123. },
  15124. errorRetry: {
  15125. maxNumRetry: 1,
  15126. retryDelayMs: 1000,
  15127. maxRetryDelayMs: 8000
  15128. }
  15129. }
  15130. },
  15131. playlistLoadPolicy: {
  15132. default: {
  15133. maxTimeToFirstByteMs: 10000,
  15134. maxLoadTimeMs: 20000,
  15135. timeoutRetry: {
  15136. maxNumRetry: 2,
  15137. retryDelayMs: 0,
  15138. maxRetryDelayMs: 0
  15139. },
  15140. errorRetry: {
  15141. maxNumRetry: 2,
  15142. retryDelayMs: 1000,
  15143. maxRetryDelayMs: 8000
  15144. }
  15145. }
  15146. },
  15147. fragLoadPolicy: {
  15148. default: {
  15149. maxTimeToFirstByteMs: 10000,
  15150. maxLoadTimeMs: 120000,
  15151. timeoutRetry: {
  15152. maxNumRetry: 4,
  15153. retryDelayMs: 0,
  15154. maxRetryDelayMs: 0
  15155. },
  15156. errorRetry: {
  15157. maxNumRetry: 6,
  15158. retryDelayMs: 1000,
  15159. maxRetryDelayMs: 8000
  15160. }
  15161. }
  15162. },
  15163. steeringManifestLoadPolicy: {
  15164. default: {
  15165. maxTimeToFirstByteMs: 10000,
  15166. maxLoadTimeMs: 20000,
  15167. timeoutRetry: {
  15168. maxNumRetry: 2,
  15169. retryDelayMs: 0,
  15170. maxRetryDelayMs: 0
  15171. },
  15172. errorRetry: {
  15173. maxNumRetry: 1,
  15174. retryDelayMs: 1000,
  15175. maxRetryDelayMs: 8000
  15176. }
  15177. }
  15178. },
  15179. interstitialAssetListLoadPolicy: {
  15180. default: defaultLoadPolicy
  15181. },
  15182. // These default settings are deprecated in favor of the above policies
  15183. // and are maintained for backwards compatibility
  15184. manifestLoadingTimeOut: 10000,
  15185. manifestLoadingMaxRetry: 1,
  15186. manifestLoadingRetryDelay: 1000,
  15187. manifestLoadingMaxRetryTimeout: 64000,
  15188. levelLoadingTimeOut: 10000,
  15189. levelLoadingMaxRetry: 4,
  15190. levelLoadingRetryDelay: 1000,
  15191. levelLoadingMaxRetryTimeout: 64000,
  15192. fragLoadingTimeOut: 20000,
  15193. fragLoadingMaxRetry: 6,
  15194. fragLoadingRetryDelay: 1000,
  15195. fragLoadingMaxRetryTimeout: 64000
  15196. }, timelineConfig()), {}, {
  15197. subtitleStreamController: undefined,
  15198. subtitleTrackController: undefined,
  15199. timelineController: undefined,
  15200. audioStreamController: undefined,
  15201. audioTrackController: undefined,
  15202. emeController: undefined,
  15203. cmcdController: undefined,
  15204. contentSteeringController: ContentSteeringController ,
  15205. interstitialsController: undefined
  15206. });
  15207. function timelineConfig() {
  15208. return {
  15209. cueHandler: Cues,
  15210. // used by timeline-controller
  15211. enableWebVTT: false,
  15212. // used by timeline-controller
  15213. enableIMSC1: false,
  15214. // used by timeline-controller
  15215. enableCEA708Captions: false,
  15216. // used by timeline-controller
  15217. captionsTextTrack1Label: 'English',
  15218. // used by timeline-controller
  15219. captionsTextTrack1LanguageCode: 'en',
  15220. // used by timeline-controller
  15221. captionsTextTrack2Label: 'Spanish',
  15222. // used by timeline-controller
  15223. captionsTextTrack2LanguageCode: 'es',
  15224. // used by timeline-controller
  15225. captionsTextTrack3Label: 'Unknown CC',
  15226. // used by timeline-controller
  15227. captionsTextTrack3LanguageCode: '',
  15228. // used by timeline-controller
  15229. captionsTextTrack4Label: 'Unknown CC',
  15230. // used by timeline-controller
  15231. captionsTextTrack4LanguageCode: '',
  15232. // used by timeline-controller
  15233. renderTextTracksNatively: true
  15234. };
  15235. }
  15236. /**
  15237. * @ignore
  15238. */
  15239. function mergeConfig(defaultConfig, userConfig, logger) {
  15240. if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {
  15241. throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");
  15242. }
  15243. if (userConfig.liveMaxLatencyDurationCount !== undefined && (userConfig.liveSyncDurationCount === undefined || userConfig.liveMaxLatencyDurationCount <= userConfig.liveSyncDurationCount)) {
  15244. throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');
  15245. }
  15246. if (userConfig.liveMaxLatencyDuration !== undefined && (userConfig.liveSyncDuration === undefined || userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)) {
  15247. throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');
  15248. }
  15249. var defaultsCopy = deepCpy(defaultConfig);
  15250. // Backwards compatibility with deprecated config values
  15251. var deprecatedSettingTypes = ['manifest', 'level', 'frag'];
  15252. var deprecatedSettings = ['TimeOut', 'MaxRetry', 'RetryDelay', 'MaxRetryTimeout'];
  15253. deprecatedSettingTypes.forEach(function (type) {
  15254. var policyName = (type === 'level' ? 'playlist' : type) + "LoadPolicy";
  15255. var policyNotSet = userConfig[policyName] === undefined;
  15256. var report = [];
  15257. deprecatedSettings.forEach(function (setting) {
  15258. var deprecatedSetting = type + "Loading" + setting;
  15259. var value = userConfig[deprecatedSetting];
  15260. if (value !== undefined && policyNotSet) {
  15261. report.push(deprecatedSetting);
  15262. var settings = defaultsCopy[policyName].default;
  15263. userConfig[policyName] = {
  15264. default: settings
  15265. };
  15266. switch (setting) {
  15267. case 'TimeOut':
  15268. settings.maxLoadTimeMs = value;
  15269. settings.maxTimeToFirstByteMs = value;
  15270. break;
  15271. case 'MaxRetry':
  15272. settings.errorRetry.maxNumRetry = value;
  15273. settings.timeoutRetry.maxNumRetry = value;
  15274. break;
  15275. case 'RetryDelay':
  15276. settings.errorRetry.retryDelayMs = value;
  15277. settings.timeoutRetry.retryDelayMs = value;
  15278. break;
  15279. case 'MaxRetryTimeout':
  15280. settings.errorRetry.maxRetryDelayMs = value;
  15281. settings.timeoutRetry.maxRetryDelayMs = value;
  15282. break;
  15283. }
  15284. }
  15285. });
  15286. if (report.length) {
  15287. logger.warn("hls.js config: \"" + report.join('", "') + "\" setting(s) are deprecated, use \"" + policyName + "\": " + stringify(userConfig[policyName]));
  15288. }
  15289. });
  15290. return _objectSpread2(_objectSpread2({}, defaultsCopy), userConfig);
  15291. }
  15292. function deepCpy(obj) {
  15293. if (obj && typeof obj === 'object') {
  15294. if (Array.isArray(obj)) {
  15295. return obj.map(deepCpy);
  15296. }
  15297. return Object.keys(obj).reduce(function (result, key) {
  15298. result[key] = deepCpy(obj[key]);
  15299. return result;
  15300. }, {});
  15301. }
  15302. return obj;
  15303. }
  15304. /**
  15305. * @ignore
  15306. */
  15307. function enableStreamingMode(config, logger) {
  15308. var currentLoader = config.loader;
  15309. if (currentLoader !== FetchLoader && currentLoader !== XhrLoader) {
  15310. // If a developer has configured their own loader, respect that choice
  15311. logger.log('[config]: Custom loader detected, cannot enable progressive streaming');
  15312. config.progressive = false;
  15313. } else {
  15314. var canStreamProgressively = fetchSupported();
  15315. if (canStreamProgressively) {
  15316. config.loader = FetchLoader;
  15317. config.progressive = true;
  15318. config.enableSoftwareAES = true;
  15319. logger.log('[config]: Progressive streaming enabled, using FetchLoader');
  15320. }
  15321. }
  15322. }
  15323. var FragmentState = {
  15324. NOT_LOADED: "NOT_LOADED",
  15325. APPENDING: "APPENDING",
  15326. PARTIAL: "PARTIAL",
  15327. OK: "OK"
  15328. };
  15329. var FragmentTracker = /*#__PURE__*/function () {
  15330. function FragmentTracker(hls) {
  15331. this.activePartLists = Object.create(null);
  15332. this.endListFragments = Object.create(null);
  15333. this.fragments = Object.create(null);
  15334. this.timeRanges = Object.create(null);
  15335. this.bufferPadding = 0.2;
  15336. this.hls = void 0;
  15337. this.hasGaps = false;
  15338. this.hls = hls;
  15339. this._registerListeners();
  15340. }
  15341. var _proto = FragmentTracker.prototype;
  15342. _proto._registerListeners = function _registerListeners() {
  15343. var hls = this.hls;
  15344. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  15345. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  15346. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  15347. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  15348. };
  15349. _proto._unregisterListeners = function _unregisterListeners() {
  15350. var hls = this.hls;
  15351. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  15352. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  15353. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  15354. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  15355. };
  15356. _proto.destroy = function destroy() {
  15357. this._unregisterListeners();
  15358. // @ts-ignore
  15359. this.fragments =
  15360. // @ts-ignore
  15361. this.activePartLists =
  15362. // @ts-ignore
  15363. this.endListFragments = this.timeRanges = null;
  15364. }
  15365. /**
  15366. * Return a Fragment or Part with an appended range that matches the position and levelType
  15367. * Otherwise, return null
  15368. */;
  15369. _proto.getAppendedFrag = function getAppendedFrag(position, levelType) {
  15370. var activeParts = this.activePartLists[levelType];
  15371. if (activeParts) {
  15372. for (var i = activeParts.length; i--;) {
  15373. var activePart = activeParts[i];
  15374. if (!activePart) {
  15375. break;
  15376. }
  15377. var appendedPTS = activePart.end;
  15378. if (activePart.start <= position && appendedPTS !== null && position <= appendedPTS) {
  15379. return activePart;
  15380. }
  15381. }
  15382. }
  15383. return this.getBufferedFrag(position, levelType);
  15384. }
  15385. /**
  15386. * Return a buffered Fragment that matches the position and levelType.
  15387. * A buffered Fragment is one whose loading, parsing and appending is done (completed or "partial" meaning aborted).
  15388. * If not found any Fragment, return null
  15389. */;
  15390. _proto.getBufferedFrag = function getBufferedFrag(position, levelType) {
  15391. return this.getFragAtPos(position, levelType, true);
  15392. };
  15393. _proto.getFragAtPos = function getFragAtPos(position, levelType, buffered) {
  15394. var fragments = this.fragments;
  15395. var keys = Object.keys(fragments);
  15396. for (var i = keys.length; i--;) {
  15397. var fragmentEntity = fragments[keys[i]];
  15398. if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === levelType && (!buffered || fragmentEntity.buffered)) {
  15399. var frag = fragmentEntity.body;
  15400. if (frag.start <= position && position <= frag.end) {
  15401. return frag;
  15402. }
  15403. }
  15404. }
  15405. return null;
  15406. }
  15407. /**
  15408. * Partial fragments effected by coded frame eviction will be removed
  15409. * The browser will unload parts of the buffer to free up memory for new buffer data
  15410. * 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)
  15411. */;
  15412. _proto.detectEvictedFragments = function detectEvictedFragments(elementaryStream, timeRange, playlistType, appendedPart, removeAppending) {
  15413. var _this = this;
  15414. if (this.timeRanges) {
  15415. this.timeRanges[elementaryStream] = timeRange;
  15416. }
  15417. // Check if any flagged fragments have been unloaded
  15418. // excluding anything newer than appendedPartSn
  15419. var appendedPartSn = (appendedPart == null ? void 0 : appendedPart.fragment.sn) || -1;
  15420. Object.keys(this.fragments).forEach(function (key) {
  15421. var fragmentEntity = _this.fragments[key];
  15422. if (!fragmentEntity) {
  15423. return;
  15424. }
  15425. if (appendedPartSn >= fragmentEntity.body.sn) {
  15426. return;
  15427. }
  15428. if (!fragmentEntity.buffered && (!fragmentEntity.loaded || removeAppending)) {
  15429. if (fragmentEntity.body.type === playlistType) {
  15430. _this.removeFragment(fragmentEntity.body);
  15431. }
  15432. return;
  15433. }
  15434. var esData = fragmentEntity.range[elementaryStream];
  15435. if (!esData) {
  15436. return;
  15437. }
  15438. if (esData.time.length === 0) {
  15439. _this.removeFragment(fragmentEntity.body);
  15440. return;
  15441. }
  15442. esData.time.some(function (time) {
  15443. var isNotBuffered = !_this.isTimeBuffered(time.startPTS, time.endPTS, timeRange);
  15444. if (isNotBuffered) {
  15445. // Unregister partial fragment as it needs to load again to be reused
  15446. _this.removeFragment(fragmentEntity.body);
  15447. }
  15448. return isNotBuffered;
  15449. });
  15450. });
  15451. }
  15452. /**
  15453. * Checks if the fragment passed in is loaded in the buffer properly
  15454. * Partially loaded fragments will be registered as a partial fragment
  15455. */;
  15456. _proto.detectPartialFragments = function detectPartialFragments(data) {
  15457. var _this2 = this;
  15458. var timeRanges = this.timeRanges;
  15459. if (!timeRanges || data.frag.sn === 'initSegment') {
  15460. return;
  15461. }
  15462. var frag = data.frag;
  15463. var fragKey = getFragmentKey(frag);
  15464. var fragmentEntity = this.fragments[fragKey];
  15465. if (!fragmentEntity || fragmentEntity.buffered && frag.gap) {
  15466. return;
  15467. }
  15468. var isFragHint = !frag.relurl;
  15469. Object.keys(timeRanges).forEach(function (elementaryStream) {
  15470. var streamInfo = frag.elementaryStreams[elementaryStream];
  15471. if (!streamInfo) {
  15472. return;
  15473. }
  15474. var timeRange = timeRanges[elementaryStream];
  15475. var partial = isFragHint || streamInfo.partial === true;
  15476. fragmentEntity.range[elementaryStream] = _this2.getBufferedTimes(frag, data.part, partial, timeRange);
  15477. });
  15478. fragmentEntity.loaded = null;
  15479. if (Object.keys(fragmentEntity.range).length) {
  15480. fragmentEntity.buffered = true;
  15481. var endList = fragmentEntity.body.endList = frag.endList || fragmentEntity.body.endList;
  15482. if (endList) {
  15483. this.endListFragments[fragmentEntity.body.type] = fragmentEntity;
  15484. }
  15485. if (!isPartial(fragmentEntity)) {
  15486. // Remove older fragment parts from lookup after frag is tracked as buffered
  15487. this.removeParts(frag.sn - 1, frag.type);
  15488. }
  15489. } else {
  15490. // remove fragment if nothing was appended
  15491. this.removeFragment(fragmentEntity.body);
  15492. }
  15493. };
  15494. _proto.removeParts = function removeParts(snToKeep, levelType) {
  15495. var activeParts = this.activePartLists[levelType];
  15496. if (!activeParts) {
  15497. return;
  15498. }
  15499. this.activePartLists[levelType] = filterParts(activeParts, function (part) {
  15500. return part.fragment.sn >= snToKeep;
  15501. });
  15502. };
  15503. _proto.fragBuffered = function fragBuffered(frag, force) {
  15504. var fragKey = getFragmentKey(frag);
  15505. var fragmentEntity = this.fragments[fragKey];
  15506. if (!fragmentEntity && force) {
  15507. fragmentEntity = this.fragments[fragKey] = {
  15508. body: frag,
  15509. appendedPTS: null,
  15510. loaded: null,
  15511. buffered: false,
  15512. range: Object.create(null)
  15513. };
  15514. if (frag.gap) {
  15515. this.hasGaps = true;
  15516. }
  15517. }
  15518. if (fragmentEntity) {
  15519. fragmentEntity.loaded = null;
  15520. fragmentEntity.buffered = true;
  15521. }
  15522. };
  15523. _proto.getBufferedTimes = function getBufferedTimes(fragment, part, partial, timeRange) {
  15524. var buffered = {
  15525. time: [],
  15526. partial: partial
  15527. };
  15528. var startPTS = fragment.start;
  15529. var endPTS = fragment.end;
  15530. var minEndPTS = fragment.minEndPTS || endPTS;
  15531. var maxStartPTS = fragment.maxStartPTS || startPTS;
  15532. for (var i = 0; i < timeRange.length; i++) {
  15533. var startTime = timeRange.start(i) - this.bufferPadding;
  15534. var endTime = timeRange.end(i) + this.bufferPadding;
  15535. if (maxStartPTS >= startTime && minEndPTS <= endTime) {
  15536. // Fragment is entirely contained in buffer
  15537. // No need to check the other timeRange times since it's completely playable
  15538. buffered.time.push({
  15539. startPTS: Math.max(startPTS, timeRange.start(i)),
  15540. endPTS: Math.min(endPTS, timeRange.end(i))
  15541. });
  15542. break;
  15543. } else if (startPTS < endTime && endPTS > startTime) {
  15544. var start = Math.max(startPTS, timeRange.start(i));
  15545. var end = Math.min(endPTS, timeRange.end(i));
  15546. if (end > start) {
  15547. buffered.partial = true;
  15548. // Check for intersection with buffer
  15549. // Get playable sections of the fragment
  15550. buffered.time.push({
  15551. startPTS: start,
  15552. endPTS: end
  15553. });
  15554. }
  15555. } else if (endPTS <= startTime) {
  15556. // No need to check the rest of the timeRange as it is in order
  15557. break;
  15558. }
  15559. }
  15560. return buffered;
  15561. }
  15562. /**
  15563. * Gets the partial fragment for a certain time
  15564. */;
  15565. _proto.getPartialFragment = function getPartialFragment(time) {
  15566. var bestFragment = null;
  15567. var timePadding;
  15568. var startTime;
  15569. var endTime;
  15570. var bestOverlap = 0;
  15571. var bufferPadding = this.bufferPadding,
  15572. fragments = this.fragments;
  15573. Object.keys(fragments).forEach(function (key) {
  15574. var fragmentEntity = fragments[key];
  15575. if (!fragmentEntity) {
  15576. return;
  15577. }
  15578. if (isPartial(fragmentEntity)) {
  15579. startTime = fragmentEntity.body.start - bufferPadding;
  15580. endTime = fragmentEntity.body.end + bufferPadding;
  15581. if (time >= startTime && time <= endTime) {
  15582. // Use the fragment that has the most padding from start and end time
  15583. timePadding = Math.min(time - startTime, endTime - time);
  15584. if (bestOverlap <= timePadding) {
  15585. bestFragment = fragmentEntity.body;
  15586. bestOverlap = timePadding;
  15587. }
  15588. }
  15589. }
  15590. });
  15591. return bestFragment;
  15592. };
  15593. _proto.isEndListAppended = function isEndListAppended(type) {
  15594. var lastFragmentEntity = this.endListFragments[type];
  15595. return lastFragmentEntity !== undefined && (lastFragmentEntity.buffered || isPartial(lastFragmentEntity));
  15596. };
  15597. _proto.getState = function getState(fragment) {
  15598. var fragKey = getFragmentKey(fragment);
  15599. var fragmentEntity = this.fragments[fragKey];
  15600. if (fragmentEntity) {
  15601. if (!fragmentEntity.buffered) {
  15602. return FragmentState.APPENDING;
  15603. } else if (isPartial(fragmentEntity)) {
  15604. return FragmentState.PARTIAL;
  15605. } else {
  15606. return FragmentState.OK;
  15607. }
  15608. }
  15609. return FragmentState.NOT_LOADED;
  15610. };
  15611. _proto.isTimeBuffered = function isTimeBuffered(startPTS, endPTS, timeRange) {
  15612. var startTime;
  15613. var endTime;
  15614. for (var i = 0; i < timeRange.length; i++) {
  15615. startTime = timeRange.start(i) - this.bufferPadding;
  15616. endTime = timeRange.end(i) + this.bufferPadding;
  15617. if (startPTS >= startTime && endPTS <= endTime) {
  15618. return true;
  15619. }
  15620. if (endPTS <= startTime) {
  15621. // No need to check the rest of the timeRange as it is in order
  15622. return false;
  15623. }
  15624. }
  15625. return false;
  15626. };
  15627. _proto.onManifestLoading = function onManifestLoading() {
  15628. this.removeAllFragments();
  15629. };
  15630. _proto.onFragLoaded = function onFragLoaded(event, data) {
  15631. // don't track initsegment (for which sn is not a number)
  15632. // don't track frags used for bitrateTest, they're irrelevant.
  15633. if (data.frag.sn === 'initSegment' || data.frag.bitrateTest) {
  15634. return;
  15635. }
  15636. var frag = data.frag;
  15637. // Fragment entity `loaded` FragLoadedData is null when loading parts
  15638. var loaded = data.part ? null : data;
  15639. var fragKey = getFragmentKey(frag);
  15640. this.fragments[fragKey] = {
  15641. body: frag,
  15642. appendedPTS: null,
  15643. loaded: loaded,
  15644. buffered: false,
  15645. range: Object.create(null)
  15646. };
  15647. };
  15648. _proto.onBufferAppended = function onBufferAppended(event, data) {
  15649. var frag = data.frag,
  15650. part = data.part,
  15651. timeRanges = data.timeRanges,
  15652. type = data.type;
  15653. if (frag.sn === 'initSegment') {
  15654. return;
  15655. }
  15656. var playlistType = frag.type;
  15657. if (part) {
  15658. var activeParts = this.activePartLists[playlistType];
  15659. if (!activeParts) {
  15660. this.activePartLists[playlistType] = activeParts = [];
  15661. }
  15662. activeParts.push(part);
  15663. }
  15664. // Store the latest timeRanges loaded in the buffer
  15665. this.timeRanges = timeRanges;
  15666. var timeRange = timeRanges[type];
  15667. this.detectEvictedFragments(type, timeRange, playlistType, part);
  15668. };
  15669. _proto.onFragBuffered = function onFragBuffered(event, data) {
  15670. this.detectPartialFragments(data);
  15671. };
  15672. _proto.hasFragment = function hasFragment(fragment) {
  15673. var fragKey = getFragmentKey(fragment);
  15674. return !!this.fragments[fragKey];
  15675. };
  15676. _proto.hasFragments = function hasFragments(type) {
  15677. var fragments = this.fragments;
  15678. var keys = Object.keys(fragments);
  15679. if (!type) {
  15680. return keys.length > 0;
  15681. }
  15682. for (var i = keys.length; i--;) {
  15683. var fragmentEntity = fragments[keys[i]];
  15684. if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === type) {
  15685. return true;
  15686. }
  15687. }
  15688. return false;
  15689. };
  15690. _proto.hasParts = function hasParts(type) {
  15691. var _this$activePartLists;
  15692. return !!((_this$activePartLists = this.activePartLists[type]) != null && _this$activePartLists.length);
  15693. };
  15694. _proto.removeFragmentsInRange = function removeFragmentsInRange(start, end, playlistType, withGapOnly, unbufferedOnly) {
  15695. var _this3 = this;
  15696. if (withGapOnly && !this.hasGaps) {
  15697. return;
  15698. }
  15699. Object.keys(this.fragments).forEach(function (key) {
  15700. var fragmentEntity = _this3.fragments[key];
  15701. if (!fragmentEntity) {
  15702. return;
  15703. }
  15704. var frag = fragmentEntity.body;
  15705. if (frag.type !== playlistType || withGapOnly && !frag.gap) {
  15706. return;
  15707. }
  15708. if (frag.start < end && frag.end > start && (fragmentEntity.buffered || unbufferedOnly)) {
  15709. _this3.removeFragment(frag);
  15710. }
  15711. });
  15712. };
  15713. _proto.removeFragment = function removeFragment(fragment) {
  15714. var fragKey = getFragmentKey(fragment);
  15715. fragment.clearElementaryStreamInfo();
  15716. var activeParts = this.activePartLists[fragment.type];
  15717. if (activeParts) {
  15718. var snToRemove = fragment.sn;
  15719. this.activePartLists[fragment.type] = filterParts(activeParts, function (part) {
  15720. return part.fragment.sn !== snToRemove;
  15721. });
  15722. }
  15723. delete this.fragments[fragKey];
  15724. if (fragment.endList) {
  15725. delete this.endListFragments[fragment.type];
  15726. }
  15727. };
  15728. _proto.removeAllFragments = function removeAllFragments() {
  15729. var _this$hls, _this$hls$latestLevel;
  15730. this.fragments = Object.create(null);
  15731. this.endListFragments = Object.create(null);
  15732. this.activePartLists = Object.create(null);
  15733. this.hasGaps = false;
  15734. var partlist = (_this$hls = this.hls) == null ? void 0 : (_this$hls$latestLevel = _this$hls.latestLevelDetails) == null ? void 0 : _this$hls$latestLevel.partList;
  15735. if (partlist) {
  15736. partlist.forEach(function (part) {
  15737. return part.clearElementaryStreamInfo();
  15738. });
  15739. }
  15740. };
  15741. return FragmentTracker;
  15742. }();
  15743. function isPartial(fragmentEntity) {
  15744. var _fragmentEntity$range, _fragmentEntity$range2, _fragmentEntity$range3;
  15745. return fragmentEntity.buffered && (fragmentEntity.body.gap || ((_fragmentEntity$range = fragmentEntity.range.video) == null ? void 0 : _fragmentEntity$range.partial) || ((_fragmentEntity$range2 = fragmentEntity.range.audio) == null ? void 0 : _fragmentEntity$range2.partial) || ((_fragmentEntity$range3 = fragmentEntity.range.audiovideo) == null ? void 0 : _fragmentEntity$range3.partial));
  15746. }
  15747. function getFragmentKey(fragment) {
  15748. return fragment.type + "_" + fragment.level + "_" + fragment.sn;
  15749. }
  15750. function filterParts(partList, predicate) {
  15751. return partList.filter(function (part) {
  15752. var keep = predicate(part);
  15753. if (!keep) {
  15754. part.clearElementaryStreamInfo();
  15755. }
  15756. return keep;
  15757. });
  15758. }
  15759. var MIN_CHUNK_SIZE = Math.pow(2, 17); // 128kb
  15760. var FragmentLoader = /*#__PURE__*/function () {
  15761. function FragmentLoader(config) {
  15762. this.config = void 0;
  15763. this.loader = null;
  15764. this.partLoadTimeout = -1;
  15765. this.config = config;
  15766. }
  15767. var _proto = FragmentLoader.prototype;
  15768. _proto.destroy = function destroy() {
  15769. if (this.loader) {
  15770. this.loader.destroy();
  15771. this.loader = null;
  15772. }
  15773. };
  15774. _proto.abort = function abort() {
  15775. if (this.loader) {
  15776. // Abort the loader for current fragment. Only one may load at any given time
  15777. this.loader.abort();
  15778. }
  15779. };
  15780. _proto.load = function load(frag, onProgress) {
  15781. var _this = this;
  15782. var url = frag.url;
  15783. if (!url) {
  15784. return Promise.reject(new LoadError({
  15785. type: ErrorTypes.NETWORK_ERROR,
  15786. details: ErrorDetails.FRAG_LOAD_ERROR,
  15787. fatal: false,
  15788. frag: frag,
  15789. error: new Error("Fragment does not have a " + (url ? 'part list' : 'url')),
  15790. networkDetails: null
  15791. }));
  15792. }
  15793. this.abort();
  15794. var config = this.config;
  15795. var FragmentILoader = config.fLoader;
  15796. var DefaultILoader = config.loader;
  15797. return new Promise(function (resolve, reject) {
  15798. if (_this.loader) {
  15799. _this.loader.destroy();
  15800. }
  15801. if (frag.gap) {
  15802. if (frag.tagList.some(function (tags) {
  15803. return tags[0] === 'GAP';
  15804. })) {
  15805. reject(createGapLoadError(frag));
  15806. return;
  15807. } else {
  15808. // Reset temporary treatment as GAP tag
  15809. frag.gap = false;
  15810. }
  15811. }
  15812. var loader = _this.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  15813. var loaderContext = createLoaderContext(frag);
  15814. frag.loader = loader;
  15815. var loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
  15816. var loaderConfig = {
  15817. loadPolicy: loadPolicy,
  15818. timeout: loadPolicy.maxLoadTimeMs,
  15819. maxRetry: 0,
  15820. retryDelay: 0,
  15821. maxRetryDelay: 0,
  15822. highWaterMark: frag.sn === 'initSegment' ? Infinity : MIN_CHUNK_SIZE
  15823. };
  15824. // Assign frag stats to the loader's stats reference
  15825. frag.stats = loader.stats;
  15826. var callbacks = {
  15827. onSuccess: function onSuccess(response, stats, context, networkDetails) {
  15828. _this.resetLoader(frag, loader);
  15829. var payload = response.data;
  15830. if (context.resetIV && frag.decryptdata) {
  15831. frag.decryptdata.iv = new Uint8Array(payload.slice(0, 16));
  15832. payload = payload.slice(16);
  15833. }
  15834. resolve({
  15835. frag: frag,
  15836. part: null,
  15837. payload: payload,
  15838. networkDetails: networkDetails
  15839. });
  15840. },
  15841. onError: function onError(response, context, networkDetails, stats) {
  15842. _this.resetLoader(frag, loader);
  15843. reject(new LoadError({
  15844. type: ErrorTypes.NETWORK_ERROR,
  15845. details: ErrorDetails.FRAG_LOAD_ERROR,
  15846. fatal: false,
  15847. frag: frag,
  15848. response: _objectSpread2({
  15849. url: url,
  15850. data: undefined
  15851. }, response),
  15852. error: new Error("HTTP Error " + response.code + " " + response.text),
  15853. networkDetails: networkDetails,
  15854. stats: stats
  15855. }));
  15856. },
  15857. onAbort: function onAbort(stats, context, networkDetails) {
  15858. _this.resetLoader(frag, loader);
  15859. reject(new LoadError({
  15860. type: ErrorTypes.NETWORK_ERROR,
  15861. details: ErrorDetails.INTERNAL_ABORTED,
  15862. fatal: false,
  15863. frag: frag,
  15864. error: new Error('Aborted'),
  15865. networkDetails: networkDetails,
  15866. stats: stats
  15867. }));
  15868. },
  15869. onTimeout: function onTimeout(stats, context, networkDetails) {
  15870. _this.resetLoader(frag, loader);
  15871. reject(new LoadError({
  15872. type: ErrorTypes.NETWORK_ERROR,
  15873. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  15874. fatal: false,
  15875. frag: frag,
  15876. error: new Error("Timeout after " + loaderConfig.timeout + "ms"),
  15877. networkDetails: networkDetails,
  15878. stats: stats
  15879. }));
  15880. }
  15881. };
  15882. if (onProgress) {
  15883. callbacks.onProgress = function (stats, context, data, networkDetails) {
  15884. return onProgress({
  15885. frag: frag,
  15886. part: null,
  15887. payload: data,
  15888. networkDetails: networkDetails
  15889. });
  15890. };
  15891. }
  15892. loader.load(loaderContext, loaderConfig, callbacks);
  15893. });
  15894. };
  15895. _proto.loadPart = function loadPart(frag, part, onProgress) {
  15896. var _this2 = this;
  15897. this.abort();
  15898. var config = this.config;
  15899. var FragmentILoader = config.fLoader;
  15900. var DefaultILoader = config.loader;
  15901. return new Promise(function (resolve, reject) {
  15902. if (_this2.loader) {
  15903. _this2.loader.destroy();
  15904. }
  15905. if (frag.gap || part.gap) {
  15906. reject(createGapLoadError(frag, part));
  15907. return;
  15908. }
  15909. var loader = _this2.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  15910. var loaderContext = createLoaderContext(frag, part);
  15911. frag.loader = loader;
  15912. // Should we define another load policy for parts?
  15913. var loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
  15914. var loaderConfig = {
  15915. loadPolicy: loadPolicy,
  15916. timeout: loadPolicy.maxLoadTimeMs,
  15917. maxRetry: 0,
  15918. retryDelay: 0,
  15919. maxRetryDelay: 0,
  15920. highWaterMark: MIN_CHUNK_SIZE
  15921. };
  15922. // Assign part stats to the loader's stats reference
  15923. part.stats = loader.stats;
  15924. loader.load(loaderContext, loaderConfig, {
  15925. onSuccess: function onSuccess(response, stats, context, networkDetails) {
  15926. _this2.resetLoader(frag, loader);
  15927. _this2.updateStatsFromPart(frag, part);
  15928. var partLoadedData = {
  15929. frag: frag,
  15930. part: part,
  15931. payload: response.data,
  15932. networkDetails: networkDetails
  15933. };
  15934. onProgress(partLoadedData);
  15935. resolve(partLoadedData);
  15936. },
  15937. onError: function onError(response, context, networkDetails, stats) {
  15938. _this2.resetLoader(frag, loader);
  15939. reject(new LoadError({
  15940. type: ErrorTypes.NETWORK_ERROR,
  15941. details: ErrorDetails.FRAG_LOAD_ERROR,
  15942. fatal: false,
  15943. frag: frag,
  15944. part: part,
  15945. response: _objectSpread2({
  15946. url: loaderContext.url,
  15947. data: undefined
  15948. }, response),
  15949. error: new Error("HTTP Error " + response.code + " " + response.text),
  15950. networkDetails: networkDetails,
  15951. stats: stats
  15952. }));
  15953. },
  15954. onAbort: function onAbort(stats, context, networkDetails) {
  15955. frag.stats.aborted = part.stats.aborted;
  15956. _this2.resetLoader(frag, loader);
  15957. reject(new LoadError({
  15958. type: ErrorTypes.NETWORK_ERROR,
  15959. details: ErrorDetails.INTERNAL_ABORTED,
  15960. fatal: false,
  15961. frag: frag,
  15962. part: part,
  15963. error: new Error('Aborted'),
  15964. networkDetails: networkDetails,
  15965. stats: stats
  15966. }));
  15967. },
  15968. onTimeout: function onTimeout(stats, context, networkDetails) {
  15969. _this2.resetLoader(frag, loader);
  15970. reject(new LoadError({
  15971. type: ErrorTypes.NETWORK_ERROR,
  15972. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  15973. fatal: false,
  15974. frag: frag,
  15975. part: part,
  15976. error: new Error("Timeout after " + loaderConfig.timeout + "ms"),
  15977. networkDetails: networkDetails,
  15978. stats: stats
  15979. }));
  15980. }
  15981. });
  15982. });
  15983. };
  15984. _proto.updateStatsFromPart = function updateStatsFromPart(frag, part) {
  15985. var fragStats = frag.stats;
  15986. var partStats = part.stats;
  15987. var partTotal = partStats.total;
  15988. fragStats.loaded += partStats.loaded;
  15989. if (partTotal) {
  15990. var estTotalParts = Math.round(frag.duration / part.duration);
  15991. var estLoadedParts = Math.min(Math.round(fragStats.loaded / partTotal), estTotalParts);
  15992. var estRemainingParts = estTotalParts - estLoadedParts;
  15993. var estRemainingBytes = estRemainingParts * Math.round(fragStats.loaded / estLoadedParts);
  15994. fragStats.total = fragStats.loaded + estRemainingBytes;
  15995. } else {
  15996. fragStats.total = Math.max(fragStats.loaded, fragStats.total);
  15997. }
  15998. var fragLoading = fragStats.loading;
  15999. var partLoading = partStats.loading;
  16000. if (fragLoading.start) {
  16001. // add to fragment loader latency
  16002. fragLoading.first += partLoading.first - partLoading.start;
  16003. } else {
  16004. fragLoading.start = partLoading.start;
  16005. fragLoading.first = partLoading.first;
  16006. }
  16007. fragLoading.end = partLoading.end;
  16008. };
  16009. _proto.resetLoader = function resetLoader(frag, loader) {
  16010. frag.loader = null;
  16011. if (this.loader === loader) {
  16012. self.clearTimeout(this.partLoadTimeout);
  16013. this.loader = null;
  16014. }
  16015. loader.destroy();
  16016. };
  16017. return FragmentLoader;
  16018. }();
  16019. function createLoaderContext(frag, part) {
  16020. if (part === void 0) {
  16021. part = null;
  16022. }
  16023. var segment = part || frag;
  16024. var loaderContext = {
  16025. frag: frag,
  16026. part: part,
  16027. responseType: 'arraybuffer',
  16028. url: segment.url,
  16029. headers: {},
  16030. rangeStart: 0,
  16031. rangeEnd: 0
  16032. };
  16033. var start = segment.byteRangeStartOffset;
  16034. var end = segment.byteRangeEndOffset;
  16035. if (isFiniteNumber(start) && isFiniteNumber(end)) {
  16036. var _frag$decryptdata;
  16037. var byteRangeStart = start;
  16038. var byteRangeEnd = end;
  16039. if (frag.sn === 'initSegment' && isMethodFullSegmentAesCbc((_frag$decryptdata = frag.decryptdata) == null ? void 0 : _frag$decryptdata.method)) {
  16040. // MAP segment encrypted with method 'AES-128' or 'AES-256' (cbc), when served with HTTP Range,
  16041. // has the unencrypted size specified in the range.
  16042. // Ref: https://tools.ietf.org/html/draft-pantos-hls-rfc8216bis-08#section-6.3.6
  16043. var fragmentLen = end - start;
  16044. if (fragmentLen % 16) {
  16045. byteRangeEnd = end + (16 - fragmentLen % 16);
  16046. }
  16047. if (start !== 0) {
  16048. loaderContext.resetIV = true;
  16049. byteRangeStart = start - 16;
  16050. }
  16051. }
  16052. loaderContext.rangeStart = byteRangeStart;
  16053. loaderContext.rangeEnd = byteRangeEnd;
  16054. }
  16055. return loaderContext;
  16056. }
  16057. function createGapLoadError(frag, part) {
  16058. var error = new Error("GAP " + (frag.gap ? 'tag' : 'attribute') + " found");
  16059. var errorData = {
  16060. type: ErrorTypes.MEDIA_ERROR,
  16061. details: ErrorDetails.FRAG_GAP,
  16062. fatal: false,
  16063. frag: frag,
  16064. error: error,
  16065. networkDetails: null
  16066. };
  16067. if (part) {
  16068. errorData.part = part;
  16069. }
  16070. (part ? part : frag).stats.aborted = true;
  16071. return new LoadError(errorData);
  16072. }
  16073. function isMethodFullSegmentAesCbc(method) {
  16074. return method === 'AES-128' || method === 'AES-256';
  16075. }
  16076. var LoadError = /*#__PURE__*/function (_Error) {
  16077. function LoadError(data) {
  16078. var _this3;
  16079. _this3 = _Error.call(this, data.error.message) || this;
  16080. _this3.data = void 0;
  16081. _this3.data = data;
  16082. return _this3;
  16083. }
  16084. _inheritsLoose(LoadError, _Error);
  16085. return LoadError;
  16086. }(/*#__PURE__*/_wrapNativeSuper(Error));
  16087. /**
  16088. * @ignore
  16089. * Sub-class specialization of EventHandler base class.
  16090. *
  16091. * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,
  16092. * scheduled asynchroneously, avoiding recursive calls in the same tick.
  16093. *
  16094. * The task itself is implemented in `doTick`. It can be requested and called for single execution
  16095. * using the `tick` method.
  16096. *
  16097. * It will be assured that the task execution method (`tick`) only gets called once per main loop "tick",
  16098. * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.
  16099. *
  16100. * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,
  16101. * and cancelled with `clearNextTick`.
  16102. *
  16103. * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).
  16104. *
  16105. * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.
  16106. *
  16107. * Further explanations:
  16108. *
  16109. * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously
  16110. * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.
  16111. *
  16112. * When the task execution (`tick` method) is called in re-entrant way this is detected and
  16113. * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further
  16114. * task processing on the next main loop iteration (also known as "next tick" in the Node/JS runtime lingo).
  16115. */
  16116. var TaskLoop = /*#__PURE__*/function (_Logger) {
  16117. function TaskLoop(label, logger) {
  16118. var _this;
  16119. _this = _Logger.call(this, label, logger) || this;
  16120. _this._boundTick = void 0;
  16121. _this._tickTimer = null;
  16122. _this._tickInterval = null;
  16123. _this._tickCallCount = 0;
  16124. _this._boundTick = _this.tick.bind(_this);
  16125. return _this;
  16126. }
  16127. _inheritsLoose(TaskLoop, _Logger);
  16128. var _proto = TaskLoop.prototype;
  16129. _proto.destroy = function destroy() {
  16130. this.onHandlerDestroying();
  16131. this.onHandlerDestroyed();
  16132. };
  16133. _proto.onHandlerDestroying = function onHandlerDestroying() {
  16134. // clear all timers before unregistering from event bus
  16135. this.clearNextTick();
  16136. this.clearInterval();
  16137. };
  16138. _proto.onHandlerDestroyed = function onHandlerDestroyed() {};
  16139. _proto.hasInterval = function hasInterval() {
  16140. return !!this._tickInterval;
  16141. };
  16142. _proto.hasNextTick = function hasNextTick() {
  16143. return !!this._tickTimer;
  16144. }
  16145. /**
  16146. * @param millis - Interval time (ms)
  16147. * @eturns True when interval has been scheduled, false when already scheduled (no effect)
  16148. */;
  16149. _proto.setInterval = function setInterval(millis) {
  16150. if (!this._tickInterval) {
  16151. this._tickCallCount = 0;
  16152. this._tickInterval = self.setInterval(this._boundTick, millis);
  16153. return true;
  16154. }
  16155. return false;
  16156. }
  16157. /**
  16158. * @returns True when interval was cleared, false when none was set (no effect)
  16159. */;
  16160. _proto.clearInterval = function clearInterval() {
  16161. if (this._tickInterval) {
  16162. self.clearInterval(this._tickInterval);
  16163. this._tickInterval = null;
  16164. return true;
  16165. }
  16166. return false;
  16167. }
  16168. /**
  16169. * @returns True when timeout was cleared, false when none was set (no effect)
  16170. */;
  16171. _proto.clearNextTick = function clearNextTick() {
  16172. if (this._tickTimer) {
  16173. self.clearTimeout(this._tickTimer);
  16174. this._tickTimer = null;
  16175. return true;
  16176. }
  16177. return false;
  16178. }
  16179. /**
  16180. * Will call the subclass doTick implementation in this main loop tick
  16181. * or in the next one (via setTimeout(,0)) in case it has already been called
  16182. * in this tick (in case this is a re-entrant call).
  16183. */;
  16184. _proto.tick = function tick() {
  16185. this._tickCallCount++;
  16186. if (this._tickCallCount === 1) {
  16187. this.doTick();
  16188. // re-entrant call to tick from previous doTick call stack
  16189. // -> schedule a call on the next main loop iteration to process this task processing request
  16190. if (this._tickCallCount > 1) {
  16191. // make sure only one timer exists at any time at max
  16192. this.tickImmediate();
  16193. }
  16194. this._tickCallCount = 0;
  16195. }
  16196. };
  16197. _proto.tickImmediate = function tickImmediate() {
  16198. this.clearNextTick();
  16199. this._tickTimer = self.setTimeout(this._boundTick, 0);
  16200. }
  16201. /**
  16202. * For subclass to implement task logic
  16203. * @abstract
  16204. */;
  16205. _proto.doTick = function doTick() {};
  16206. return TaskLoop;
  16207. }(Logger);
  16208. var ChunkMetadata = function ChunkMetadata(level, sn, id, size, part, partial) {
  16209. if (size === void 0) {
  16210. size = 0;
  16211. }
  16212. if (part === void 0) {
  16213. part = -1;
  16214. }
  16215. if (partial === void 0) {
  16216. partial = false;
  16217. }
  16218. this.level = void 0;
  16219. this.sn = void 0;
  16220. this.part = void 0;
  16221. this.id = void 0;
  16222. this.size = void 0;
  16223. this.partial = void 0;
  16224. this.transmuxing = getNewPerformanceTiming();
  16225. this.buffering = {
  16226. audio: getNewPerformanceTiming(),
  16227. video: getNewPerformanceTiming(),
  16228. audiovideo: getNewPerformanceTiming()
  16229. };
  16230. this.level = level;
  16231. this.sn = sn;
  16232. this.id = id;
  16233. this.size = size;
  16234. this.part = part;
  16235. this.partial = partial;
  16236. };
  16237. function getNewPerformanceTiming() {
  16238. return {
  16239. start: 0,
  16240. executeStart: 0,
  16241. executeEnd: 0,
  16242. end: 0
  16243. };
  16244. }
  16245. function findFirstFragWithCC(fragments, cc) {
  16246. for (var i = 0, len = fragments.length; i < len; i++) {
  16247. var _fragments$i;
  16248. if (((_fragments$i = fragments[i]) == null ? void 0 : _fragments$i.cc) === cc) {
  16249. return fragments[i];
  16250. }
  16251. }
  16252. return null;
  16253. }
  16254. function shouldAlignOnDiscontinuities(refDetails, details) {
  16255. if (refDetails) {
  16256. if (details.startCC < refDetails.endCC && details.endCC > refDetails.startCC) {
  16257. return true;
  16258. }
  16259. }
  16260. return false;
  16261. }
  16262. function adjustFragmentStart(frag, sliding) {
  16263. if (frag) {
  16264. var start = frag.start + sliding;
  16265. frag.start = frag.startPTS = start;
  16266. frag.endPTS = start + frag.duration;
  16267. }
  16268. }
  16269. function adjustSlidingStart(sliding, details) {
  16270. // Update segments
  16271. var fragments = details.fragments;
  16272. for (var i = 0, len = fragments.length; i < len; i++) {
  16273. adjustFragmentStart(fragments[i], sliding);
  16274. }
  16275. // Update LL-HLS parts at the end of the playlist
  16276. if (details.fragmentHint) {
  16277. adjustFragmentStart(details.fragmentHint, sliding);
  16278. }
  16279. details.alignedSliding = true;
  16280. }
  16281. /**
  16282. * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a
  16283. * contiguous stream with the last fragments.
  16284. * The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to
  16285. * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time
  16286. * and an extra download.
  16287. * @param lastLevel
  16288. * @param details
  16289. */
  16290. function alignStream(switchDetails, details) {
  16291. if (!switchDetails) {
  16292. return;
  16293. }
  16294. alignDiscontinuities(details, switchDetails);
  16295. if (!details.alignedSliding && switchDetails) {
  16296. // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.
  16297. // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same
  16298. // discontinuity sequence.
  16299. alignMediaPlaylistByPDT(details, switchDetails);
  16300. }
  16301. if (!details.alignedSliding && switchDetails && !details.skippedSegments) {
  16302. // Try to align on sn so that we pick a better start fragment.
  16303. // Do not perform this on playlists with delta updates as this is only to align levels on switch
  16304. // and adjustSliding only adjusts fragments after skippedSegments.
  16305. adjustSliding(switchDetails, details, false);
  16306. }
  16307. }
  16308. /**
  16309. * Ajust the start of fragments in `details` by the difference in time between fragments of the latest
  16310. * shared discontinuity sequence change.
  16311. * @param lastLevel - The details of the last loaded level
  16312. * @param details - The details of the new level
  16313. */
  16314. function alignDiscontinuities(details, refDetails) {
  16315. if (!shouldAlignOnDiscontinuities(refDetails, details)) {
  16316. return;
  16317. }
  16318. var targetCC = Math.min(refDetails.endCC, details.endCC);
  16319. var refFrag = findFirstFragWithCC(refDetails.fragments, targetCC);
  16320. var frag = findFirstFragWithCC(details.fragments, targetCC);
  16321. if (!refFrag || !frag) {
  16322. return;
  16323. }
  16324. logger.log("Aligning playlist at start of dicontinuity sequence " + targetCC);
  16325. var delta = refFrag.start - frag.start;
  16326. adjustSlidingStart(delta, details);
  16327. }
  16328. /**
  16329. * Ensures appropriate time-alignment between renditions based on PDT.
  16330. * This function assumes the timelines represented in `refDetails` are accurate, including the PDTs
  16331. * for the last discontinuity sequence number shared by both playlists when present,
  16332. * and uses the "wallclock"/PDT timeline as a cross-reference to `details`, adjusting the presentation
  16333. * times/timelines of `details` accordingly.
  16334. * Given the asynchronous nature of fetches and initial loads of live `main` and audio/subtitle tracks,
  16335. * the primary purpose of this function is to ensure the "local timelines" of audio/subtitle tracks
  16336. * are aligned to the main/video timeline, using PDT as the cross-reference/"anchor" that should
  16337. * be consistent across playlists, per the HLS spec.
  16338. * @param details - The details of the rendition you'd like to time-align (e.g. an audio rendition).
  16339. * @param refDetails - The details of the reference rendition with start and PDT times for alignment.
  16340. */
  16341. function alignMediaPlaylistByPDT(details, refDetails) {
  16342. if (!details.hasProgramDateTime || !refDetails.hasProgramDateTime) {
  16343. return;
  16344. }
  16345. var fragments = details.fragments;
  16346. var refFragments = refDetails.fragments;
  16347. if (!fragments.length || !refFragments.length) {
  16348. return;
  16349. }
  16350. // Calculate a delta to apply to all fragments according to the delta in PDT times and start times
  16351. // of a fragment in the reference details, and a fragment in the target details of the same discontinuity.
  16352. // If a fragment of the same discontinuity was not found use the middle fragment of both.
  16353. var refFrag;
  16354. var frag;
  16355. var targetCC = Math.min(refDetails.endCC, details.endCC);
  16356. if (refDetails.startCC < targetCC && details.startCC < targetCC) {
  16357. refFrag = findFirstFragWithCC(refFragments, targetCC);
  16358. frag = findFirstFragWithCC(fragments, targetCC);
  16359. }
  16360. if (!refFrag || !frag) {
  16361. refFrag = refFragments[Math.floor(refFragments.length / 2)];
  16362. frag = findFirstFragWithCC(fragments, refFrag.cc) || fragments[Math.floor(fragments.length / 2)];
  16363. }
  16364. var refPDT = refFrag.programDateTime;
  16365. var targetPDT = frag.programDateTime;
  16366. if (!refPDT || !targetPDT) {
  16367. return;
  16368. }
  16369. var delta = (targetPDT - refPDT) / 1000 - (frag.start - refFrag.start);
  16370. adjustSlidingStart(delta, details);
  16371. }
  16372. /**
  16373. * TimeRanges to string helper
  16374. */
  16375. var TimeRanges = {
  16376. toString: function toString(r) {
  16377. var log = '';
  16378. var len = r.length;
  16379. for (var i = 0; i < len; i++) {
  16380. log += "[" + r.start(i).toFixed(3) + "-" + r.end(i).toFixed(3) + "]";
  16381. }
  16382. return log;
  16383. }
  16384. };
  16385. var State = {
  16386. STOPPED: 'STOPPED',
  16387. IDLE: 'IDLE',
  16388. KEY_LOADING: 'KEY_LOADING',
  16389. FRAG_LOADING: 'FRAG_LOADING',
  16390. FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
  16391. PARSING: 'PARSING',
  16392. PARSED: 'PARSED',
  16393. ENDED: 'ENDED',
  16394. ERROR: 'ERROR',
  16395. WAITING_LEVEL: 'WAITING_LEVEL'
  16396. };
  16397. var BaseStreamController = /*#__PURE__*/function (_TaskLoop) {
  16398. function BaseStreamController(hls, fragmentTracker, keyLoader, logPrefix, playlistType) {
  16399. var _this;
  16400. _this = _TaskLoop.call(this, logPrefix, hls.logger) || this;
  16401. _this.hls = void 0;
  16402. _this.fragPrevious = null;
  16403. _this.fragCurrent = null;
  16404. _this.fragmentTracker = void 0;
  16405. _this.transmuxer = null;
  16406. _this._state = State.STOPPED;
  16407. _this.playlistType = void 0;
  16408. _this.media = null;
  16409. _this.mediaBuffer = null;
  16410. _this.config = void 0;
  16411. _this.bitrateTest = false;
  16412. _this.lastCurrentTime = 0;
  16413. _this.nextLoadPosition = 0;
  16414. _this.startPosition = 0;
  16415. _this.startTimeOffset = null;
  16416. _this.retryDate = 0;
  16417. _this.levels = null;
  16418. _this.fragmentLoader = void 0;
  16419. _this.keyLoader = void 0;
  16420. _this.levelLastLoaded = null;
  16421. _this.startFragRequested = false;
  16422. _this.decrypter = void 0;
  16423. _this.initPTS = [];
  16424. _this.buffering = true;
  16425. _this.loadingParts = false;
  16426. _this.loopSn = void 0;
  16427. _this.onMediaSeeking = function () {
  16428. var _this2 = _this,
  16429. config = _this2.config,
  16430. fragCurrent = _this2.fragCurrent,
  16431. media = _this2.media,
  16432. mediaBuffer = _this2.mediaBuffer,
  16433. state = _this2.state;
  16434. var currentTime = media ? media.currentTime : 0;
  16435. var bufferInfo = BufferHelper.bufferInfo(mediaBuffer ? mediaBuffer : media, currentTime, config.maxBufferHole);
  16436. var noFowardBuffer = !bufferInfo.len;
  16437. _this.log("Media seeking to " + (isFiniteNumber(currentTime) ? currentTime.toFixed(3) : currentTime) + ", state: " + state + ", " + (noFowardBuffer ? 'out of' : 'in') + " buffer");
  16438. if (_this.state === State.ENDED) {
  16439. _this.resetLoadingState();
  16440. } else if (fragCurrent) {
  16441. // Seeking while frag load is in progress
  16442. var tolerance = config.maxFragLookUpTolerance;
  16443. var fragStartOffset = fragCurrent.start - tolerance;
  16444. var fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;
  16445. // if seeking out of buffered range or into new one
  16446. if (noFowardBuffer || fragEndOffset < bufferInfo.start || fragStartOffset > bufferInfo.end) {
  16447. var pastFragment = currentTime > fragEndOffset;
  16448. // if the seek position is outside the current fragment range
  16449. if (currentTime < fragStartOffset || pastFragment) {
  16450. if (pastFragment && fragCurrent.loader) {
  16451. _this.log("Cancelling fragment load for seek (sn: " + fragCurrent.sn + ")");
  16452. fragCurrent.abortRequests();
  16453. _this.resetLoadingState();
  16454. }
  16455. _this.fragPrevious = null;
  16456. }
  16457. }
  16458. }
  16459. if (media) {
  16460. // Remove gap fragments
  16461. _this.fragmentTracker.removeFragmentsInRange(currentTime, Infinity, _this.playlistType, true);
  16462. // Don't set lastCurrentTime with backward seeks (allows for frag selection with strict tolerances)
  16463. var lastCurrentTime = _this.lastCurrentTime;
  16464. if (currentTime > lastCurrentTime) {
  16465. _this.lastCurrentTime = currentTime;
  16466. }
  16467. if (!_this.loadingParts) {
  16468. var bufferEnd = Math.max(bufferInfo.end, currentTime);
  16469. var shouldLoadParts = _this.shouldLoadParts(_this.getLevelDetails(), bufferEnd);
  16470. if (shouldLoadParts) {
  16471. _this.log("LL-Part loading ON after seeking to " + currentTime.toFixed(2) + " with buffer @" + bufferEnd.toFixed(2));
  16472. _this.loadingParts = shouldLoadParts;
  16473. }
  16474. }
  16475. }
  16476. // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
  16477. if (!_this.hls.hasEnoughToStart) {
  16478. _this.log("Setting " + (noFowardBuffer ? 'startPosition' : 'nextLoadPosition') + " to " + currentTime + " for seek without enough to start");
  16479. _this.nextLoadPosition = currentTime;
  16480. if (noFowardBuffer) {
  16481. _this.startPosition = currentTime;
  16482. }
  16483. }
  16484. // Async tick to speed up processing
  16485. _this.tickImmediate();
  16486. };
  16487. _this.onMediaEnded = function () {
  16488. // reset startPosition and lastCurrentTime to restart playback @ stream beginning
  16489. _this.log("setting startPosition to 0 because media ended");
  16490. _this.startPosition = _this.lastCurrentTime = 0;
  16491. };
  16492. _this.playlistType = playlistType;
  16493. _this.hls = hls;
  16494. _this.fragmentLoader = new FragmentLoader(hls.config);
  16495. _this.keyLoader = keyLoader;
  16496. _this.fragmentTracker = fragmentTracker;
  16497. _this.config = hls.config;
  16498. _this.decrypter = new Decrypter(hls.config);
  16499. return _this;
  16500. }
  16501. _inheritsLoose(BaseStreamController, _TaskLoop);
  16502. var _proto = BaseStreamController.prototype;
  16503. _proto.registerListeners = function registerListeners() {
  16504. var hls = this.hls;
  16505. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  16506. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  16507. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  16508. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  16509. hls.on(Events.ERROR, this.onError, this);
  16510. };
  16511. _proto.unregisterListeners = function unregisterListeners() {
  16512. var hls = this.hls;
  16513. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  16514. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  16515. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  16516. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  16517. hls.off(Events.ERROR, this.onError, this);
  16518. };
  16519. _proto.doTick = function doTick() {
  16520. this.onTickEnd();
  16521. };
  16522. _proto.onTickEnd = function onTickEnd() {};
  16523. _proto.startLoad = function startLoad(startPosition) {};
  16524. _proto.stopLoad = function stopLoad() {
  16525. if (this.state === State.STOPPED) {
  16526. return;
  16527. }
  16528. this.fragmentLoader.abort();
  16529. this.keyLoader.abort(this.playlistType);
  16530. var frag = this.fragCurrent;
  16531. if (frag != null && frag.loader) {
  16532. frag.abortRequests();
  16533. this.fragmentTracker.removeFragment(frag);
  16534. }
  16535. this.resetTransmuxer();
  16536. this.fragCurrent = null;
  16537. this.fragPrevious = null;
  16538. this.clearInterval();
  16539. this.clearNextTick();
  16540. this.state = State.STOPPED;
  16541. };
  16542. _proto.pauseBuffering = function pauseBuffering() {
  16543. this.buffering = false;
  16544. };
  16545. _proto.resumeBuffering = function resumeBuffering() {
  16546. this.buffering = true;
  16547. };
  16548. _proto._streamEnded = function _streamEnded(bufferInfo, levelDetails) {
  16549. // Stream is never "ended" when playlist is live or media is detached
  16550. if (levelDetails.live || !this.media) {
  16551. return false;
  16552. }
  16553. // Stream is not "ended" when nothing is buffered past the start
  16554. var bufferEnd = bufferInfo.end || 0;
  16555. var timelineStart = this.config.timelineOffset || 0;
  16556. if (bufferEnd <= timelineStart) {
  16557. return false;
  16558. }
  16559. // Stream is not "ended" when there is a second buffered range starting before the end of the playlist
  16560. var bufferedRanges = bufferInfo.buffered;
  16561. if (this.config.maxBufferHole && bufferedRanges && bufferedRanges.length > 1) {
  16562. // make sure bufferInfo accounts for any gaps
  16563. bufferInfo = BufferHelper.bufferedInfo(bufferedRanges, bufferInfo.start, 0);
  16564. }
  16565. var nextStart = bufferInfo.nextStart;
  16566. var hasSecondBufferedRange = nextStart && nextStart > timelineStart && nextStart < levelDetails.edge;
  16567. if (hasSecondBufferedRange) {
  16568. return false;
  16569. }
  16570. // Playhead is in unbuffered region. Marking EoS now could result in Safari failing to dispatch "ended" event following seek on start.
  16571. if (this.media.currentTime < bufferInfo.start) {
  16572. return false;
  16573. }
  16574. var partList = levelDetails.partList;
  16575. // Since the last part isn't guaranteed to correspond to the last playlist segment for Low-Latency HLS,
  16576. // check instead if the last part is buffered.
  16577. if (partList != null && partList.length) {
  16578. var lastPart = partList[partList.length - 1];
  16579. // Checking the midpoint of the part for potential margin of error and related issues.
  16580. // NOTE: Technically I believe parts could yield content that is < the computed duration (including potential a duration of 0)
  16581. // and still be spec-compliant, so there may still be edge cases here. Likewise, there could be issues in end of stream
  16582. // part mismatches for independent audio and video playlists/segments.
  16583. var lastPartBuffered = BufferHelper.isBuffered(this.media, lastPart.start + lastPart.duration / 2);
  16584. return lastPartBuffered;
  16585. }
  16586. var playlistType = levelDetails.fragments[levelDetails.fragments.length - 1].type;
  16587. return this.fragmentTracker.isEndListAppended(playlistType);
  16588. };
  16589. _proto.getLevelDetails = function getLevelDetails() {
  16590. if (this.levels && this.levelLastLoaded !== null) {
  16591. var _this$levelLastLoaded;
  16592. return (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details;
  16593. }
  16594. };
  16595. _proto.onMediaAttached = function onMediaAttached(event, data) {
  16596. var media = this.media = this.mediaBuffer = data.media;
  16597. media.removeEventListener('seeking', this.onMediaSeeking);
  16598. media.removeEventListener('ended', this.onMediaEnded);
  16599. media.addEventListener('seeking', this.onMediaSeeking);
  16600. media.addEventListener('ended', this.onMediaEnded);
  16601. var config = this.config;
  16602. if (this.levels && config.autoStartLoad && this.state === State.STOPPED) {
  16603. this.startLoad(config.startPosition);
  16604. }
  16605. };
  16606. _proto.onMediaDetaching = function onMediaDetaching(event, data) {
  16607. var transferringMedia = !!data.transferMedia;
  16608. var media = this.media;
  16609. if (media === null) {
  16610. return;
  16611. }
  16612. if (media.ended) {
  16613. this.log('MSE detaching and video ended, reset startPosition');
  16614. this.startPosition = this.lastCurrentTime = 0;
  16615. }
  16616. // remove video listeners
  16617. media.removeEventListener('seeking', this.onMediaSeeking);
  16618. media.removeEventListener('ended', this.onMediaEnded);
  16619. if (this.keyLoader && !transferringMedia) {
  16620. this.keyLoader.detach();
  16621. }
  16622. this.media = this.mediaBuffer = null;
  16623. this.loopSn = undefined;
  16624. if (transferringMedia) {
  16625. this.resetLoadingState();
  16626. this.resetTransmuxer();
  16627. return;
  16628. }
  16629. this.loadingParts = false;
  16630. this.fragmentTracker.removeAllFragments();
  16631. this.stopLoad();
  16632. };
  16633. _proto.onManifestLoading = function onManifestLoading() {
  16634. this.initPTS = [];
  16635. this.levels = this.levelLastLoaded = this.fragCurrent = null;
  16636. this.lastCurrentTime = this.startPosition = 0;
  16637. this.startFragRequested = false;
  16638. };
  16639. _proto.onError = function onError(event, data) {};
  16640. _proto.onManifestLoaded = function onManifestLoaded(event, data) {
  16641. this.startTimeOffset = data.startTimeOffset;
  16642. };
  16643. _proto.onHandlerDestroying = function onHandlerDestroying() {
  16644. this.stopLoad();
  16645. if (this.transmuxer) {
  16646. this.transmuxer.destroy();
  16647. this.transmuxer = null;
  16648. }
  16649. _TaskLoop.prototype.onHandlerDestroying.call(this);
  16650. // @ts-ignore
  16651. this.hls = this.onMediaSeeking = this.onMediaEnded = null;
  16652. };
  16653. _proto.onHandlerDestroyed = function onHandlerDestroyed() {
  16654. this.state = State.STOPPED;
  16655. if (this.fragmentLoader) {
  16656. this.fragmentLoader.destroy();
  16657. }
  16658. if (this.keyLoader) {
  16659. this.keyLoader.destroy();
  16660. }
  16661. if (this.decrypter) {
  16662. this.decrypter.destroy();
  16663. }
  16664. this.hls = this.log = this.warn = this.decrypter = this.keyLoader = this.fragmentLoader = this.fragmentTracker = null;
  16665. _TaskLoop.prototype.onHandlerDestroyed.call(this);
  16666. };
  16667. _proto.loadFragment = function loadFragment(frag, level, targetBufferTime) {
  16668. this.startFragRequested = true;
  16669. this._loadFragForPlayback(frag, level, targetBufferTime);
  16670. };
  16671. _proto._loadFragForPlayback = function _loadFragForPlayback(fragment, level, targetBufferTime) {
  16672. var _this3 = this;
  16673. var progressCallback = function progressCallback(data) {
  16674. var frag = data.frag;
  16675. if (_this3.fragContextChanged(frag)) {
  16676. _this3.warn(frag.type + " sn: " + frag.sn + (data.part ? ' part: ' + data.part.index : '') + " of " + _this3.fragInfo(frag, false, data.part) + ") was dropped during download.");
  16677. _this3.fragmentTracker.removeFragment(frag);
  16678. return;
  16679. }
  16680. frag.stats.chunkCount++;
  16681. _this3._handleFragmentLoadProgress(data);
  16682. };
  16683. this._doFragLoad(fragment, level, targetBufferTime, progressCallback).then(function (data) {
  16684. if (!data) {
  16685. // if we're here we probably needed to backtrack or are waiting for more parts
  16686. return;
  16687. }
  16688. var state = _this3.state;
  16689. var frag = data.frag;
  16690. if (_this3.fragContextChanged(frag)) {
  16691. if (state === State.FRAG_LOADING || !_this3.fragCurrent && state === State.PARSING) {
  16692. _this3.fragmentTracker.removeFragment(frag);
  16693. _this3.state = State.IDLE;
  16694. }
  16695. return;
  16696. }
  16697. if ('payload' in data) {
  16698. _this3.log("Loaded " + frag.type + " sn: " + frag.sn + " of " + _this3.playlistLabel() + " " + frag.level);
  16699. _this3.hls.trigger(Events.FRAG_LOADED, data);
  16700. }
  16701. // Pass through the whole payload; controllers not implementing progressive loading receive data from this callback
  16702. _this3._handleFragmentLoadComplete(data);
  16703. }).catch(function (reason) {
  16704. if (_this3.state === State.STOPPED || _this3.state === State.ERROR) {
  16705. return;
  16706. }
  16707. _this3.warn("Frag error: " + ((reason == null ? void 0 : reason.message) || reason));
  16708. _this3.resetFragmentLoading(fragment);
  16709. });
  16710. };
  16711. _proto.clearTrackerIfNeeded = function clearTrackerIfNeeded(frag) {
  16712. var _this$mediaBuffer;
  16713. var fragmentTracker = this.fragmentTracker;
  16714. var fragState = fragmentTracker.getState(frag);
  16715. if (fragState === FragmentState.APPENDING) {
  16716. // Lower the max buffer length and try again
  16717. var playlistType = frag.type;
  16718. var bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  16719. var minForwardBufferLength = Math.max(frag.duration, bufferedInfo ? bufferedInfo.len : this.config.maxBufferLength);
  16720. // If backtracking, always remove from the tracker without reducing max buffer length
  16721. var backtrackFragment = this.backtrackFragment;
  16722. var backtracked = backtrackFragment ? frag.sn - backtrackFragment.sn : 0;
  16723. if (backtracked === 1 || this.reduceMaxBufferLength(minForwardBufferLength, frag.duration)) {
  16724. fragmentTracker.removeFragment(frag);
  16725. }
  16726. } else if (((_this$mediaBuffer = this.mediaBuffer) == null ? void 0 : _this$mediaBuffer.buffered.length) === 0) {
  16727. // Stop gap for bad tracker / buffer flush behavior
  16728. fragmentTracker.removeAllFragments();
  16729. } else if (fragmentTracker.hasParts(frag.type)) {
  16730. // In low latency mode, remove fragments for which only some parts were buffered
  16731. fragmentTracker.detectPartialFragments({
  16732. frag: frag,
  16733. part: null,
  16734. stats: frag.stats,
  16735. id: frag.type
  16736. });
  16737. if (fragmentTracker.getState(frag) === FragmentState.PARTIAL) {
  16738. fragmentTracker.removeFragment(frag);
  16739. }
  16740. }
  16741. };
  16742. _proto.checkLiveUpdate = function checkLiveUpdate(details) {
  16743. if (details.updated && !details.live) {
  16744. // Live stream ended, update fragment tracker
  16745. var lastFragment = details.fragments[details.fragments.length - 1];
  16746. this.fragmentTracker.detectPartialFragments({
  16747. frag: lastFragment,
  16748. part: null,
  16749. stats: lastFragment.stats,
  16750. id: lastFragment.type
  16751. });
  16752. }
  16753. if (!details.fragments[0]) {
  16754. details.deltaUpdateFailed = true;
  16755. }
  16756. };
  16757. _proto.waitForLive = function waitForLive(levelInfo) {
  16758. var details = levelInfo.details;
  16759. return (details == null ? void 0 : details.live) && details.type !== 'EVENT' && (this.levelLastLoaded !== levelInfo || details.expired);
  16760. };
  16761. _proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset, type) {
  16762. if (type === void 0) {
  16763. type = null;
  16764. }
  16765. if (!(startOffset - endOffset)) {
  16766. return;
  16767. }
  16768. // When alternate audio is playing, the audio-stream-controller is responsible for the audio buffer. Otherwise,
  16769. // passing a null type flushes both buffers
  16770. var flushScope = {
  16771. startOffset: startOffset,
  16772. endOffset: endOffset,
  16773. type: type
  16774. };
  16775. this.hls.trigger(Events.BUFFER_FLUSHING, flushScope);
  16776. };
  16777. _proto._loadInitSegment = function _loadInitSegment(fragment, level) {
  16778. var _this4 = this;
  16779. this._doFragLoad(fragment, level).then(function (data) {
  16780. var frag = data == null ? void 0 : data.frag;
  16781. if (!frag || _this4.fragContextChanged(frag) || !_this4.levels) {
  16782. throw new Error('init load aborted');
  16783. }
  16784. return data;
  16785. }).then(function (data) {
  16786. var hls = _this4.hls;
  16787. var frag = data.frag,
  16788. payload = data.payload;
  16789. var decryptData = frag.decryptdata;
  16790. // check to see if the payload needs to be decrypted
  16791. if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && isFullSegmentEncryption(decryptData.method)) {
  16792. var startTime = self.performance.now();
  16793. // decrypt init segment data
  16794. return _this4.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer, getAesModeFromFullSegmentMethod(decryptData.method)).catch(function (err) {
  16795. hls.trigger(Events.ERROR, {
  16796. type: ErrorTypes.MEDIA_ERROR,
  16797. details: ErrorDetails.FRAG_DECRYPT_ERROR,
  16798. fatal: false,
  16799. error: err,
  16800. reason: err.message,
  16801. frag: frag
  16802. });
  16803. throw err;
  16804. }).then(function (decryptedData) {
  16805. var endTime = self.performance.now();
  16806. hls.trigger(Events.FRAG_DECRYPTED, {
  16807. frag: frag,
  16808. payload: decryptedData,
  16809. stats: {
  16810. tstart: startTime,
  16811. tdecrypt: endTime
  16812. }
  16813. });
  16814. data.payload = decryptedData;
  16815. return _this4.completeInitSegmentLoad(data);
  16816. });
  16817. }
  16818. return _this4.completeInitSegmentLoad(data);
  16819. }).catch(function (reason) {
  16820. if (_this4.state === State.STOPPED || _this4.state === State.ERROR) {
  16821. return;
  16822. }
  16823. _this4.warn(reason);
  16824. _this4.resetFragmentLoading(fragment);
  16825. });
  16826. };
  16827. _proto.completeInitSegmentLoad = function completeInitSegmentLoad(data) {
  16828. var levels = this.levels;
  16829. if (!levels) {
  16830. throw new Error('init load aborted, missing levels');
  16831. }
  16832. var stats = data.frag.stats;
  16833. if (this.state !== State.STOPPED) {
  16834. this.state = State.IDLE;
  16835. }
  16836. data.frag.data = new Uint8Array(data.payload);
  16837. stats.parsing.start = stats.buffering.start = self.performance.now();
  16838. stats.parsing.end = stats.buffering.end = self.performance.now();
  16839. this.tick();
  16840. };
  16841. _proto.fragContextChanged = function fragContextChanged(frag) {
  16842. var fragCurrent = this.fragCurrent;
  16843. return !frag || !fragCurrent || frag.sn !== fragCurrent.sn || frag.level !== fragCurrent.level;
  16844. };
  16845. _proto.fragBufferedComplete = function fragBufferedComplete(frag, part) {
  16846. var media = this.mediaBuffer ? this.mediaBuffer : this.media;
  16847. this.log("Buffered " + frag.type + " sn: " + frag.sn + (part ? ' part: ' + part.index : '') + " of " + this.fragInfo(frag, false, part) + " > buffer:" + (media ? TimeRanges.toString(BufferHelper.getBuffered(media)) : '(detached)') + ")");
  16848. if (isMediaFragment(frag)) {
  16849. var _this$levels;
  16850. if (frag.type !== PlaylistLevelType.SUBTITLE) {
  16851. var el = frag.elementaryStreams;
  16852. if (!Object.keys(el).some(function (type) {
  16853. return !!el[type];
  16854. })) {
  16855. // empty segment
  16856. this.state = State.IDLE;
  16857. return;
  16858. }
  16859. }
  16860. var level = (_this$levels = this.levels) == null ? void 0 : _this$levels[frag.level];
  16861. if (level != null && level.fragmentError) {
  16862. this.log("Resetting level fragment error count of " + level.fragmentError + " on frag buffered");
  16863. level.fragmentError = 0;
  16864. }
  16865. }
  16866. this.state = State.IDLE;
  16867. };
  16868. _proto._handleFragmentLoadComplete = function _handleFragmentLoadComplete(fragLoadedEndData) {
  16869. var transmuxer = this.transmuxer;
  16870. if (!transmuxer) {
  16871. return;
  16872. }
  16873. var frag = fragLoadedEndData.frag,
  16874. part = fragLoadedEndData.part,
  16875. partsLoaded = fragLoadedEndData.partsLoaded;
  16876. // If we did not load parts, or loaded all parts, we have complete (not partial) fragment data
  16877. var complete = !partsLoaded || partsLoaded.length === 0 || partsLoaded.some(function (fragLoaded) {
  16878. return !fragLoaded;
  16879. });
  16880. var chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount + 1, 0, part ? part.index : -1, !complete);
  16881. transmuxer.flush(chunkMeta);
  16882. };
  16883. _proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(frag) {};
  16884. _proto._doFragLoad = function _doFragLoad(frag, level, targetBufferTime, progressCallback) {
  16885. var _frag$decryptdata,
  16886. _this5 = this;
  16887. if (targetBufferTime === void 0) {
  16888. targetBufferTime = null;
  16889. }
  16890. this.fragCurrent = frag;
  16891. var details = level == null ? void 0 : level.details;
  16892. if (!this.levels || !details) {
  16893. throw new Error("frag load aborted, missing level" + (details ? '' : ' detail') + "s");
  16894. }
  16895. var keyLoadingPromise = null;
  16896. if (frag.encrypted && !((_frag$decryptdata = frag.decryptdata) != null && _frag$decryptdata.key)) {
  16897. this.log("Loading key for " + frag.sn + " of [" + details.startSN + "-" + details.endSN + "], " + this.playlistLabel() + " " + frag.level);
  16898. this.state = State.KEY_LOADING;
  16899. this.fragCurrent = frag;
  16900. keyLoadingPromise = this.keyLoader.load(frag).then(function (keyLoadedData) {
  16901. if (!_this5.fragContextChanged(keyLoadedData.frag)) {
  16902. _this5.hls.trigger(Events.KEY_LOADED, keyLoadedData);
  16903. if (_this5.state === State.KEY_LOADING) {
  16904. _this5.state = State.IDLE;
  16905. }
  16906. return keyLoadedData;
  16907. }
  16908. });
  16909. this.hls.trigger(Events.KEY_LOADING, {
  16910. frag: frag
  16911. });
  16912. if (this.fragCurrent === null) {
  16913. keyLoadingPromise = Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING"));
  16914. }
  16915. } else if (!frag.encrypted) {
  16916. keyLoadingPromise = this.keyLoader.loadClear(frag, details.encryptedFragments, this.startFragRequested);
  16917. if (keyLoadingPromise) {
  16918. this.log("[eme] blocking frag load until media-keys acquired");
  16919. }
  16920. }
  16921. var fragPrevious = this.fragPrevious;
  16922. if (isMediaFragment(frag) && (!fragPrevious || frag.sn !== fragPrevious.sn)) {
  16923. var shouldLoadParts = this.shouldLoadParts(level.details, frag.end);
  16924. if (shouldLoadParts !== this.loadingParts) {
  16925. this.log("LL-Part loading " + (shouldLoadParts ? 'ON' : 'OFF') + " loading sn " + (fragPrevious == null ? void 0 : fragPrevious.sn) + "->" + frag.sn);
  16926. this.loadingParts = shouldLoadParts;
  16927. }
  16928. }
  16929. targetBufferTime = Math.max(frag.start, targetBufferTime || 0);
  16930. if (this.loadingParts && isMediaFragment(frag)) {
  16931. var partList = details.partList;
  16932. if (partList && progressCallback) {
  16933. if (targetBufferTime > frag.end && details.fragmentHint) {
  16934. frag = details.fragmentHint;
  16935. }
  16936. var partIndex = this.getNextPart(partList, frag, targetBufferTime);
  16937. if (partIndex > -1) {
  16938. var part = partList[partIndex];
  16939. frag = this.fragCurrent = part.fragment;
  16940. this.log("Loading " + frag.type + " sn: " + frag.sn + " part: " + part.index + " (" + partIndex + "/" + (partList.length - 1) + ") of " + this.fragInfo(frag, false, part) + ") cc: " + frag.cc + " [" + details.startSN + "-" + details.endSN + "], target: " + parseFloat(targetBufferTime.toFixed(3)));
  16941. this.nextLoadPosition = part.start + part.duration;
  16942. this.state = State.FRAG_LOADING;
  16943. var _result;
  16944. if (keyLoadingPromise) {
  16945. _result = keyLoadingPromise.then(function (keyLoadedData) {
  16946. if (!keyLoadedData || _this5.fragContextChanged(keyLoadedData.frag)) {
  16947. return null;
  16948. }
  16949. return _this5.doFragPartsLoad(frag, part, level, progressCallback);
  16950. }).catch(function (error) {
  16951. return _this5.handleFragLoadError(error);
  16952. });
  16953. } else {
  16954. _result = this.doFragPartsLoad(frag, part, level, progressCallback).catch(function (error) {
  16955. return _this5.handleFragLoadError(error);
  16956. });
  16957. }
  16958. this.hls.trigger(Events.FRAG_LOADING, {
  16959. frag: frag,
  16960. part: part,
  16961. targetBufferTime: targetBufferTime
  16962. });
  16963. if (this.fragCurrent === null) {
  16964. return Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts"));
  16965. }
  16966. return _result;
  16967. } else if (!frag.url || this.loadedEndOfParts(partList, targetBufferTime)) {
  16968. // Fragment hint has no parts
  16969. return Promise.resolve(null);
  16970. }
  16971. }
  16972. }
  16973. if (isMediaFragment(frag) && this.loadingParts) {
  16974. this.log("LL-Part loading OFF after next part miss @" + targetBufferTime.toFixed(2));
  16975. this.loadingParts = false;
  16976. } else if (!frag.url) {
  16977. // Selected fragment hint for part but not loading parts
  16978. return Promise.resolve(null);
  16979. }
  16980. this.log("Loading " + frag.type + " sn: " + frag.sn + " of " + this.fragInfo(frag, false) + ") cc: " + frag.cc + " " + (details ? '[' + details.startSN + '-' + details.endSN + ']' : '') + ", target: " + parseFloat(targetBufferTime.toFixed(3)));
  16981. // Don't update nextLoadPosition for fragments which are not buffered
  16982. if (isFiniteNumber(frag.sn) && !this.bitrateTest) {
  16983. this.nextLoadPosition = frag.start + frag.duration;
  16984. }
  16985. this.state = State.FRAG_LOADING;
  16986. // Load key before streaming fragment data
  16987. var dataOnProgress = this.config.progressive;
  16988. var result;
  16989. if (dataOnProgress && keyLoadingPromise) {
  16990. result = keyLoadingPromise.then(function (keyLoadedData) {
  16991. if (!keyLoadedData || _this5.fragContextChanged(keyLoadedData == null ? void 0 : keyLoadedData.frag)) {
  16992. return null;
  16993. }
  16994. return _this5.fragmentLoader.load(frag, progressCallback);
  16995. }).catch(function (error) {
  16996. return _this5.handleFragLoadError(error);
  16997. });
  16998. } else {
  16999. // load unencrypted fragment data with progress event,
  17000. // or handle fragment result after key and fragment are finished loading
  17001. result = Promise.all([this.fragmentLoader.load(frag, dataOnProgress ? progressCallback : undefined), keyLoadingPromise]).then(function (_ref) {
  17002. var fragLoadedData = _ref[0];
  17003. if (!dataOnProgress && fragLoadedData && progressCallback) {
  17004. progressCallback(fragLoadedData);
  17005. }
  17006. return fragLoadedData;
  17007. }).catch(function (error) {
  17008. return _this5.handleFragLoadError(error);
  17009. });
  17010. }
  17011. this.hls.trigger(Events.FRAG_LOADING, {
  17012. frag: frag,
  17013. targetBufferTime: targetBufferTime
  17014. });
  17015. if (this.fragCurrent === null) {
  17016. return Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING"));
  17017. }
  17018. return result;
  17019. };
  17020. _proto.doFragPartsLoad = function doFragPartsLoad(frag, fromPart, level, progressCallback) {
  17021. var _this6 = this;
  17022. return new Promise(function (resolve, reject) {
  17023. var _level$details;
  17024. var partsLoaded = [];
  17025. var initialPartList = (_level$details = level.details) == null ? void 0 : _level$details.partList;
  17026. var _loadPart = function loadPart(part) {
  17027. _this6.fragmentLoader.loadPart(frag, part, progressCallback).then(function (partLoadedData) {
  17028. partsLoaded[part.index] = partLoadedData;
  17029. var loadedPart = partLoadedData.part;
  17030. _this6.hls.trigger(Events.FRAG_LOADED, partLoadedData);
  17031. var nextPart = getPartWith(level.details, frag.sn, part.index + 1) || findPart(initialPartList, frag.sn, part.index + 1);
  17032. if (nextPart) {
  17033. _loadPart(nextPart);
  17034. } else {
  17035. return resolve({
  17036. frag: frag,
  17037. part: loadedPart,
  17038. partsLoaded: partsLoaded
  17039. });
  17040. }
  17041. }).catch(reject);
  17042. };
  17043. _loadPart(fromPart);
  17044. });
  17045. };
  17046. _proto.handleFragLoadError = function handleFragLoadError(error) {
  17047. if ('data' in error) {
  17048. var data = error.data;
  17049. if (error.data && data.details === ErrorDetails.INTERNAL_ABORTED) {
  17050. this.handleFragLoadAborted(data.frag, data.part);
  17051. } else {
  17052. this.hls.trigger(Events.ERROR, data);
  17053. }
  17054. } else {
  17055. this.hls.trigger(Events.ERROR, {
  17056. type: ErrorTypes.OTHER_ERROR,
  17057. details: ErrorDetails.INTERNAL_EXCEPTION,
  17058. err: error,
  17059. error: error,
  17060. fatal: true
  17061. });
  17062. }
  17063. return null;
  17064. };
  17065. _proto._handleTransmuxerFlush = function _handleTransmuxerFlush(chunkMeta) {
  17066. var context = this.getCurrentContext(chunkMeta);
  17067. if (!context || this.state !== State.PARSING) {
  17068. if (!this.fragCurrent && this.state !== State.STOPPED && this.state !== State.ERROR) {
  17069. this.state = State.IDLE;
  17070. }
  17071. return;
  17072. }
  17073. var frag = context.frag,
  17074. part = context.part,
  17075. level = context.level;
  17076. var now = self.performance.now();
  17077. frag.stats.parsing.end = now;
  17078. if (part) {
  17079. part.stats.parsing.end = now;
  17080. }
  17081. // See if part loading should be disabled/enabled based on buffer and playback position.
  17082. var levelDetails = this.getLevelDetails();
  17083. var loadingPartsAtEdge = levelDetails && frag.sn > levelDetails.endSN;
  17084. var shouldLoadParts = loadingPartsAtEdge || this.shouldLoadParts(levelDetails, frag.end);
  17085. if (shouldLoadParts !== this.loadingParts) {
  17086. this.log("LL-Part loading " + (shouldLoadParts ? 'ON' : 'OFF') + " after parsing segment ending @" + frag.end.toFixed(2));
  17087. this.loadingParts = shouldLoadParts;
  17088. }
  17089. this.updateLevelTiming(frag, part, level, chunkMeta.partial);
  17090. };
  17091. _proto.shouldLoadParts = function shouldLoadParts(details, bufferEnd) {
  17092. if (this.config.lowLatencyMode) {
  17093. if (!details) {
  17094. return this.loadingParts;
  17095. }
  17096. if (details != null && details.partList) {
  17097. var _details$fragmentHint;
  17098. // Buffer must be ahead of first part + duration of parts after last segment
  17099. // and playback must be at or past segment adjacent to part list
  17100. var firstPart = details.partList[0];
  17101. var safePartStart = firstPart.end + (((_details$fragmentHint = details.fragmentHint) == null ? void 0 : _details$fragmentHint.duration) || 0);
  17102. if (bufferEnd >= safePartStart) {
  17103. var _this$media;
  17104. var playhead = this.hls.hasEnoughToStart ? ((_this$media = this.media) == null ? void 0 : _this$media.currentTime) || this.lastCurrentTime : this.getLoadPosition();
  17105. if (playhead > firstPart.start - firstPart.fragment.duration) {
  17106. return true;
  17107. }
  17108. }
  17109. }
  17110. }
  17111. return false;
  17112. };
  17113. _proto.getCurrentContext = function getCurrentContext(chunkMeta) {
  17114. var levels = this.levels,
  17115. fragCurrent = this.fragCurrent;
  17116. var levelIndex = chunkMeta.level,
  17117. sn = chunkMeta.sn,
  17118. partIndex = chunkMeta.part;
  17119. if (!(levels != null && levels[levelIndex])) {
  17120. this.warn("Levels object was unset while buffering fragment " + sn + " of " + this.playlistLabel() + " " + levelIndex + ". The current chunk will not be buffered.");
  17121. return null;
  17122. }
  17123. var level = levels[levelIndex];
  17124. var levelDetails = level.details;
  17125. var part = partIndex > -1 ? getPartWith(levelDetails, sn, partIndex) : null;
  17126. var frag = part ? part.fragment : getFragmentWithSN(levelDetails, sn, fragCurrent);
  17127. if (!frag) {
  17128. return null;
  17129. }
  17130. if (fragCurrent && fragCurrent !== frag) {
  17131. frag.stats = fragCurrent.stats;
  17132. }
  17133. return {
  17134. frag: frag,
  17135. part: part,
  17136. level: level
  17137. };
  17138. };
  17139. _proto.bufferFragmentData = function bufferFragmentData(data, frag, part, chunkMeta, noBacktracking) {
  17140. var _buffer;
  17141. if (!data || this.state !== State.PARSING) {
  17142. return;
  17143. }
  17144. var data1 = data.data1,
  17145. data2 = data.data2;
  17146. var buffer = data1;
  17147. if (data1 && data2) {
  17148. // Combine the moof + mdat so that we buffer with a single append
  17149. buffer = appendUint8Array(data1, data2);
  17150. }
  17151. if (!((_buffer = buffer) != null && _buffer.length)) {
  17152. return;
  17153. }
  17154. var offsetTimestamp = this.initPTS[frag.cc];
  17155. var offset = offsetTimestamp ? -offsetTimestamp.baseTime / offsetTimestamp.timescale : undefined;
  17156. var segment = {
  17157. type: data.type,
  17158. frag: frag,
  17159. part: part,
  17160. chunkMeta: chunkMeta,
  17161. offset: offset,
  17162. parent: frag.type,
  17163. data: buffer
  17164. };
  17165. this.hls.trigger(Events.BUFFER_APPENDING, segment);
  17166. if (data.dropped && data.independent && !part) {
  17167. if (noBacktracking) {
  17168. return;
  17169. }
  17170. // Clear buffer so that we reload previous segments sequentially if required
  17171. this.flushBufferGap(frag);
  17172. }
  17173. };
  17174. _proto.flushBufferGap = function flushBufferGap(frag) {
  17175. var media = this.media;
  17176. if (!media) {
  17177. return;
  17178. }
  17179. // If currentTime is not buffered, clear the back buffer so that we can backtrack as much as needed
  17180. if (!BufferHelper.isBuffered(media, media.currentTime)) {
  17181. this.flushMainBuffer(0, frag.start);
  17182. return;
  17183. }
  17184. // Remove back-buffer without interrupting playback to allow back tracking
  17185. var currentTime = media.currentTime;
  17186. var bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  17187. var fragDuration = frag.duration;
  17188. var segmentFraction = Math.min(this.config.maxFragLookUpTolerance * 2, fragDuration * 0.25);
  17189. var start = Math.max(Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction), currentTime + segmentFraction);
  17190. if (frag.start - start > segmentFraction) {
  17191. this.flushMainBuffer(start, frag.start);
  17192. }
  17193. };
  17194. _proto.getFwdBufferInfo = function getFwdBufferInfo(bufferable, type) {
  17195. var _this$media2;
  17196. var pos = this.getLoadPosition();
  17197. if (!isFiniteNumber(pos)) {
  17198. return null;
  17199. }
  17200. var backwardSeek = this.lastCurrentTime > pos;
  17201. var maxBufferHole = backwardSeek || (_this$media2 = this.media) != null && _this$media2.paused ? 0 : this.config.maxBufferHole;
  17202. return this.getFwdBufferInfoAtPos(bufferable, pos, type, maxBufferHole);
  17203. };
  17204. _proto.getFwdBufferInfoAtPos = function getFwdBufferInfoAtPos(bufferable, pos, type, maxBufferHole) {
  17205. var bufferInfo = BufferHelper.bufferInfo(bufferable, pos, maxBufferHole);
  17206. // Workaround flaw in getting forward buffer when maxBufferHole is smaller than gap at current pos
  17207. if (bufferInfo.len === 0 && bufferInfo.nextStart !== undefined) {
  17208. var bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type);
  17209. if (bufferedFragAtPos && (bufferInfo.nextStart <= bufferedFragAtPos.end || bufferedFragAtPos.gap)) {
  17210. var gapDuration = Math.max(Math.min(bufferInfo.nextStart, bufferedFragAtPos.end) - pos, maxBufferHole);
  17211. return BufferHelper.bufferInfo(bufferable, pos, gapDuration);
  17212. }
  17213. }
  17214. return bufferInfo;
  17215. };
  17216. _proto.getMaxBufferLength = function getMaxBufferLength(levelBitrate) {
  17217. var config = this.config;
  17218. var maxBufLen;
  17219. if (levelBitrate) {
  17220. maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
  17221. } else {
  17222. maxBufLen = config.maxBufferLength;
  17223. }
  17224. return Math.min(maxBufLen, config.maxMaxBufferLength);
  17225. };
  17226. _proto.reduceMaxBufferLength = function reduceMaxBufferLength(threshold, fragDuration) {
  17227. var config = this.config;
  17228. var minLength = Math.max(Math.min(threshold - fragDuration, config.maxBufferLength), fragDuration);
  17229. var reducedLength = Math.max(threshold - fragDuration * 3, config.maxMaxBufferLength / 2, minLength);
  17230. if (reducedLength >= minLength) {
  17231. // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
  17232. config.maxMaxBufferLength = reducedLength;
  17233. this.warn("Reduce max buffer length to " + reducedLength + "s");
  17234. return true;
  17235. }
  17236. return false;
  17237. };
  17238. _proto.getAppendedFrag = function getAppendedFrag(position, playlistType) {
  17239. var _this$fragmentTracker;
  17240. if (playlistType === void 0) {
  17241. playlistType = PlaylistLevelType.MAIN;
  17242. }
  17243. var fragOrPart = (_this$fragmentTracker = this.fragmentTracker) == null ? void 0 : _this$fragmentTracker.getAppendedFrag(position, playlistType);
  17244. if (fragOrPart && 'fragment' in fragOrPart) {
  17245. return fragOrPart.fragment;
  17246. }
  17247. return fragOrPart;
  17248. };
  17249. _proto.getNextFragment = function getNextFragment(pos, levelDetails) {
  17250. var fragments = levelDetails.fragments;
  17251. var fragLen = fragments.length;
  17252. if (!fragLen) {
  17253. return null;
  17254. }
  17255. // find fragment index, contiguous with end of buffer position
  17256. var config = this.config;
  17257. var start = fragments[0].start;
  17258. var canLoadParts = config.lowLatencyMode && !!levelDetails.partList;
  17259. var frag = null;
  17260. if (levelDetails.live) {
  17261. var initialLiveManifestSize = config.initialLiveManifestSize;
  17262. if (fragLen < initialLiveManifestSize) {
  17263. this.warn("Not enough fragments to start playback (have: " + fragLen + ", need: " + initialLiveManifestSize + ")");
  17264. return null;
  17265. }
  17266. // The real fragment start times for a live stream are only known after the PTS range for that level is known.
  17267. // In order to discover the range, we load the best matching fragment for that level and demux it.
  17268. // Do not load using live logic if the starting frag is requested - we want to use getFragmentAtPosition() so that
  17269. // we get the fragment matching that start time
  17270. if (!levelDetails.PTSKnown && !this.startFragRequested && this.startPosition === -1 || pos < start) {
  17271. var _frag;
  17272. if (canLoadParts && !this.loadingParts) {
  17273. this.log("LL-Part loading ON for initial live fragment");
  17274. this.loadingParts = true;
  17275. }
  17276. frag = this.getInitialLiveFragment(levelDetails);
  17277. var mainStart = this.hls.startPosition;
  17278. var liveSyncPosition = this.hls.liveSyncPosition;
  17279. var startPosition = frag ? (mainStart !== -1 && mainStart >= start ? mainStart : liveSyncPosition) || frag.start : pos;
  17280. this.log("Setting startPosition to " + startPosition + " to match start frag at live edge. mainStart: " + mainStart + " liveSyncPosition: " + liveSyncPosition + " frag.start: " + ((_frag = frag) == null ? void 0 : _frag.start));
  17281. this.startPosition = this.nextLoadPosition = startPosition;
  17282. }
  17283. } else if (pos <= start) {
  17284. // VoD playlist: if loadPosition before start of playlist, load first fragment
  17285. frag = fragments[0];
  17286. }
  17287. // If we haven't run into any special cases already, just load the fragment most closely matching the requested position
  17288. if (!frag) {
  17289. var end = this.loadingParts ? levelDetails.partEnd : levelDetails.fragmentEnd;
  17290. frag = this.getFragmentAtPosition(pos, end, levelDetails);
  17291. }
  17292. var programFrag = this.filterReplacedPrimary(frag, levelDetails);
  17293. if (!programFrag && frag) {
  17294. var curSNIdx = frag.sn - levelDetails.startSN;
  17295. programFrag = this.filterReplacedPrimary(fragments[curSNIdx + 1] || null, levelDetails);
  17296. }
  17297. return this.mapToInitFragWhenRequired(programFrag);
  17298. };
  17299. _proto.isLoopLoading = function isLoopLoading(frag, targetBufferTime) {
  17300. var trackerState = this.fragmentTracker.getState(frag);
  17301. return (trackerState === FragmentState.OK || trackerState === FragmentState.PARTIAL && !!frag.gap) && this.nextLoadPosition > targetBufferTime;
  17302. };
  17303. _proto.getNextFragmentLoopLoading = function getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, playlistType, maxBufLen) {
  17304. var nextFragment = null;
  17305. if (frag.gap) {
  17306. nextFragment = this.getNextFragment(this.nextLoadPosition, levelDetails);
  17307. if (nextFragment && !nextFragment.gap && bufferInfo.nextStart) {
  17308. // Media buffered after GAP tags should not make the next buffer timerange exceed forward buffer length
  17309. var nextbufferInfo = this.getFwdBufferInfoAtPos(this.mediaBuffer ? this.mediaBuffer : this.media, bufferInfo.nextStart, playlistType, 0);
  17310. if (nextbufferInfo !== null && bufferInfo.len + nextbufferInfo.len >= maxBufLen) {
  17311. // Returning here might result in not finding an audio and video candiate to skip to
  17312. var sn = nextFragment.sn;
  17313. if (this.loopSn !== sn) {
  17314. this.log("buffer full after gaps in \"" + playlistType + "\" playlist starting at sn: " + sn);
  17315. this.loopSn = sn;
  17316. }
  17317. return null;
  17318. }
  17319. }
  17320. }
  17321. this.loopSn = undefined;
  17322. return nextFragment;
  17323. };
  17324. _proto.filterReplacedPrimary = function filterReplacedPrimary(frag, details) {
  17325. if (!frag) {
  17326. return frag;
  17327. }
  17328. if (interstitialsEnabled(this.hls.config)) ;
  17329. return frag;
  17330. };
  17331. _proto.mapToInitFragWhenRequired = function mapToInitFragWhenRequired(frag) {
  17332. // If an initSegment is present, it must be buffered first
  17333. if (frag != null && frag.initSegment && !(frag != null && frag.initSegment.data) && !this.bitrateTest) {
  17334. return frag.initSegment;
  17335. }
  17336. return frag;
  17337. };
  17338. _proto.getNextPart = function getNextPart(partList, frag, targetBufferTime) {
  17339. var nextPart = -1;
  17340. var contiguous = false;
  17341. var independentAttrOmitted = true;
  17342. for (var i = 0, len = partList.length; i < len; i++) {
  17343. var part = partList[i];
  17344. independentAttrOmitted = independentAttrOmitted && !part.independent;
  17345. if (nextPart > -1 && targetBufferTime < part.start) {
  17346. break;
  17347. }
  17348. var loaded = part.loaded;
  17349. if (loaded) {
  17350. nextPart = -1;
  17351. } else if ((contiguous || part.independent || independentAttrOmitted) && part.fragment === frag) {
  17352. nextPart = i;
  17353. }
  17354. contiguous = loaded;
  17355. }
  17356. return nextPart;
  17357. };
  17358. _proto.loadedEndOfParts = function loadedEndOfParts(partList, targetBufferTime) {
  17359. var lastPart = partList[partList.length - 1];
  17360. return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;
  17361. }
  17362. /*
  17363. This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the
  17364. "sliding" of the playlist, which is its offset from the start of playback. After sliding we can compute the real
  17365. start and end times for each fragment in the playlist (after which this method will not need to be called).
  17366. */;
  17367. _proto.getInitialLiveFragment = function getInitialLiveFragment(levelDetails) {
  17368. var fragments = levelDetails.fragments;
  17369. var fragPrevious = this.fragPrevious;
  17370. var frag = null;
  17371. if (fragPrevious) {
  17372. if (levelDetails.hasProgramDateTime) {
  17373. // Prefer using PDT, because it can be accurate enough to choose the correct fragment without knowing the level sliding
  17374. this.log("Live playlist, switching playlist, load frag with same PDT: " + fragPrevious.programDateTime);
  17375. frag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, this.config.maxFragLookUpTolerance);
  17376. }
  17377. if (!frag) {
  17378. // SN does not need to be accurate between renditions, but depending on the packaging it may be so.
  17379. var targetSN = fragPrevious.sn + 1;
  17380. if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
  17381. var fragNext = fragments[targetSN - levelDetails.startSN];
  17382. // Ensure that we're staying within the continuity range, since PTS resets upon a new range
  17383. if (fragPrevious.cc === fragNext.cc) {
  17384. frag = fragNext;
  17385. this.log("Live playlist, switching playlist, load frag with next SN: " + frag.sn);
  17386. }
  17387. }
  17388. // It's important to stay within the continuity range if available; otherwise the fragments in the playlist
  17389. // will have the wrong start times
  17390. if (!frag) {
  17391. frag = findNearestWithCC(levelDetails, fragPrevious.cc, fragPrevious.end);
  17392. if (frag) {
  17393. this.log("Live playlist, switching playlist, load frag with same CC: " + frag.sn);
  17394. }
  17395. }
  17396. }
  17397. } else {
  17398. // Find a new start fragment when fragPrevious is null
  17399. var liveStart = this.hls.liveSyncPosition;
  17400. if (liveStart !== null) {
  17401. frag = this.getFragmentAtPosition(liveStart, this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge, levelDetails);
  17402. }
  17403. }
  17404. return frag;
  17405. }
  17406. /*
  17407. This method finds the best matching fragment given the provided position.
  17408. */;
  17409. _proto.getFragmentAtPosition = function getFragmentAtPosition(bufferEnd, end, levelDetails) {
  17410. var config = this.config;
  17411. var fragPrevious = this.fragPrevious;
  17412. var fragments = levelDetails.fragments,
  17413. endSN = levelDetails.endSN;
  17414. var fragmentHint = levelDetails.fragmentHint;
  17415. var maxFragLookUpTolerance = config.maxFragLookUpTolerance;
  17416. var partList = levelDetails.partList;
  17417. var loadingParts = !!(this.loadingParts && partList != null && partList.length && fragmentHint);
  17418. if (loadingParts && fragmentHint && !this.bitrateTest && partList[partList.length - 1].fragment.sn === fragmentHint.sn) {
  17419. // Include incomplete fragment with parts at end
  17420. fragments = fragments.concat(fragmentHint);
  17421. endSN = fragmentHint.sn;
  17422. }
  17423. var frag;
  17424. if (bufferEnd < end) {
  17425. var _this$media3;
  17426. var backwardSeek = bufferEnd < this.lastCurrentTime;
  17427. var lookupTolerance = backwardSeek || bufferEnd > end - maxFragLookUpTolerance || (_this$media3 = this.media) != null && _this$media3.paused || !this.startFragRequested ? 0 : maxFragLookUpTolerance;
  17428. // Remove the tolerance if it would put the bufferEnd past the actual end of stream
  17429. // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
  17430. frag = findFragmentByPTS(fragPrevious, fragments, bufferEnd, lookupTolerance);
  17431. } else {
  17432. // reach end of playlist
  17433. frag = fragments[fragments.length - 1];
  17434. }
  17435. if (frag) {
  17436. var curSNIdx = frag.sn - levelDetails.startSN;
  17437. // Move fragPrevious forward to support forcing the next fragment to load
  17438. // when the buffer catches up to a previously buffered range.
  17439. var fragState = this.fragmentTracker.getState(frag);
  17440. if (fragState === FragmentState.OK || fragState === FragmentState.PARTIAL && frag.gap) {
  17441. fragPrevious = frag;
  17442. }
  17443. if (fragPrevious && frag.sn === fragPrevious.sn && (!loadingParts || partList[0].fragment.sn > frag.sn || !levelDetails.live && !loadingParts)) {
  17444. // Force the next fragment to load if the previous one was already selected. This can occasionally happen with
  17445. // non-uniform fragment durations
  17446. var sameLevel = fragPrevious && frag.level === fragPrevious.level;
  17447. if (sameLevel) {
  17448. var nextFrag = fragments[curSNIdx + 1];
  17449. if (frag.sn < endSN && this.fragmentTracker.getState(nextFrag) !== FragmentState.OK) {
  17450. frag = nextFrag;
  17451. } else {
  17452. frag = null;
  17453. }
  17454. }
  17455. }
  17456. }
  17457. return frag;
  17458. };
  17459. _proto.alignPlaylists = function alignPlaylists(details, previousDetails, switchDetails) {
  17460. // TODO: If not for `shouldAlignOnDiscontinuities` requiring fragPrevious.cc,
  17461. // this could all go in level-helper mergeDetails()
  17462. var length = details.fragments.length;
  17463. if (!length) {
  17464. this.warn("No fragments in live playlist");
  17465. return 0;
  17466. }
  17467. var slidingStart = details.fragmentStart;
  17468. var firstLevelLoad = !previousDetails;
  17469. var aligned = details.alignedSliding && isFiniteNumber(slidingStart);
  17470. if (firstLevelLoad || !aligned && !slidingStart) {
  17471. alignStream(switchDetails, details);
  17472. var alignedSlidingStart = details.fragmentStart;
  17473. this.log("Live playlist sliding: " + alignedSlidingStart.toFixed(2) + " start-sn: " + (previousDetails ? previousDetails.startSN : 'na') + "->" + details.startSN + " fragments: " + length);
  17474. return alignedSlidingStart;
  17475. }
  17476. return slidingStart;
  17477. };
  17478. _proto.waitForCdnTuneIn = function waitForCdnTuneIn(details) {
  17479. // Wait for Low-Latency CDN Tune-in to get an updated playlist
  17480. var advancePartLimit = 3;
  17481. return details.live && details.canBlockReload && details.partTarget && details.tuneInGoal > Math.max(details.partHoldBack, details.partTarget * advancePartLimit);
  17482. };
  17483. _proto.setStartPosition = function setStartPosition(details, sliding) {
  17484. // compute start position if set to -1. use it straight away if value is defined
  17485. var startPosition = this.startPosition;
  17486. if (startPosition < sliding) {
  17487. startPosition = -1;
  17488. }
  17489. var timelineOffset = this.timelineOffset;
  17490. if (startPosition === -1) {
  17491. // Use Playlist EXT-X-START:TIME-OFFSET when set
  17492. // Prioritize Multivariant Playlist offset so that main, audio, and subtitle stream-controller start times match
  17493. var offsetInMultivariantPlaylist = this.startTimeOffset !== null;
  17494. var startTimeOffset = offsetInMultivariantPlaylist ? this.startTimeOffset : details.startTimeOffset;
  17495. if (startTimeOffset !== null && isFiniteNumber(startTimeOffset)) {
  17496. startPosition = sliding + startTimeOffset;
  17497. if (startTimeOffset < 0) {
  17498. startPosition += details.edge;
  17499. }
  17500. startPosition = Math.min(Math.max(sliding, startPosition), sliding + details.totalduration);
  17501. this.log("Setting startPosition to " + startPosition + " for start time offset " + startTimeOffset + " found in " + (offsetInMultivariantPlaylist ? 'multivariant' : 'media') + " playlist");
  17502. this.startPosition = startPosition;
  17503. } else if (details.live) {
  17504. // Leave this.startPosition at -1, so that we can use `getInitialLiveFragment` logic when startPosition has
  17505. // not been specified via the config or an as an argument to startLoad (#3736).
  17506. startPosition = this.hls.liveSyncPosition || sliding;
  17507. this.log("Setting startPosition to -1 to start at live edge " + startPosition);
  17508. this.startPosition = -1;
  17509. } else {
  17510. this.log("setting startPosition to 0 by default");
  17511. this.startPosition = startPosition = 0;
  17512. }
  17513. this.lastCurrentTime = startPosition + timelineOffset;
  17514. }
  17515. this.nextLoadPosition = startPosition + timelineOffset;
  17516. };
  17517. _proto.getLoadPosition = function getLoadPosition() {
  17518. var _this$hls;
  17519. var media = this.media;
  17520. // if we have not yet loaded any fragment, start loading from start position
  17521. var pos = 0;
  17522. if ((_this$hls = this.hls) != null && _this$hls.hasEnoughToStart && media) {
  17523. pos = media.currentTime;
  17524. } else if (this.nextLoadPosition >= 0) {
  17525. pos = this.nextLoadPosition;
  17526. }
  17527. return pos;
  17528. };
  17529. _proto.handleFragLoadAborted = function handleFragLoadAborted(frag, part) {
  17530. if (this.transmuxer && frag.type === this.playlistType && isMediaFragment(frag) && frag.stats.aborted) {
  17531. this.log("Fragment " + frag.sn + (part ? ' part ' + part.index : '') + " of " + this.playlistLabel() + " " + frag.level + " was aborted");
  17532. this.resetFragmentLoading(frag);
  17533. }
  17534. };
  17535. _proto.resetFragmentLoading = function resetFragmentLoading(frag) {
  17536. if (!this.fragCurrent || !this.fragContextChanged(frag) && this.state !== State.FRAG_LOADING_WAITING_RETRY) {
  17537. this.state = State.IDLE;
  17538. }
  17539. };
  17540. _proto.onFragmentOrKeyLoadError = function onFragmentOrKeyLoadError(filterType, data) {
  17541. if (data.chunkMeta && !data.frag) {
  17542. var context = this.getCurrentContext(data.chunkMeta);
  17543. if (context) {
  17544. data.frag = context.frag;
  17545. }
  17546. }
  17547. var frag = data.frag;
  17548. // Handle frag error related to caller's filterType
  17549. if (!frag || frag.type !== filterType || !this.levels) {
  17550. return;
  17551. }
  17552. if (this.fragContextChanged(frag)) {
  17553. var _this$fragCurrent;
  17554. this.warn("Frag load error must match current frag to retry " + frag.url + " > " + ((_this$fragCurrent = this.fragCurrent) == null ? void 0 : _this$fragCurrent.url));
  17555. return;
  17556. }
  17557. var gapTagEncountered = data.details === ErrorDetails.FRAG_GAP;
  17558. if (gapTagEncountered) {
  17559. this.fragmentTracker.fragBuffered(frag, true);
  17560. }
  17561. // keep retrying until the limit will be reached
  17562. var errorAction = data.errorAction;
  17563. var _ref2 = errorAction || {},
  17564. action = _ref2.action,
  17565. flags = _ref2.flags,
  17566. _ref2$retryCount = _ref2.retryCount,
  17567. retryCount = _ref2$retryCount === void 0 ? 0 : _ref2$retryCount,
  17568. retryConfig = _ref2.retryConfig;
  17569. var couldRetry = !!errorAction && !!retryConfig;
  17570. var retry = couldRetry && action === NetworkErrorAction.RetryRequest;
  17571. var noAlternate = couldRetry && !errorAction.resolved && flags === ErrorActionFlags.MoveAllAlternatesMatchingHost;
  17572. if (!retry && noAlternate && isMediaFragment(frag) && !frag.endList) {
  17573. this.resetFragmentErrors(filterType);
  17574. this.treatAsGap(frag);
  17575. errorAction.resolved = true;
  17576. } else if ((retry || noAlternate) && retryCount < retryConfig.maxNumRetry) {
  17577. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  17578. var delay = getRetryDelay(retryConfig, retryCount);
  17579. this.warn("Fragment " + frag.sn + " of " + filterType + " " + frag.level + " errored with " + data.details + ", retrying loading " + (retryCount + 1) + "/" + retryConfig.maxNumRetry + " in " + delay + "ms");
  17580. errorAction.resolved = true;
  17581. this.retryDate = self.performance.now() + delay;
  17582. this.state = State.FRAG_LOADING_WAITING_RETRY;
  17583. } else if (retryConfig && errorAction) {
  17584. this.resetFragmentErrors(filterType);
  17585. if (retryCount < retryConfig.maxNumRetry) {
  17586. // Network retry is skipped when level switch is preferred
  17587. if (!gapTagEncountered && action !== NetworkErrorAction.RemoveAlternatePermanently) {
  17588. errorAction.resolved = true;
  17589. }
  17590. } else {
  17591. this.warn(data.details + " reached or exceeded max retry (" + retryCount + ")");
  17592. return;
  17593. }
  17594. } else if (action === NetworkErrorAction.SendAlternateToPenaltyBox) {
  17595. this.state = State.WAITING_LEVEL;
  17596. } else {
  17597. this.state = State.ERROR;
  17598. }
  17599. // Perform next async tick sooner to speed up error action resolution
  17600. this.tickImmediate();
  17601. };
  17602. _proto.reduceLengthAndFlushBuffer = function reduceLengthAndFlushBuffer(data) {
  17603. // if in appending state
  17604. if (this.state === State.PARSING || this.state === State.PARSED) {
  17605. var frag = data.frag;
  17606. var playlistType = data.parent;
  17607. var bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  17608. // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
  17609. // reduce max buf len if current position is buffered
  17610. var buffered = bufferedInfo && bufferedInfo.len > 0.5;
  17611. if (buffered) {
  17612. this.reduceMaxBufferLength(bufferedInfo.len, (frag == null ? void 0 : frag.duration) || 10);
  17613. }
  17614. var flushBuffer = !buffered;
  17615. if (flushBuffer) {
  17616. // current position is not buffered, but browser is still complaining about buffer full error
  17617. // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
  17618. // in that case flush the whole audio buffer to recover
  17619. this.warn("Buffer full error while media.currentTime is not buffered, flush " + playlistType + " buffer");
  17620. }
  17621. if (frag) {
  17622. this.fragmentTracker.removeFragment(frag);
  17623. this.nextLoadPosition = frag.start;
  17624. }
  17625. this.resetLoadingState();
  17626. return flushBuffer;
  17627. }
  17628. return false;
  17629. };
  17630. _proto.resetFragmentErrors = function resetFragmentErrors(filterType) {
  17631. if (filterType === PlaylistLevelType.AUDIO) {
  17632. // Reset current fragment since audio track audio is essential and may not have a fail-over track
  17633. this.fragCurrent = null;
  17634. }
  17635. // Fragment errors that result in a level switch or redundant fail-over
  17636. // should reset the stream controller state to idle
  17637. if (!this.hls.hasEnoughToStart) {
  17638. this.startFragRequested = false;
  17639. }
  17640. if (this.state !== State.STOPPED) {
  17641. this.state = State.IDLE;
  17642. }
  17643. };
  17644. _proto.afterBufferFlushed = function afterBufferFlushed(media, bufferType, playlistType) {
  17645. if (!media) {
  17646. return;
  17647. }
  17648. // After successful buffer flushing, filter flushed fragments from bufferedFrags use mediaBuffered instead of media
  17649. // (so that we will check against video.buffered ranges in case of alt audio track)
  17650. var bufferedTimeRanges = BufferHelper.getBuffered(media);
  17651. this.fragmentTracker.detectEvictedFragments(bufferType, bufferedTimeRanges, playlistType);
  17652. if (this.state === State.ENDED) {
  17653. this.resetLoadingState();
  17654. }
  17655. };
  17656. _proto.resetLoadingState = function resetLoadingState() {
  17657. this.log('Reset loading state');
  17658. this.fragCurrent = null;
  17659. this.fragPrevious = null;
  17660. if (this.state !== State.STOPPED) {
  17661. this.state = State.IDLE;
  17662. }
  17663. };
  17664. _proto.resetStartWhenNotLoaded = function resetStartWhenNotLoaded(level) {
  17665. // if loadedmetadata is not set, it means that first frag request failed
  17666. // in that case, reset startFragRequested flag
  17667. if (!this.hls.hasEnoughToStart) {
  17668. this.startFragRequested = false;
  17669. var details = level ? level.details : null;
  17670. if (details != null && details.live) {
  17671. // Update the start position and return to IDLE to recover live start
  17672. this.log("resetting startPosition for live start");
  17673. this.startPosition = -1;
  17674. this.setStartPosition(details, details.fragmentStart);
  17675. this.resetLoadingState();
  17676. } else {
  17677. this.nextLoadPosition = this.startPosition;
  17678. }
  17679. }
  17680. };
  17681. _proto.resetWhenMissingContext = function resetWhenMissingContext(chunkMeta) {
  17682. this.warn("The loading context changed while buffering fragment " + chunkMeta.sn + " of " + this.playlistLabel() + " " + chunkMeta.level + ". This chunk will not be buffered.");
  17683. this.removeUnbufferedFrags();
  17684. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  17685. this.resetLoadingState();
  17686. };
  17687. _proto.removeUnbufferedFrags = function removeUnbufferedFrags(start) {
  17688. if (start === void 0) {
  17689. start = 0;
  17690. }
  17691. this.fragmentTracker.removeFragmentsInRange(start, Infinity, this.playlistType, false, true);
  17692. };
  17693. _proto.updateLevelTiming = function updateLevelTiming(frag, part, level, partial) {
  17694. var _this7 = this;
  17695. var details = level.details;
  17696. if (!details) {
  17697. this.warn('level.details undefined');
  17698. return;
  17699. }
  17700. var parsed = Object.keys(frag.elementaryStreams).reduce(function (result, type) {
  17701. var info = frag.elementaryStreams[type];
  17702. if (info) {
  17703. var parsedDuration = info.endPTS - info.startPTS;
  17704. if (parsedDuration <= 0) {
  17705. // Destroy the transmuxer after it's next time offset failed to advance because duration was <= 0.
  17706. // The new transmuxer will be configured with a time offset matching the next fragment start,
  17707. // preventing the timeline from shifting.
  17708. _this7.warn("Could not parse fragment " + frag.sn + " " + type + " duration reliably (" + parsedDuration + ")");
  17709. return result || false;
  17710. }
  17711. var drift = partial ? 0 : updateFragPTSDTS(details, frag, info.startPTS, info.endPTS, info.startDTS, info.endDTS);
  17712. _this7.hls.trigger(Events.LEVEL_PTS_UPDATED, {
  17713. details: details,
  17714. level: level,
  17715. drift: drift,
  17716. type: type,
  17717. frag: frag,
  17718. start: info.startPTS,
  17719. end: info.endPTS
  17720. });
  17721. return true;
  17722. }
  17723. return result;
  17724. }, false);
  17725. if (!parsed) {
  17726. var _this$transmuxer;
  17727. if (level.fragmentError === 0) {
  17728. // Mark and track the odd empty segment as a gap to avoid reloading
  17729. this.treatAsGap(frag, level);
  17730. }
  17731. if (((_this$transmuxer = this.transmuxer) == null ? void 0 : _this$transmuxer.error) === null) {
  17732. var error = new Error("Found no media in fragment " + frag.sn + " of " + this.playlistLabel() + " " + frag.level + " resetting transmuxer to fallback to playlist timing");
  17733. this.warn(error.message);
  17734. this.hls.trigger(Events.ERROR, {
  17735. type: ErrorTypes.MEDIA_ERROR,
  17736. details: ErrorDetails.FRAG_PARSING_ERROR,
  17737. fatal: false,
  17738. error: error,
  17739. frag: frag,
  17740. reason: "Found no media in msn " + frag.sn + " of " + this.playlistLabel() + " \"" + level.url + "\""
  17741. });
  17742. if (!this.hls) {
  17743. return;
  17744. }
  17745. this.resetTransmuxer();
  17746. }
  17747. // For this error fallthrough. Marking parsed will allow advancing to next fragment.
  17748. }
  17749. this.state = State.PARSED;
  17750. this.log("Parsed " + frag.type + " sn: " + frag.sn + (part ? ' part: ' + part.index : '') + " of " + this.fragInfo(frag, false, part) + ")");
  17751. this.hls.trigger(Events.FRAG_PARSED, {
  17752. frag: frag,
  17753. part: part
  17754. });
  17755. };
  17756. _proto.playlistLabel = function playlistLabel() {
  17757. return this.playlistType === PlaylistLevelType.MAIN ? 'level' : 'track';
  17758. };
  17759. _proto.fragInfo = function fragInfo(frag, pts, part) {
  17760. var _ref3, _ref4;
  17761. if (pts === void 0) {
  17762. pts = true;
  17763. }
  17764. return this.playlistLabel() + " " + frag.level + " (" + (part ? 'part' : 'frag') + ":[" + ((_ref3 = pts && !part ? frag.startPTS : (part || frag).start) != null ? _ref3 : NaN).toFixed(3) + "-" + ((_ref4 = pts && !part ? frag.endPTS : (part || frag).end) != null ? _ref4 : NaN).toFixed(3) + "]" + (part && frag.type === 'main' ? 'INDEPENDENT=' + (part.independent ? 'YES' : 'NO') : '');
  17765. };
  17766. _proto.treatAsGap = function treatAsGap(frag, level) {
  17767. if (level) {
  17768. level.fragmentError++;
  17769. }
  17770. frag.gap = true;
  17771. this.fragmentTracker.removeFragment(frag);
  17772. this.fragmentTracker.fragBuffered(frag, true);
  17773. };
  17774. _proto.resetTransmuxer = function resetTransmuxer() {
  17775. var _this$transmuxer2;
  17776. (_this$transmuxer2 = this.transmuxer) == null ? void 0 : _this$transmuxer2.reset();
  17777. };
  17778. _proto.recoverWorkerError = function recoverWorkerError(data) {
  17779. if (data.event === 'demuxerWorker') {
  17780. this.fragmentTracker.removeAllFragments();
  17781. if (this.transmuxer) {
  17782. this.transmuxer.destroy();
  17783. this.transmuxer = null;
  17784. }
  17785. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  17786. this.resetLoadingState();
  17787. }
  17788. };
  17789. return _createClass(BaseStreamController, [{
  17790. key: "startPositionValue",
  17791. get: function get() {
  17792. var nextLoadPosition = this.nextLoadPosition,
  17793. startPosition = this.startPosition;
  17794. if (startPosition === -1 && nextLoadPosition) {
  17795. return nextLoadPosition;
  17796. }
  17797. return startPosition;
  17798. }
  17799. }, {
  17800. key: "bufferingEnabled",
  17801. get: function get() {
  17802. return this.buffering;
  17803. }
  17804. }, {
  17805. key: "inFlightFrag",
  17806. get: function get() {
  17807. return {
  17808. frag: this.fragCurrent,
  17809. state: this.state
  17810. };
  17811. }
  17812. }, {
  17813. key: "timelineOffset",
  17814. get: function get() {
  17815. var configuredTimelineOffset = this.config.timelineOffset;
  17816. if (configuredTimelineOffset) {
  17817. var _this$getLevelDetails;
  17818. return ((_this$getLevelDetails = this.getLevelDetails()) == null ? void 0 : _this$getLevelDetails.appliedTimelineOffset) || configuredTimelineOffset;
  17819. }
  17820. return 0;
  17821. }
  17822. }, {
  17823. key: "primaryPrefetch",
  17824. get: function get() {
  17825. if (interstitialsEnabled(this.hls.config)) ;
  17826. return false;
  17827. }
  17828. }, {
  17829. key: "state",
  17830. get: function get() {
  17831. return this._state;
  17832. },
  17833. set: function set(nextState) {
  17834. var previousState = this._state;
  17835. if (previousState !== nextState) {
  17836. this._state = nextState;
  17837. this.log(previousState + "->" + nextState);
  17838. }
  17839. }
  17840. }]);
  17841. }(TaskLoop);
  17842. function interstitialsEnabled(config) {
  17843. return false;
  17844. }
  17845. function addEventListener(el, type, listener) {
  17846. removeEventListener(el, type, listener);
  17847. el.addEventListener(type, listener);
  17848. }
  17849. function removeEventListener(el, type, listener) {
  17850. el.removeEventListener(type, listener);
  17851. }
  17852. var MAX_START_GAP_JUMP = 2.0;
  17853. var SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;
  17854. var SKIP_BUFFER_RANGE_START = 0.05;
  17855. var TICK_INTERVAL$1 = 100;
  17856. var GapController = /*#__PURE__*/function (_TaskLoop) {
  17857. function GapController(hls, fragmentTracker) {
  17858. var _this;
  17859. _this = _TaskLoop.call(this, 'gap-controller', hls.logger) || this;
  17860. _this.hls = null;
  17861. _this.fragmentTracker = null;
  17862. _this.media = null;
  17863. _this.mediaSource = void 0;
  17864. _this.nudgeRetry = 0;
  17865. _this.stallReported = false;
  17866. _this.stalled = null;
  17867. _this.moved = false;
  17868. _this.seeking = false;
  17869. _this.buffered = {};
  17870. _this.lastCurrentTime = 0;
  17871. _this.ended = 0;
  17872. _this.waiting = 0;
  17873. _this.onMediaPlaying = function () {
  17874. _this.ended = 0;
  17875. _this.waiting = 0;
  17876. };
  17877. _this.onMediaWaiting = function () {
  17878. var _this$media;
  17879. if ((_this$media = _this.media) != null && _this$media.seeking) {
  17880. return;
  17881. }
  17882. _this.waiting = self.performance.now();
  17883. _this.tick();
  17884. };
  17885. _this.onMediaEnded = function () {
  17886. if (_this.hls) {
  17887. var _this$media2;
  17888. // ended is set when triggering MEDIA_ENDED so that we do not trigger it again on stall or on tick with media.ended
  17889. _this.ended = ((_this$media2 = _this.media) == null ? void 0 : _this$media2.currentTime) || 1;
  17890. _this.hls.trigger(Events.MEDIA_ENDED, {
  17891. stalled: false
  17892. });
  17893. }
  17894. };
  17895. _this.hls = hls;
  17896. _this.fragmentTracker = fragmentTracker;
  17897. _this.registerListeners();
  17898. return _this;
  17899. }
  17900. _inheritsLoose(GapController, _TaskLoop);
  17901. var _proto = GapController.prototype;
  17902. _proto.registerListeners = function registerListeners() {
  17903. var hls = this.hls;
  17904. if (hls) {
  17905. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  17906. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  17907. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  17908. }
  17909. };
  17910. _proto.unregisterListeners = function unregisterListeners() {
  17911. var hls = this.hls;
  17912. if (hls) {
  17913. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  17914. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  17915. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  17916. }
  17917. };
  17918. _proto.destroy = function destroy() {
  17919. _TaskLoop.prototype.destroy.call(this);
  17920. this.unregisterListeners();
  17921. this.media = this.hls = this.fragmentTracker = null;
  17922. this.mediaSource = undefined;
  17923. };
  17924. _proto.onMediaAttached = function onMediaAttached(event, data) {
  17925. this.setInterval(TICK_INTERVAL$1);
  17926. this.mediaSource = data.mediaSource;
  17927. var media = this.media = data.media;
  17928. addEventListener(media, 'playing', this.onMediaPlaying);
  17929. addEventListener(media, 'waiting', this.onMediaWaiting);
  17930. addEventListener(media, 'ended', this.onMediaEnded);
  17931. };
  17932. _proto.onMediaDetaching = function onMediaDetaching(event, data) {
  17933. this.clearInterval();
  17934. var media = this.media;
  17935. if (media) {
  17936. removeEventListener(media, 'playing', this.onMediaPlaying);
  17937. removeEventListener(media, 'waiting', this.onMediaWaiting);
  17938. removeEventListener(media, 'ended', this.onMediaEnded);
  17939. this.media = null;
  17940. }
  17941. this.mediaSource = undefined;
  17942. };
  17943. _proto.onBufferAppended = function onBufferAppended(event, data) {
  17944. this.buffered = data.timeRanges;
  17945. };
  17946. _proto.tick = function tick() {
  17947. var _this$media3;
  17948. if (!((_this$media3 = this.media) != null && _this$media3.readyState) || !this.hasBuffered) {
  17949. return;
  17950. }
  17951. var currentTime = this.media.currentTime;
  17952. this.poll(currentTime, this.lastCurrentTime);
  17953. this.lastCurrentTime = currentTime;
  17954. }
  17955. /**
  17956. * Checks if the playhead is stuck within a gap, and if so, attempts to free it.
  17957. * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).
  17958. *
  17959. * @param lastCurrentTime - Previously read playhead position
  17960. */;
  17961. _proto.poll = function poll(currentTime, lastCurrentTime) {
  17962. var _this$hls, _this$hls2;
  17963. var config = (_this$hls = this.hls) == null ? void 0 : _this$hls.config;
  17964. if (!config) {
  17965. return;
  17966. }
  17967. var media = this.media;
  17968. if (!media) {
  17969. return;
  17970. }
  17971. var seeking = media.seeking;
  17972. var seeked = this.seeking && !seeking;
  17973. var beginSeek = !this.seeking && seeking;
  17974. var pausedEndedOrHalted = media.paused && !seeking || media.ended || media.playbackRate === 0;
  17975. this.seeking = seeking;
  17976. // The playhead is moving, no-op
  17977. if (currentTime !== lastCurrentTime) {
  17978. if (lastCurrentTime) {
  17979. this.ended = 0;
  17980. }
  17981. this.moved = true;
  17982. if (!seeking) {
  17983. this.nudgeRetry = 0;
  17984. // When crossing between buffered video time ranges, but not audio, flush pipeline with seek (Chrome)
  17985. if (config.nudgeOnVideoHole && !pausedEndedOrHalted && currentTime > lastCurrentTime) {
  17986. this.nudgeOnVideoHole(currentTime, lastCurrentTime);
  17987. }
  17988. }
  17989. if (this.waiting === 0) {
  17990. this.stallResolved(currentTime);
  17991. }
  17992. return;
  17993. }
  17994. // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek
  17995. if (beginSeek || seeked) {
  17996. if (seeked) {
  17997. this.stallResolved(currentTime);
  17998. }
  17999. return;
  18000. }
  18001. // The playhead should not be moving
  18002. if (pausedEndedOrHalted) {
  18003. this.nudgeRetry = 0;
  18004. this.stallResolved(currentTime);
  18005. // Fire MEDIA_ENDED to workaround event not being dispatched by browser
  18006. if (!this.ended && media.ended && this.hls) {
  18007. this.ended = currentTime || 1;
  18008. this.hls.trigger(Events.MEDIA_ENDED, {
  18009. stalled: false
  18010. });
  18011. }
  18012. return;
  18013. }
  18014. if (!BufferHelper.getBuffered(media).length) {
  18015. this.nudgeRetry = 0;
  18016. return;
  18017. }
  18018. // Resolve stalls at buffer holes using the main buffer, whose ranges are the intersections of the A/V sourcebuffers
  18019. var bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  18020. var nextStart = bufferInfo.nextStart || 0;
  18021. var fragmentTracker = this.fragmentTracker;
  18022. if (seeking && fragmentTracker && this.hls) {
  18023. // Is there a fragment loading/parsing/appending before currentTime?
  18024. var inFlightDependency = getInFlightDependency(this.hls.inFlightFragments, currentTime);
  18025. // Waiting for seeking in a buffered range to complete
  18026. var hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP;
  18027. // Next buffered range is too far ahead to jump to while still seeking
  18028. var noBufferHole = !nextStart || inFlightDependency || nextStart - currentTime > MAX_START_GAP_JUMP && !fragmentTracker.getPartialFragment(currentTime);
  18029. if (hasEnoughBuffer || noBufferHole) {
  18030. return;
  18031. }
  18032. // Reset moved state when seeking to a point in or before a gap/hole
  18033. this.moved = false;
  18034. }
  18035. // Skip start gaps if we haven't played, but the last poll detected the start of a stall
  18036. // The addition poll gives the browser a chance to jump the gap for us
  18037. var levelDetails = (_this$hls2 = this.hls) == null ? void 0 : _this$hls2.latestLevelDetails;
  18038. if (!this.moved && this.stalled !== null && fragmentTracker) {
  18039. // There is no playable buffer (seeked, waiting for buffer)
  18040. var isBuffered = bufferInfo.len > 0;
  18041. if (!isBuffered && !nextStart) {
  18042. return;
  18043. }
  18044. // Jump start gaps within jump threshold
  18045. var startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime;
  18046. // When joining a live stream with audio tracks, account for live playlist window sliding by allowing
  18047. // a larger jump over start gaps caused by the audio-stream-controller buffering a start fragment
  18048. // that begins over 1 target duration after the video start position.
  18049. var isLive = !!(levelDetails != null && levelDetails.live);
  18050. var maxStartGapJump = isLive ? levelDetails.targetduration * 2 : MAX_START_GAP_JUMP;
  18051. var partialOrGap = fragmentTracker.getPartialFragment(currentTime);
  18052. if (startJump > 0 && (startJump <= maxStartGapJump || partialOrGap)) {
  18053. if (!media.paused) {
  18054. this._trySkipBufferHole(partialOrGap);
  18055. }
  18056. return;
  18057. }
  18058. }
  18059. // Start tracking stall time
  18060. var detectStallWithCurrentTimeMs = config.detectStallWithCurrentTimeMs;
  18061. var tnow = self.performance.now();
  18062. var tWaiting = this.waiting;
  18063. var stalled = this.stalled;
  18064. if (stalled === null) {
  18065. // Use time of recent "waiting" event
  18066. if (tWaiting > 0 && tnow - tWaiting < detectStallWithCurrentTimeMs) {
  18067. stalled = this.stalled = tWaiting;
  18068. } else {
  18069. this.stalled = tnow;
  18070. return;
  18071. }
  18072. }
  18073. var stalledDuration = tnow - stalled;
  18074. if (!seeking && (stalledDuration >= detectStallWithCurrentTimeMs || tWaiting) && this.hls) {
  18075. var _this$mediaSource;
  18076. // Dispatch MEDIA_ENDED when media.ended/ended event is not signalled at end of stream
  18077. if (((_this$mediaSource = this.mediaSource) == null ? void 0 : _this$mediaSource.readyState) === 'ended' && !(levelDetails != null && levelDetails.live) && Math.abs(currentTime - ((levelDetails == null ? void 0 : levelDetails.edge) || 0)) < 1) {
  18078. if (this.ended) {
  18079. return;
  18080. }
  18081. this.ended = currentTime || 1;
  18082. this.hls.trigger(Events.MEDIA_ENDED, {
  18083. stalled: true
  18084. });
  18085. return;
  18086. }
  18087. // Report stalling after trying to fix
  18088. this._reportStall(bufferInfo);
  18089. if (!this.media || !this.hls) {
  18090. return;
  18091. }
  18092. }
  18093. var bufferedWithHoles = BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);
  18094. this._tryFixBufferStall(bufferedWithHoles, stalledDuration, currentTime);
  18095. };
  18096. _proto.stallResolved = function stallResolved(currentTime) {
  18097. var stalled = this.stalled;
  18098. if (stalled && this.hls) {
  18099. this.stalled = null;
  18100. // The playhead is now moving, but was previously stalled
  18101. if (this.stallReported) {
  18102. var stalledDuration = self.performance.now() - stalled;
  18103. this.log("playback not stuck anymore @" + currentTime + ", after " + Math.round(stalledDuration) + "ms");
  18104. this.stallReported = false;
  18105. this.waiting = 0;
  18106. this.hls.trigger(Events.STALL_RESOLVED, {});
  18107. }
  18108. }
  18109. };
  18110. _proto.nudgeOnVideoHole = function nudgeOnVideoHole(currentTime, lastCurrentTime) {
  18111. var _this$buffered$audio;
  18112. // Chrome will play one second past a hole in video buffered time ranges without rendering any video from the subsequent range and then stall as long as audio is buffered:
  18113. // https://github.com/video-dev/hls.js/issues/5631
  18114. // https://issues.chromium.org/issues/40280613#comment10
  18115. // Detect the potential for this situation and proactively seek to flush the video pipeline once the playhead passes the start of the video hole.
  18116. // When there are audio and video buffers and currentTime is past the end of the first video buffered range...
  18117. var videoSourceBuffered = this.buffered.video;
  18118. if (this.hls && this.media && this.fragmentTracker && (_this$buffered$audio = this.buffered.audio) != null && _this$buffered$audio.length && videoSourceBuffered && videoSourceBuffered.length > 1 && currentTime > videoSourceBuffered.end(0)) {
  18119. // and audio is buffered at the playhead
  18120. var audioBufferInfo = BufferHelper.bufferedInfo(BufferHelper.timeRangesToArray(this.buffered.audio), currentTime, 0);
  18121. if (audioBufferInfo.len > 1 && lastCurrentTime >= audioBufferInfo.start) {
  18122. var videoTimes = BufferHelper.timeRangesToArray(videoSourceBuffered);
  18123. var lastBufferedIndex = BufferHelper.bufferedInfo(videoTimes, lastCurrentTime, 0).bufferedIndex;
  18124. // nudge when crossing into another video buffered range (hole).
  18125. if (lastBufferedIndex > -1 && lastBufferedIndex < videoTimes.length - 1) {
  18126. var bufferedIndex = BufferHelper.bufferedInfo(videoTimes, currentTime, 0).bufferedIndex;
  18127. var holeStart = videoTimes[lastBufferedIndex].end;
  18128. var holeEnd = videoTimes[lastBufferedIndex + 1].start;
  18129. if ((bufferedIndex === -1 || bufferedIndex > lastBufferedIndex) && holeEnd - holeStart < 1 &&
  18130. // `maxBufferHole` may be too small and setting it to 0 should not disable this feature
  18131. currentTime - holeStart < 2) {
  18132. var error = new Error("nudging playhead to flush pipeline after video hole. currentTime: " + currentTime + " hole: " + holeStart + " -> " + holeEnd + " buffered index: " + bufferedIndex);
  18133. this.warn(error.message);
  18134. // Magic number to flush the pipeline without interuption to audio playback:
  18135. this.media.currentTime += 0.000001;
  18136. var frag = this.fragmentTracker.getPartialFragment(currentTime) || undefined;
  18137. var bufferInfo = BufferHelper.bufferInfo(this.media, currentTime, 0);
  18138. this.hls.trigger(Events.ERROR, {
  18139. type: ErrorTypes.MEDIA_ERROR,
  18140. details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,
  18141. fatal: false,
  18142. error: error,
  18143. reason: error.message,
  18144. frag: frag,
  18145. buffer: bufferInfo.len,
  18146. bufferInfo: bufferInfo
  18147. });
  18148. }
  18149. }
  18150. }
  18151. }
  18152. }
  18153. /**
  18154. * Detects and attempts to fix known buffer stalling issues.
  18155. * @param bufferInfo - The properties of the current buffer.
  18156. * @param stalledDurationMs - The amount of time Hls.js has been stalling for.
  18157. * @private
  18158. */;
  18159. _proto._tryFixBufferStall = function _tryFixBufferStall(bufferInfo, stalledDurationMs, currentTime) {
  18160. var _this$hls3, _this$hls4;
  18161. var fragmentTracker = this.fragmentTracker,
  18162. media = this.media;
  18163. var config = (_this$hls3 = this.hls) == null ? void 0 : _this$hls3.config;
  18164. if (!media || !fragmentTracker || !config) {
  18165. return;
  18166. }
  18167. var levelDetails = (_this$hls4 = this.hls) == null ? void 0 : _this$hls4.latestLevelDetails;
  18168. var partial = fragmentTracker.getPartialFragment(currentTime);
  18169. if (partial || levelDetails != null && levelDetails.live && currentTime < levelDetails.fragmentStart) {
  18170. // Try to skip over the buffer hole caused by a partial fragment
  18171. // This method isn't limited by the size of the gap between buffered ranges
  18172. var targetTime = this._trySkipBufferHole(partial);
  18173. // we return here in this case, meaning
  18174. // the branch below only executes when we haven't seeked to a new position
  18175. if (targetTime || !this.media) {
  18176. return;
  18177. }
  18178. }
  18179. // if we haven't had to skip over a buffer hole of a partial fragment
  18180. // we may just have to "nudge" the playlist as the browser decoding/rendering engine
  18181. // needs to cross some sort of threshold covering all source-buffers content
  18182. // to start playing properly.
  18183. var bufferedRanges = bufferInfo.buffered;
  18184. var adjacentTraversal = this.adjacentTraversal(bufferInfo, currentTime);
  18185. if ((bufferedRanges && bufferedRanges.length > 1 && bufferInfo.len > config.maxBufferHole || bufferInfo.nextStart && (bufferInfo.nextStart - currentTime < config.maxBufferHole || adjacentTraversal)) && (stalledDurationMs > config.highBufferWatchdogPeriod * 1000 || this.waiting)) {
  18186. this.warn('Trying to nudge playhead over buffer-hole');
  18187. // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds
  18188. // We only try to jump the hole if it's under the configured size
  18189. this._tryNudgeBuffer(bufferInfo);
  18190. }
  18191. };
  18192. _proto.adjacentTraversal = function adjacentTraversal(bufferInfo, currentTime) {
  18193. var fragmentTracker = this.fragmentTracker;
  18194. var nextStart = bufferInfo.nextStart;
  18195. if (fragmentTracker && nextStart) {
  18196. var current = fragmentTracker.getFragAtPos(currentTime, PlaylistLevelType.MAIN);
  18197. var next = fragmentTracker.getFragAtPos(nextStart, PlaylistLevelType.MAIN);
  18198. if (current && next) {
  18199. return next.sn - current.sn < 2;
  18200. }
  18201. }
  18202. return false;
  18203. }
  18204. /**
  18205. * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.
  18206. * @param bufferLen - The playhead distance from the end of the current buffer segment.
  18207. * @private
  18208. */;
  18209. _proto._reportStall = function _reportStall(bufferInfo) {
  18210. var hls = this.hls,
  18211. media = this.media,
  18212. stallReported = this.stallReported,
  18213. stalled = this.stalled;
  18214. if (!stallReported && stalled !== null && media && hls) {
  18215. // Report stalled error once
  18216. this.stallReported = true;
  18217. var error = new Error("Playback stalling at @" + media.currentTime + " due to low buffer (" + stringify(bufferInfo) + ")");
  18218. this.warn(error.message);
  18219. hls.trigger(Events.ERROR, {
  18220. type: ErrorTypes.MEDIA_ERROR,
  18221. details: ErrorDetails.BUFFER_STALLED_ERROR,
  18222. fatal: false,
  18223. error: error,
  18224. buffer: bufferInfo.len,
  18225. bufferInfo: bufferInfo,
  18226. stalled: {
  18227. start: stalled
  18228. }
  18229. });
  18230. }
  18231. }
  18232. /**
  18233. * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
  18234. * @param partial - The partial fragment found at the current time (where playback is stalling).
  18235. * @private
  18236. */;
  18237. _proto._trySkipBufferHole = function _trySkipBufferHole(partial) {
  18238. var _this$hls5;
  18239. var fragmentTracker = this.fragmentTracker,
  18240. media = this.media;
  18241. var config = (_this$hls5 = this.hls) == null ? void 0 : _this$hls5.config;
  18242. if (!media || !fragmentTracker || !config) {
  18243. return 0;
  18244. }
  18245. // Check if currentTime is between unbuffered regions of partial fragments
  18246. var currentTime = media.currentTime;
  18247. var bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  18248. var startTime = currentTime < bufferInfo.start ? bufferInfo.start : bufferInfo.nextStart;
  18249. if (startTime && this.hls) {
  18250. var bufferStarved = bufferInfo.len <= config.maxBufferHole;
  18251. var waiting = bufferInfo.len > 0 && bufferInfo.len < 1 && media.readyState < 3;
  18252. var gapLength = startTime - currentTime;
  18253. if (gapLength > 0 && (bufferStarved || waiting)) {
  18254. // Only allow large gaps to be skipped if it is a start gap, or all fragments in skip range are partial
  18255. if (gapLength > config.maxBufferHole) {
  18256. var startGap = false;
  18257. if (currentTime === 0) {
  18258. var startFrag = fragmentTracker.getAppendedFrag(0, PlaylistLevelType.MAIN);
  18259. if (startFrag && startTime < startFrag.end) {
  18260. startGap = true;
  18261. }
  18262. }
  18263. if (!startGap) {
  18264. var startProvisioned = partial || fragmentTracker.getAppendedFrag(currentTime, PlaylistLevelType.MAIN);
  18265. if (startProvisioned) {
  18266. var _this$hls$loadLevelOb;
  18267. // Do not seek when selected variant playlist is unloaded
  18268. if (!((_this$hls$loadLevelOb = this.hls.loadLevelObj) != null && _this$hls$loadLevelOb.details)) {
  18269. return 0;
  18270. }
  18271. // Do not seek when required fragments are inflight or appending
  18272. var inFlightDependency = getInFlightDependency(this.hls.inFlightFragments, startTime);
  18273. if (inFlightDependency) {
  18274. return 0;
  18275. }
  18276. // Do not seek if we can't walk tracked fragments to end of gap
  18277. var moreToLoad = false;
  18278. var pos = startProvisioned.end;
  18279. while (pos < startTime) {
  18280. var provisioned = fragmentTracker.getAppendedFrag(pos, PlaylistLevelType.MAIN) || fragmentTracker.getPartialFragment(pos);
  18281. if (provisioned) {
  18282. pos += provisioned.duration;
  18283. } else {
  18284. moreToLoad = true;
  18285. break;
  18286. }
  18287. }
  18288. if (moreToLoad) {
  18289. return 0;
  18290. }
  18291. }
  18292. }
  18293. }
  18294. var targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);
  18295. this.warn("skipping hole, adjusting currentTime from " + currentTime + " to " + targetTime);
  18296. this.moved = true;
  18297. media.currentTime = targetTime;
  18298. if (!(partial != null && partial.gap)) {
  18299. var error = new Error("fragment loaded with buffer holes, seeking from " + currentTime + " to " + targetTime);
  18300. this.hls.trigger(Events.ERROR, {
  18301. type: ErrorTypes.MEDIA_ERROR,
  18302. details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,
  18303. fatal: false,
  18304. error: error,
  18305. reason: error.message,
  18306. frag: partial || undefined,
  18307. buffer: bufferInfo.len,
  18308. bufferInfo: bufferInfo
  18309. });
  18310. }
  18311. return targetTime;
  18312. }
  18313. }
  18314. return 0;
  18315. }
  18316. /**
  18317. * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
  18318. * @private
  18319. */;
  18320. _proto._tryNudgeBuffer = function _tryNudgeBuffer(bufferInfo) {
  18321. var hls = this.hls,
  18322. media = this.media,
  18323. nudgeRetry = this.nudgeRetry;
  18324. var config = hls == null ? void 0 : hls.config;
  18325. if (!media || !config) {
  18326. return 0;
  18327. }
  18328. var currentTime = media.currentTime;
  18329. this.nudgeRetry++;
  18330. if (nudgeRetry < config.nudgeMaxRetry) {
  18331. var targetTime = currentTime + (nudgeRetry + 1) * config.nudgeOffset;
  18332. // playback stalled in buffered area ... let's nudge currentTime to try to overcome this
  18333. var error = new Error("Nudging 'currentTime' from " + currentTime + " to " + targetTime);
  18334. this.warn(error.message);
  18335. media.currentTime = targetTime;
  18336. hls.trigger(Events.ERROR, {
  18337. type: ErrorTypes.MEDIA_ERROR,
  18338. details: ErrorDetails.BUFFER_NUDGE_ON_STALL,
  18339. error: error,
  18340. fatal: false,
  18341. buffer: bufferInfo.len,
  18342. bufferInfo: bufferInfo
  18343. });
  18344. } else {
  18345. var _error = new Error("Playhead still not moving while enough data buffered @" + currentTime + " after " + config.nudgeMaxRetry + " nudges");
  18346. this.error(_error.message);
  18347. hls.trigger(Events.ERROR, {
  18348. type: ErrorTypes.MEDIA_ERROR,
  18349. details: ErrorDetails.BUFFER_STALLED_ERROR,
  18350. error: _error,
  18351. fatal: true,
  18352. buffer: bufferInfo.len,
  18353. bufferInfo: bufferInfo
  18354. });
  18355. }
  18356. };
  18357. return _createClass(GapController, [{
  18358. key: "hasBuffered",
  18359. get: function get() {
  18360. return Object.keys(this.buffered).length > 0;
  18361. }
  18362. }]);
  18363. }(TaskLoop);
  18364. function getInFlightDependency(inFlightFragments, currentTime) {
  18365. var main = inFlight(inFlightFragments.main);
  18366. if (main && main.start <= currentTime) {
  18367. return main;
  18368. }
  18369. var audio = inFlight(inFlightFragments.audio);
  18370. if (audio && audio.start <= currentTime) {
  18371. return audio;
  18372. }
  18373. return null;
  18374. }
  18375. function inFlight(inFlightData) {
  18376. if (!inFlightData) {
  18377. return null;
  18378. }
  18379. switch (inFlightData.state) {
  18380. case State.IDLE:
  18381. case State.STOPPED:
  18382. case State.ENDED:
  18383. case State.ERROR:
  18384. return null;
  18385. }
  18386. return inFlightData.frag;
  18387. }
  18388. function sendAddTrackEvent(track, videoEl) {
  18389. var event;
  18390. try {
  18391. event = new Event('addtrack');
  18392. } catch (err) {
  18393. // for IE11
  18394. event = document.createEvent('Event');
  18395. event.initEvent('addtrack', false, false);
  18396. }
  18397. event.track = track;
  18398. videoEl.dispatchEvent(event);
  18399. }
  18400. function clearCurrentCues(track, enterHandler) {
  18401. // When track.mode is disabled, track.cues will be null.
  18402. // To guarantee the removal of cues, we need to temporarily
  18403. // change the mode to hidden
  18404. var mode = track.mode;
  18405. if (mode === 'disabled') {
  18406. track.mode = 'hidden';
  18407. }
  18408. if (track.cues) {
  18409. for (var i = track.cues.length; i--;) {
  18410. if (enterHandler) {
  18411. track.cues[i].removeEventListener('enter', enterHandler);
  18412. }
  18413. track.removeCue(track.cues[i]);
  18414. }
  18415. }
  18416. if (mode === 'disabled') {
  18417. track.mode = mode;
  18418. }
  18419. }
  18420. function removeCuesInRange(track, start, end, predicate) {
  18421. var mode = track.mode;
  18422. if (mode === 'disabled') {
  18423. track.mode = 'hidden';
  18424. }
  18425. if (track.cues && track.cues.length > 0) {
  18426. var cues = getCuesInRange(track.cues, start, end);
  18427. for (var i = 0; i < cues.length; i++) {
  18428. if (!predicate || predicate(cues[i])) {
  18429. track.removeCue(cues[i]);
  18430. }
  18431. }
  18432. }
  18433. if (mode === 'disabled') {
  18434. track.mode = mode;
  18435. }
  18436. }
  18437. // Find first cue starting at or after given time.
  18438. // Modified version of binary search O(log(n)).
  18439. function getFirstCueIndexFromTime(cues, time) {
  18440. // If first cue starts at or after time, start there
  18441. if (time <= cues[0].startTime) {
  18442. return 0;
  18443. }
  18444. // If the last cue ends before time there is no overlap
  18445. var len = cues.length - 1;
  18446. if (time > cues[len].endTime) {
  18447. return -1;
  18448. }
  18449. var left = 0;
  18450. var right = len;
  18451. var mid;
  18452. while (left <= right) {
  18453. mid = Math.floor((right + left) / 2);
  18454. if (time < cues[mid].startTime) {
  18455. right = mid - 1;
  18456. } else if (time > cues[mid].startTime && left < len) {
  18457. left = mid + 1;
  18458. } else {
  18459. // If it's not lower or higher, it must be equal.
  18460. return mid;
  18461. }
  18462. }
  18463. // At this point, left and right have swapped.
  18464. // No direct match was found, left or right element must be the closest. Check which one has the smallest diff.
  18465. return cues[left].startTime - time < time - cues[right].startTime ? left : right;
  18466. }
  18467. function getCuesInRange(cues, start, end) {
  18468. var cuesFound = [];
  18469. var firstCueInRange = getFirstCueIndexFromTime(cues, start);
  18470. if (firstCueInRange > -1) {
  18471. for (var i = firstCueInRange, len = cues.length; i < len; i++) {
  18472. var cue = cues[i];
  18473. if (cue.startTime >= start && cue.endTime <= end) {
  18474. cuesFound.push(cue);
  18475. } else if (cue.startTime > end) {
  18476. return cuesFound;
  18477. }
  18478. }
  18479. }
  18480. return cuesFound;
  18481. }
  18482. var MIN_CUE_DURATION = 0.25;
  18483. function getCueClass() {
  18484. if (typeof self === 'undefined') return undefined;
  18485. return self.VTTCue || self.TextTrackCue;
  18486. }
  18487. function createCueWithDataFields(Cue, startTime, endTime, data, type) {
  18488. var cue = new Cue(startTime, endTime, '');
  18489. try {
  18490. cue.value = data;
  18491. if (type) {
  18492. cue.type = type;
  18493. }
  18494. } catch (e) {
  18495. cue = new Cue(startTime, endTime, stringify(type ? _objectSpread2({
  18496. type: type
  18497. }, data) : data));
  18498. }
  18499. return cue;
  18500. }
  18501. // VTTCue latest draft allows an infinite duration, fallback
  18502. // to MAX_VALUE if necessary
  18503. var MAX_CUE_ENDTIME = function () {
  18504. var Cue = getCueClass();
  18505. try {
  18506. Cue && new Cue(0, Number.POSITIVE_INFINITY, '');
  18507. } catch (e) {
  18508. return Number.MAX_VALUE;
  18509. }
  18510. return Number.POSITIVE_INFINITY;
  18511. }();
  18512. var ID3TrackController = /*#__PURE__*/function () {
  18513. function ID3TrackController(hls) {
  18514. var _this = this;
  18515. this.hls = void 0;
  18516. this.id3Track = null;
  18517. this.media = null;
  18518. this.dateRangeCuesAppended = {};
  18519. this.removeCues = true;
  18520. this.onEventCueEnter = function () {
  18521. if (!_this.hls) {
  18522. return;
  18523. }
  18524. _this.hls.trigger(Events.EVENT_CUE_ENTER, {});
  18525. };
  18526. this.hls = hls;
  18527. this._registerListeners();
  18528. }
  18529. var _proto = ID3TrackController.prototype;
  18530. _proto.destroy = function destroy() {
  18531. this._unregisterListeners();
  18532. this.id3Track = null;
  18533. this.media = null;
  18534. this.dateRangeCuesAppended = {};
  18535. // @ts-ignore
  18536. this.hls = this.onEventCueEnter = null;
  18537. };
  18538. _proto._registerListeners = function _registerListeners() {
  18539. var hls = this.hls;
  18540. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  18541. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  18542. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  18543. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  18544. hls.on(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  18545. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  18546. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  18547. hls.on(Events.LEVEL_PTS_UPDATED, this.onLevelPtsUpdated, this);
  18548. };
  18549. _proto._unregisterListeners = function _unregisterListeners() {
  18550. var hls = this.hls;
  18551. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  18552. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  18553. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  18554. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  18555. hls.off(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  18556. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  18557. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  18558. hls.off(Events.LEVEL_PTS_UPDATED, this.onLevelPtsUpdated, this);
  18559. };
  18560. // Add ID3 metatadata text track.
  18561. _proto.onMediaAttaching = function onMediaAttaching(event, data) {
  18562. var _data$overrides;
  18563. this.media = data.media;
  18564. if (((_data$overrides = data.overrides) == null ? void 0 : _data$overrides.cueRemoval) === false) {
  18565. this.removeCues = false;
  18566. }
  18567. };
  18568. _proto.onMediaAttached = function onMediaAttached() {
  18569. var details = this.hls.latestLevelDetails;
  18570. if (details) {
  18571. this.updateDateRangeCues(details);
  18572. }
  18573. };
  18574. _proto.onMediaDetaching = function onMediaDetaching(event, data) {
  18575. this.media = null;
  18576. var transferringMedia = !!data.transferMedia;
  18577. if (transferringMedia) {
  18578. return;
  18579. }
  18580. if (this.id3Track) {
  18581. if (this.removeCues) {
  18582. clearCurrentCues(this.id3Track, this.onEventCueEnter);
  18583. }
  18584. this.id3Track = null;
  18585. }
  18586. this.dateRangeCuesAppended = {};
  18587. };
  18588. _proto.onManifestLoading = function onManifestLoading() {
  18589. this.dateRangeCuesAppended = {};
  18590. };
  18591. _proto.createTrack = function createTrack(media) {
  18592. var track = this.getID3Track(media.textTracks);
  18593. track.mode = 'hidden';
  18594. return track;
  18595. };
  18596. _proto.getID3Track = function getID3Track(textTracks) {
  18597. if (!this.media) {
  18598. return;
  18599. }
  18600. for (var i = 0; i < textTracks.length; i++) {
  18601. var textTrack = textTracks[i];
  18602. if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {
  18603. // send 'addtrack' when reusing the textTrack for metadata,
  18604. // same as what we do for captions
  18605. sendAddTrackEvent(textTrack, this.media);
  18606. return textTrack;
  18607. }
  18608. }
  18609. return this.media.addTextTrack('metadata', 'id3');
  18610. };
  18611. _proto.onFragParsingMetadata = function onFragParsingMetadata(event, data) {
  18612. if (!this.media) {
  18613. return;
  18614. }
  18615. var _this$hls$config = this.hls.config,
  18616. enableEmsgMetadataCues = _this$hls$config.enableEmsgMetadataCues,
  18617. enableID3MetadataCues = _this$hls$config.enableID3MetadataCues;
  18618. if (!enableEmsgMetadataCues && !enableID3MetadataCues) {
  18619. return;
  18620. }
  18621. var samples = data.samples;
  18622. // create track dynamically
  18623. if (!this.id3Track) {
  18624. this.id3Track = this.createTrack(this.media);
  18625. }
  18626. var Cue = getCueClass();
  18627. if (!Cue) {
  18628. return;
  18629. }
  18630. for (var i = 0; i < samples.length; i++) {
  18631. var type = samples[i].type;
  18632. if (type === MetadataSchema.emsg && !enableEmsgMetadataCues || !enableID3MetadataCues) {
  18633. continue;
  18634. }
  18635. var frames = getId3Frames(samples[i].data);
  18636. if (frames) {
  18637. var startTime = samples[i].pts;
  18638. var endTime = startTime + samples[i].duration;
  18639. if (endTime > MAX_CUE_ENDTIME) {
  18640. endTime = MAX_CUE_ENDTIME;
  18641. }
  18642. var timeDiff = endTime - startTime;
  18643. if (timeDiff <= 0) {
  18644. endTime = startTime + MIN_CUE_DURATION;
  18645. }
  18646. for (var j = 0; j < frames.length; j++) {
  18647. var frame = frames[j];
  18648. // Safari doesn't put the timestamp frame in the TextTrack
  18649. if (!isId3TimestampFrame(frame)) {
  18650. // add a bounds to any unbounded cues
  18651. this.updateId3CueEnds(startTime, type);
  18652. var cue = createCueWithDataFields(Cue, startTime, endTime, frame, type);
  18653. if (cue) {
  18654. this.id3Track.addCue(cue);
  18655. }
  18656. }
  18657. }
  18658. }
  18659. }
  18660. };
  18661. _proto.updateId3CueEnds = function updateId3CueEnds(startTime, type) {
  18662. var _this$id3Track;
  18663. var cues = (_this$id3Track = this.id3Track) == null ? void 0 : _this$id3Track.cues;
  18664. if (cues) {
  18665. for (var i = cues.length; i--;) {
  18666. var cue = cues[i];
  18667. if (cue.type === type && cue.startTime < startTime && cue.endTime === MAX_CUE_ENDTIME) {
  18668. cue.endTime = startTime;
  18669. }
  18670. }
  18671. }
  18672. };
  18673. _proto.onBufferFlushing = function onBufferFlushing(event, _ref) {
  18674. var startOffset = _ref.startOffset,
  18675. endOffset = _ref.endOffset,
  18676. type = _ref.type;
  18677. var id3Track = this.id3Track,
  18678. hls = this.hls;
  18679. if (!hls) {
  18680. return;
  18681. }
  18682. var _hls$config = hls.config,
  18683. enableEmsgMetadataCues = _hls$config.enableEmsgMetadataCues,
  18684. enableID3MetadataCues = _hls$config.enableID3MetadataCues;
  18685. if (id3Track && (enableEmsgMetadataCues || enableID3MetadataCues)) {
  18686. var predicate;
  18687. if (type === 'audio') {
  18688. predicate = function predicate(cue) {
  18689. return cue.type === MetadataSchema.audioId3 && enableID3MetadataCues;
  18690. };
  18691. } else if (type === 'video') {
  18692. predicate = function predicate(cue) {
  18693. return cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  18694. };
  18695. } else {
  18696. predicate = function predicate(cue) {
  18697. return cue.type === MetadataSchema.audioId3 && enableID3MetadataCues || cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  18698. };
  18699. }
  18700. removeCuesInRange(id3Track, startOffset, endOffset, predicate);
  18701. }
  18702. };
  18703. _proto.onLevelUpdated = function onLevelUpdated(event, _ref2) {
  18704. var details = _ref2.details;
  18705. this.updateDateRangeCues(details, true);
  18706. };
  18707. _proto.onLevelPtsUpdated = function onLevelPtsUpdated(event, data) {
  18708. if (Math.abs(data.drift) > 0.01) {
  18709. this.updateDateRangeCues(data.details);
  18710. }
  18711. };
  18712. _proto.updateDateRangeCues = function updateDateRangeCues(details, removeOldCues) {
  18713. var _this2 = this;
  18714. if (!this.media || !details.hasProgramDateTime || !this.hls.config.enableDateRangeMetadataCues) {
  18715. return;
  18716. }
  18717. var id3Track = this.id3Track;
  18718. var dateRanges = details.dateRanges;
  18719. var ids = Object.keys(dateRanges);
  18720. var dateRangeCuesAppended = this.dateRangeCuesAppended;
  18721. // Remove cues from track not found in details.dateRanges
  18722. if (id3Track && removeOldCues) {
  18723. var _id3Track$cues;
  18724. if ((_id3Track$cues = id3Track.cues) != null && _id3Track$cues.length) {
  18725. var idsToRemove = Object.keys(dateRangeCuesAppended).filter(function (id) {
  18726. return !ids.includes(id);
  18727. });
  18728. var _loop = function _loop() {
  18729. var id = idsToRemove[i];
  18730. var cues = dateRangeCuesAppended[id].cues;
  18731. delete dateRangeCuesAppended[id];
  18732. Object.keys(cues).forEach(function (key) {
  18733. try {
  18734. var cue = cues[key];
  18735. cue.removeEventListener('enter', _this2.onEventCueEnter);
  18736. id3Track.removeCue(cue);
  18737. } catch (e) {
  18738. /* no-op */
  18739. }
  18740. });
  18741. };
  18742. for (var i = idsToRemove.length; i--;) {
  18743. _loop();
  18744. }
  18745. } else {
  18746. dateRangeCuesAppended = this.dateRangeCuesAppended = {};
  18747. }
  18748. }
  18749. // Exit if the playlist does not have Date Ranges or does not have Program Date Time
  18750. var lastFragment = details.fragments[details.fragments.length - 1];
  18751. if (ids.length === 0 || !isFiniteNumber(lastFragment == null ? void 0 : lastFragment.programDateTime)) {
  18752. return;
  18753. }
  18754. if (!this.id3Track) {
  18755. this.id3Track = this.createTrack(this.media);
  18756. }
  18757. var Cue = getCueClass();
  18758. var _loop2 = function _loop2() {
  18759. var id = ids[_i];
  18760. var dateRange = dateRanges[id];
  18761. var startTime = dateRange.startTime;
  18762. // Process DateRanges to determine end-time (known DURATION, END-DATE, or END-ON-NEXT)
  18763. var appendedDateRangeCues = dateRangeCuesAppended[id];
  18764. var cues = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.cues) || {};
  18765. var durationKnown = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.durationKnown) || false;
  18766. var endTime = MAX_CUE_ENDTIME;
  18767. var duration = dateRange.duration,
  18768. endDate = dateRange.endDate;
  18769. if (endDate && duration !== null) {
  18770. endTime = startTime + duration;
  18771. durationKnown = true;
  18772. } else if (dateRange.endOnNext && !durationKnown) {
  18773. var nextDateRangeWithSameClass = ids.reduce(function (candidateDateRange, id) {
  18774. if (id !== dateRange.id) {
  18775. var otherDateRange = dateRanges[id];
  18776. if (otherDateRange.class === dateRange.class && otherDateRange.startDate > dateRange.startDate && (!candidateDateRange || dateRange.startDate < candidateDateRange.startDate)) {
  18777. return otherDateRange;
  18778. }
  18779. }
  18780. return candidateDateRange;
  18781. }, null);
  18782. if (nextDateRangeWithSameClass) {
  18783. endTime = nextDateRangeWithSameClass.startTime;
  18784. durationKnown = true;
  18785. }
  18786. }
  18787. // Create TextTrack Cues for each MetadataGroup Item (select DateRange attribute)
  18788. // This is to emulate Safari HLS playback handling of DateRange tags
  18789. var attributes = Object.keys(dateRange.attr);
  18790. for (var j = 0; j < attributes.length; j++) {
  18791. var key = attributes[j];
  18792. if (!isDateRangeCueAttribute(key)) {
  18793. continue;
  18794. }
  18795. var cue = cues[key];
  18796. if (cue) {
  18797. if (durationKnown && !appendedDateRangeCues.durationKnown) {
  18798. cue.endTime = endTime;
  18799. } else if (Math.abs(cue.startTime - startTime) > 0.01) {
  18800. cue.startTime = startTime;
  18801. cue.endTime = endTime;
  18802. }
  18803. } else if (Cue) {
  18804. var data = dateRange.attr[key];
  18805. if (isSCTE35Attribute(key)) {
  18806. data = hexToArrayBuffer(data);
  18807. }
  18808. var payload = {
  18809. key: key,
  18810. data: data
  18811. };
  18812. var _cue = createCueWithDataFields(Cue, startTime, endTime, payload, MetadataSchema.dateRange);
  18813. if (_cue) {
  18814. _cue.id = id;
  18815. _this2.id3Track.addCue(_cue);
  18816. cues[key] = _cue;
  18817. }
  18818. }
  18819. }
  18820. // Keep track of processed DateRanges by ID for updating cues with new DateRange tag attributes
  18821. dateRangeCuesAppended[id] = {
  18822. cues: cues,
  18823. dateRange: dateRange,
  18824. durationKnown: durationKnown
  18825. };
  18826. };
  18827. for (var _i = 0; _i < ids.length; _i++) {
  18828. _loop2();
  18829. }
  18830. };
  18831. return ID3TrackController;
  18832. }();
  18833. var LatencyController = /*#__PURE__*/function () {
  18834. function LatencyController(hls) {
  18835. var _this = this;
  18836. this.hls = void 0;
  18837. this.config = void 0;
  18838. this.media = null;
  18839. this.currentTime = 0;
  18840. this.stallCount = 0;
  18841. this._latency = null;
  18842. this._targetLatencyUpdated = false;
  18843. this.onTimeupdate = function () {
  18844. var media = _this.media;
  18845. var levelDetails = _this.levelDetails;
  18846. if (!media || !levelDetails) {
  18847. return;
  18848. }
  18849. _this.currentTime = media.currentTime;
  18850. var latency = _this.computeLatency();
  18851. if (latency === null) {
  18852. return;
  18853. }
  18854. _this._latency = latency;
  18855. // Adapt playbackRate to meet target latency in low-latency mode
  18856. var _this$config = _this.config,
  18857. lowLatencyMode = _this$config.lowLatencyMode,
  18858. maxLiveSyncPlaybackRate = _this$config.maxLiveSyncPlaybackRate;
  18859. if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1 || !levelDetails.live) {
  18860. return;
  18861. }
  18862. var targetLatency = _this.targetLatency;
  18863. if (targetLatency === null) {
  18864. return;
  18865. }
  18866. var distanceFromTarget = latency - targetLatency;
  18867. // Only adjust playbackRate when within one target duration of targetLatency
  18868. // and more than one second from under-buffering.
  18869. // Playback further than one target duration from target can be considered DVR playback.
  18870. var liveMinLatencyDuration = Math.min(_this.maxLatency, targetLatency + levelDetails.targetduration);
  18871. var inLiveRange = distanceFromTarget < liveMinLatencyDuration;
  18872. if (inLiveRange && distanceFromTarget > 0.05 && _this.forwardBufferLength > 1) {
  18873. var max = Math.min(2, Math.max(1.0, maxLiveSyncPlaybackRate));
  18874. var rate = Math.round(2 / (1 + Math.exp(-0.75 * distanceFromTarget - _this.edgeStalled)) * 20) / 20;
  18875. var playbackRate = Math.min(max, Math.max(1, rate));
  18876. _this.changeMediaPlaybackRate(media, playbackRate);
  18877. } else if (media.playbackRate !== 1 && media.playbackRate !== 0) {
  18878. _this.changeMediaPlaybackRate(media, 1);
  18879. }
  18880. };
  18881. this.hls = hls;
  18882. this.config = hls.config;
  18883. this.registerListeners();
  18884. }
  18885. var _proto = LatencyController.prototype;
  18886. _proto.destroy = function destroy() {
  18887. this.unregisterListeners();
  18888. this.onMediaDetaching();
  18889. this.hls = null;
  18890. };
  18891. _proto.registerListeners = function registerListeners() {
  18892. var hls = this.hls;
  18893. if (!hls) {
  18894. return;
  18895. }
  18896. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  18897. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  18898. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  18899. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  18900. hls.on(Events.ERROR, this.onError, this);
  18901. };
  18902. _proto.unregisterListeners = function unregisterListeners() {
  18903. var hls = this.hls;
  18904. if (!hls) {
  18905. return;
  18906. }
  18907. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  18908. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  18909. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  18910. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  18911. hls.off(Events.ERROR, this.onError, this);
  18912. };
  18913. _proto.onMediaAttached = function onMediaAttached(event, data) {
  18914. this.media = data.media;
  18915. this.media.addEventListener('timeupdate', this.onTimeupdate);
  18916. };
  18917. _proto.onMediaDetaching = function onMediaDetaching() {
  18918. if (this.media) {
  18919. this.media.removeEventListener('timeupdate', this.onTimeupdate);
  18920. this.media = null;
  18921. }
  18922. };
  18923. _proto.onManifestLoading = function onManifestLoading() {
  18924. this._latency = null;
  18925. this.stallCount = 0;
  18926. };
  18927. _proto.onLevelUpdated = function onLevelUpdated(event, _ref) {
  18928. var details = _ref.details;
  18929. if (details.advanced) {
  18930. this.onTimeupdate();
  18931. }
  18932. if (!details.live && this.media) {
  18933. this.media.removeEventListener('timeupdate', this.onTimeupdate);
  18934. }
  18935. };
  18936. _proto.onError = function onError(event, data) {
  18937. var _this$levelDetails;
  18938. if (data.details !== ErrorDetails.BUFFER_STALLED_ERROR) {
  18939. return;
  18940. }
  18941. this.stallCount++;
  18942. if (this.hls && (_this$levelDetails = this.levelDetails) != null && _this$levelDetails.live) {
  18943. this.hls.logger.warn('[latency-controller]: Stall detected, adjusting target latency');
  18944. }
  18945. };
  18946. _proto.changeMediaPlaybackRate = function changeMediaPlaybackRate(media, playbackRate) {
  18947. var _this$hls, _this$targetLatency;
  18948. if (media.playbackRate === playbackRate) {
  18949. return;
  18950. }
  18951. (_this$hls = this.hls) == null ? void 0 : _this$hls.logger.debug("[latency-controller]: latency=" + this.latency.toFixed(3) + ", targetLatency=" + ((_this$targetLatency = this.targetLatency) == null ? void 0 : _this$targetLatency.toFixed(3)) + ", forwardBufferLength=" + this.forwardBufferLength.toFixed(3) + ": adjusting playback rate from " + media.playbackRate + " to " + playbackRate);
  18952. media.playbackRate = playbackRate;
  18953. };
  18954. _proto.estimateLiveEdge = function estimateLiveEdge() {
  18955. var levelDetails = this.levelDetails;
  18956. if (levelDetails === null) {
  18957. return null;
  18958. }
  18959. return levelDetails.edge + levelDetails.age;
  18960. };
  18961. _proto.computeLatency = function computeLatency() {
  18962. var liveEdge = this.estimateLiveEdge();
  18963. if (liveEdge === null) {
  18964. return null;
  18965. }
  18966. return liveEdge - this.currentTime;
  18967. };
  18968. return _createClass(LatencyController, [{
  18969. key: "levelDetails",
  18970. get: function get() {
  18971. var _this$hls2;
  18972. return ((_this$hls2 = this.hls) == null ? void 0 : _this$hls2.latestLevelDetails) || null;
  18973. }
  18974. }, {
  18975. key: "latency",
  18976. get: function get() {
  18977. return this._latency || 0;
  18978. }
  18979. }, {
  18980. key: "maxLatency",
  18981. get: function get() {
  18982. var config = this.config;
  18983. if (config.liveMaxLatencyDuration !== undefined) {
  18984. return config.liveMaxLatencyDuration;
  18985. }
  18986. var levelDetails = this.levelDetails;
  18987. return levelDetails ? config.liveMaxLatencyDurationCount * levelDetails.targetduration : 0;
  18988. }
  18989. }, {
  18990. key: "targetLatency",
  18991. get: function get() {
  18992. var levelDetails = this.levelDetails;
  18993. if (levelDetails === null || this.hls === null) {
  18994. return null;
  18995. }
  18996. var holdBack = levelDetails.holdBack,
  18997. partHoldBack = levelDetails.partHoldBack,
  18998. targetduration = levelDetails.targetduration;
  18999. var _this$config2 = this.config,
  19000. liveSyncDuration = _this$config2.liveSyncDuration,
  19001. liveSyncDurationCount = _this$config2.liveSyncDurationCount,
  19002. lowLatencyMode = _this$config2.lowLatencyMode;
  19003. var userConfig = this.hls.userConfig;
  19004. var targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack;
  19005. if (this._targetLatencyUpdated || userConfig.liveSyncDuration || userConfig.liveSyncDurationCount || targetLatency === 0) {
  19006. targetLatency = liveSyncDuration !== undefined ? liveSyncDuration : liveSyncDurationCount * targetduration;
  19007. }
  19008. var maxLiveSyncOnStallIncrease = targetduration;
  19009. return targetLatency + Math.min(this.stallCount * this.config.liveSyncOnStallIncrease, maxLiveSyncOnStallIncrease);
  19010. },
  19011. set: function set(latency) {
  19012. this.stallCount = 0;
  19013. this.config.liveSyncDuration = latency;
  19014. this._targetLatencyUpdated = true;
  19015. }
  19016. }, {
  19017. key: "liveSyncPosition",
  19018. get: function get() {
  19019. var liveEdge = this.estimateLiveEdge();
  19020. var targetLatency = this.targetLatency;
  19021. if (liveEdge === null || targetLatency === null) {
  19022. return null;
  19023. }
  19024. var levelDetails = this.levelDetails;
  19025. if (levelDetails === null) {
  19026. return null;
  19027. }
  19028. var edge = levelDetails.edge;
  19029. var syncPosition = liveEdge - targetLatency - this.edgeStalled;
  19030. var min = edge - levelDetails.totalduration;
  19031. var max = edge - (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration);
  19032. return Math.min(Math.max(min, syncPosition), max);
  19033. }
  19034. }, {
  19035. key: "drift",
  19036. get: function get() {
  19037. var levelDetails = this.levelDetails;
  19038. if (levelDetails === null) {
  19039. return 1;
  19040. }
  19041. return levelDetails.drift;
  19042. }
  19043. }, {
  19044. key: "edgeStalled",
  19045. get: function get() {
  19046. var levelDetails = this.levelDetails;
  19047. if (levelDetails === null) {
  19048. return 0;
  19049. }
  19050. var maxLevelUpdateAge = (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration) * 3;
  19051. return Math.max(levelDetails.age - maxLevelUpdateAge, 0);
  19052. }
  19053. }, {
  19054. key: "forwardBufferLength",
  19055. get: function get() {
  19056. var media = this.media;
  19057. var levelDetails = this.levelDetails;
  19058. if (!media || !levelDetails) {
  19059. return 0;
  19060. }
  19061. var bufferedRanges = media.buffered.length;
  19062. return (bufferedRanges ? media.buffered.end(bufferedRanges - 1) : levelDetails.edge) - this.currentTime;
  19063. }
  19064. }]);
  19065. }();
  19066. var BasePlaylistController = /*#__PURE__*/function (_Logger) {
  19067. function BasePlaylistController(hls, logPrefix) {
  19068. var _this;
  19069. _this = _Logger.call(this, logPrefix, hls.logger) || this;
  19070. _this.hls = void 0;
  19071. _this.canLoad = false;
  19072. _this.timer = -1;
  19073. _this.hls = hls;
  19074. return _this;
  19075. }
  19076. _inheritsLoose(BasePlaylistController, _Logger);
  19077. var _proto = BasePlaylistController.prototype;
  19078. _proto.destroy = function destroy() {
  19079. this.clearTimer();
  19080. // @ts-ignore
  19081. this.hls = this.log = this.warn = null;
  19082. };
  19083. _proto.clearTimer = function clearTimer() {
  19084. if (this.timer !== -1) {
  19085. self.clearTimeout(this.timer);
  19086. this.timer = -1;
  19087. }
  19088. };
  19089. _proto.startLoad = function startLoad() {
  19090. this.canLoad = true;
  19091. this.loadPlaylist();
  19092. };
  19093. _proto.stopLoad = function stopLoad() {
  19094. this.canLoad = false;
  19095. this.clearTimer();
  19096. };
  19097. _proto.switchParams = function switchParams(playlistUri, previous, current) {
  19098. var renditionReports = previous == null ? void 0 : previous.renditionReports;
  19099. if (renditionReports) {
  19100. var foundIndex = -1;
  19101. for (var i = 0; i < renditionReports.length; i++) {
  19102. var attr = renditionReports[i];
  19103. var uri = void 0;
  19104. try {
  19105. uri = new self.URL(attr.URI, previous.url).href;
  19106. } catch (error) {
  19107. this.warn("Could not construct new URL for Rendition Report: " + error);
  19108. uri = attr.URI || '';
  19109. }
  19110. // Use exact match. Otherwise, the last partial match, if any, will be used
  19111. // (Playlist URI includes a query string that the Rendition Report does not)
  19112. if (uri === playlistUri) {
  19113. foundIndex = i;
  19114. break;
  19115. } else if (uri === playlistUri.substring(0, uri.length)) {
  19116. foundIndex = i;
  19117. }
  19118. }
  19119. if (foundIndex !== -1) {
  19120. var _attr = renditionReports[foundIndex];
  19121. var msn = parseInt(_attr['LAST-MSN']) || (previous == null ? void 0 : previous.lastPartSn);
  19122. var part = parseInt(_attr['LAST-PART']) || (previous == null ? void 0 : previous.lastPartIndex);
  19123. if (this.hls.config.lowLatencyMode) {
  19124. var currentGoal = Math.min(previous.age - previous.partTarget, previous.targetduration);
  19125. if (part >= 0 && currentGoal > previous.partTarget) {
  19126. part += 1;
  19127. }
  19128. }
  19129. var skip = current && getSkipValue(current);
  19130. return new HlsUrlParameters(msn, part >= 0 ? part : undefined, skip);
  19131. }
  19132. }
  19133. };
  19134. _proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {
  19135. // Loading is handled by the subclasses
  19136. this.clearTimer();
  19137. };
  19138. _proto.loadingPlaylist = function loadingPlaylist(playlist, hlsUrlParameters) {
  19139. // Loading is handled by the subclasses
  19140. this.clearTimer();
  19141. };
  19142. _proto.shouldLoadPlaylist = function shouldLoadPlaylist(playlist) {
  19143. return this.canLoad && !!playlist && !!playlist.url && (!playlist.details || playlist.details.live);
  19144. };
  19145. _proto.getUrlWithDirectives = function getUrlWithDirectives(uri, hlsUrlParameters) {
  19146. if (hlsUrlParameters) {
  19147. try {
  19148. return hlsUrlParameters.addDirectives(uri);
  19149. } catch (error) {
  19150. this.warn("Could not construct new URL with HLS Delivery Directives: " + error);
  19151. }
  19152. }
  19153. return uri;
  19154. };
  19155. _proto.playlistLoaded = function playlistLoaded(index, data, previousDetails) {
  19156. var details = data.details,
  19157. stats = data.stats;
  19158. // Set last updated date-time
  19159. var now = self.performance.now();
  19160. var elapsed = stats.loading.first ? Math.max(0, now - stats.loading.first) : 0;
  19161. details.advancedDateTime = Date.now() - elapsed;
  19162. // shift fragment starts with timelineOffset
  19163. var timelineOffset = this.hls.config.timelineOffset;
  19164. if (timelineOffset !== details.appliedTimelineOffset) {
  19165. var offset = Math.max(timelineOffset || 0, 0);
  19166. details.appliedTimelineOffset = offset;
  19167. details.fragments.forEach(function (frag) {
  19168. frag.start = frag.playlistOffset + offset;
  19169. });
  19170. }
  19171. // if current playlist is a live playlist, arm a timer to reload it
  19172. if (details.live || previousDetails != null && previousDetails.live) {
  19173. var levelOrTrack = 'levelInfo' in data ? data.levelInfo : data.track;
  19174. details.reloaded(previousDetails);
  19175. // Merge live playlists to adjust fragment starts and fill in delta playlist skipped segments
  19176. if (previousDetails && details.fragments.length > 0) {
  19177. mergeDetails(previousDetails, details);
  19178. var error = details.playlistParsingError;
  19179. if (error) {
  19180. this.warn(error);
  19181. var hls = this.hls;
  19182. if (!hls.config.ignorePlaylistParsingErrors) {
  19183. var _details$fragments$;
  19184. var networkDetails = data.networkDetails;
  19185. hls.trigger(Events.ERROR, {
  19186. type: ErrorTypes.NETWORK_ERROR,
  19187. details: ErrorDetails.LEVEL_PARSING_ERROR,
  19188. fatal: false,
  19189. url: details.url,
  19190. error: error,
  19191. reason: error.message,
  19192. level: data.level || undefined,
  19193. parent: (_details$fragments$ = details.fragments[0]) == null ? void 0 : _details$fragments$.type,
  19194. networkDetails: networkDetails,
  19195. stats: stats
  19196. });
  19197. return;
  19198. }
  19199. details.playlistParsingError = null;
  19200. }
  19201. }
  19202. if (details.requestScheduled === -1) {
  19203. details.requestScheduled = stats.loading.start;
  19204. }
  19205. var bufferInfo = this.hls.mainForwardBufferInfo;
  19206. var position = bufferInfo ? bufferInfo.end - bufferInfo.len : 0;
  19207. var distanceToLiveEdgeMs = (details.edge - position) * 1000;
  19208. var reloadInterval = computeReloadInterval(details, distanceToLiveEdgeMs);
  19209. if (details.requestScheduled + reloadInterval < now) {
  19210. details.requestScheduled = now;
  19211. } else {
  19212. details.requestScheduled += reloadInterval;
  19213. }
  19214. this.log("live playlist " + index + " " + (details.advanced ? 'REFRESHED ' + details.lastPartSn + '-' + details.lastPartIndex : details.updated ? 'UPDATED' : 'MISSED'));
  19215. if (!this.canLoad || !details.live) {
  19216. return;
  19217. }
  19218. var deliveryDirectives;
  19219. var msn = undefined;
  19220. var part = undefined;
  19221. if (details.canBlockReload && details.endSN && details.advanced) {
  19222. // Load level with LL-HLS delivery directives
  19223. var lowLatencyMode = this.hls.config.lowLatencyMode;
  19224. var lastPartSn = details.lastPartSn;
  19225. var endSn = details.endSN;
  19226. var lastPartIndex = details.lastPartIndex;
  19227. var hasParts = lastPartIndex !== -1;
  19228. var atLastPartOfSegment = lastPartSn === endSn;
  19229. if (hasParts) {
  19230. // When low latency mode is disabled, request the last part of the next segment
  19231. if (atLastPartOfSegment) {
  19232. msn = endSn + 1;
  19233. part = lowLatencyMode ? 0 : lastPartIndex;
  19234. } else {
  19235. msn = lastPartSn;
  19236. part = lowLatencyMode ? lastPartIndex + 1 : details.maxPartIndex;
  19237. }
  19238. } else {
  19239. msn = endSn + 1;
  19240. }
  19241. // Low-Latency CDN Tune-in: "age" header and time since load indicates we're behind by more than one part
  19242. // Update directives to obtain the Playlist that has the estimated additional duration of media
  19243. var lastAdvanced = details.age;
  19244. var cdnAge = lastAdvanced + details.ageHeader;
  19245. var currentGoal = Math.min(cdnAge - details.partTarget, details.targetduration * 1.5);
  19246. if (currentGoal > 0) {
  19247. if (cdnAge > details.targetduration * 3) {
  19248. // Omit segment and part directives when the last response was more than 3 target durations ago,
  19249. this.log("Playlist last advanced " + lastAdvanced.toFixed(2) + "s ago. Omitting segment and part directives.");
  19250. msn = undefined;
  19251. part = undefined;
  19252. } else if (previousDetails != null && previousDetails.tuneInGoal && cdnAge - details.partTarget > previousDetails.tuneInGoal) {
  19253. // If we attempted to get the next or latest playlist update, but currentGoal increased,
  19254. // then we either can't catchup, or the "age" header cannot be trusted.
  19255. this.warn("CDN Tune-in goal increased from: " + previousDetails.tuneInGoal + " to: " + currentGoal + " with playlist age: " + details.age);
  19256. currentGoal = 0;
  19257. } else {
  19258. var segments = Math.floor(currentGoal / details.targetduration);
  19259. msn += segments;
  19260. if (part !== undefined) {
  19261. var parts = Math.round(currentGoal % details.targetduration / details.partTarget);
  19262. part += parts;
  19263. }
  19264. this.log("CDN Tune-in age: " + details.ageHeader + "s last advanced " + lastAdvanced.toFixed(2) + "s goal: " + currentGoal + " skip sn " + segments + " to part " + part);
  19265. }
  19266. details.tuneInGoal = currentGoal;
  19267. }
  19268. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  19269. if (lowLatencyMode || !atLastPartOfSegment) {
  19270. details.requestScheduled = now;
  19271. this.loadingPlaylist(levelOrTrack, deliveryDirectives);
  19272. return;
  19273. }
  19274. } else if (details.canBlockReload || details.canSkipUntil) {
  19275. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  19276. }
  19277. if (deliveryDirectives && msn !== undefined && details.canBlockReload) {
  19278. details.requestScheduled = stats.loading.first + Math.max(reloadInterval - elapsed * 2, reloadInterval / 2);
  19279. }
  19280. this.scheduleLoading(levelOrTrack, deliveryDirectives, details);
  19281. } else {
  19282. this.clearTimer();
  19283. }
  19284. };
  19285. _proto.scheduleLoading = function scheduleLoading(levelOrTrack, deliveryDirectives, updatedDetails) {
  19286. var _this2 = this;
  19287. var details = updatedDetails || levelOrTrack.details;
  19288. if (!details) {
  19289. this.loadingPlaylist(levelOrTrack, deliveryDirectives);
  19290. return;
  19291. }
  19292. var now = self.performance.now();
  19293. var requestScheduled = details.requestScheduled;
  19294. if (now >= requestScheduled) {
  19295. this.loadingPlaylist(levelOrTrack, deliveryDirectives);
  19296. return;
  19297. }
  19298. var estimatedTimeUntilUpdate = requestScheduled - now;
  19299. this.log("reload live playlist " + (levelOrTrack.name || levelOrTrack.bitrate + 'bps') + " in " + Math.round(estimatedTimeUntilUpdate) + " ms");
  19300. this.clearTimer();
  19301. this.timer = self.setTimeout(function () {
  19302. return _this2.loadingPlaylist(levelOrTrack, deliveryDirectives);
  19303. }, estimatedTimeUntilUpdate);
  19304. };
  19305. _proto.getDeliveryDirectives = function getDeliveryDirectives(details, previousDeliveryDirectives, msn, part) {
  19306. var skip = getSkipValue(details);
  19307. if (previousDeliveryDirectives != null && previousDeliveryDirectives.skip && details.deltaUpdateFailed) {
  19308. msn = previousDeliveryDirectives.msn;
  19309. part = previousDeliveryDirectives.part;
  19310. skip = HlsSkip.No;
  19311. }
  19312. return new HlsUrlParameters(msn, part, skip);
  19313. };
  19314. _proto.checkRetry = function checkRetry(errorEvent) {
  19315. var _this3 = this;
  19316. var errorDetails = errorEvent.details;
  19317. var isTimeout = isTimeoutError(errorEvent);
  19318. var errorAction = errorEvent.errorAction;
  19319. var _ref = errorAction || {},
  19320. action = _ref.action,
  19321. _ref$retryCount = _ref.retryCount,
  19322. retryCount = _ref$retryCount === void 0 ? 0 : _ref$retryCount,
  19323. retryConfig = _ref.retryConfig;
  19324. var retry = !!errorAction && !!retryConfig && (action === NetworkErrorAction.RetryRequest || !errorAction.resolved && action === NetworkErrorAction.SendAlternateToPenaltyBox);
  19325. if (retry) {
  19326. var _errorEvent$context;
  19327. if (retryCount >= retryConfig.maxNumRetry) {
  19328. return false;
  19329. }
  19330. if (isTimeout && (_errorEvent$context = errorEvent.context) != null && _errorEvent$context.deliveryDirectives) {
  19331. // The LL-HLS request already timed out so retry immediately
  19332. this.warn("Retrying playlist loading " + (retryCount + 1) + "/" + retryConfig.maxNumRetry + " after \"" + errorDetails + "\" without delivery-directives");
  19333. this.loadPlaylist();
  19334. } else {
  19335. var delay = getRetryDelay(retryConfig, retryCount);
  19336. // Schedule level/track reload
  19337. this.clearTimer();
  19338. this.timer = self.setTimeout(function () {
  19339. return _this3.loadPlaylist();
  19340. }, delay);
  19341. this.warn("Retrying playlist loading " + (retryCount + 1) + "/" + retryConfig.maxNumRetry + " after \"" + errorDetails + "\" in " + delay + "ms");
  19342. }
  19343. // `levelRetry = true` used to inform other controllers that a retry is happening
  19344. errorEvent.levelRetry = true;
  19345. errorAction.resolved = true;
  19346. }
  19347. return retry;
  19348. };
  19349. return BasePlaylistController;
  19350. }(Logger);
  19351. var LevelController = /*#__PURE__*/function (_BasePlaylistControll) {
  19352. function LevelController(hls, contentSteeringController) {
  19353. var _this;
  19354. _this = _BasePlaylistControll.call(this, hls, 'level-controller') || this;
  19355. _this._levels = [];
  19356. _this._firstLevel = -1;
  19357. _this._maxAutoLevel = -1;
  19358. _this._startLevel = void 0;
  19359. _this.currentLevel = null;
  19360. _this.currentLevelIndex = -1;
  19361. _this.manualLevelIndex = -1;
  19362. _this.steering = void 0;
  19363. _this.onParsedComplete = void 0;
  19364. _this.steering = contentSteeringController;
  19365. _this._registerListeners();
  19366. return _this;
  19367. }
  19368. _inheritsLoose(LevelController, _BasePlaylistControll);
  19369. var _proto = LevelController.prototype;
  19370. _proto._registerListeners = function _registerListeners() {
  19371. var hls = this.hls;
  19372. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  19373. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  19374. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  19375. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  19376. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  19377. hls.on(Events.ERROR, this.onError, this);
  19378. };
  19379. _proto._unregisterListeners = function _unregisterListeners() {
  19380. var hls = this.hls;
  19381. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  19382. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  19383. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  19384. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  19385. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  19386. hls.off(Events.ERROR, this.onError, this);
  19387. };
  19388. _proto.destroy = function destroy() {
  19389. this._unregisterListeners();
  19390. this.steering = null;
  19391. this.resetLevels();
  19392. _BasePlaylistControll.prototype.destroy.call(this);
  19393. };
  19394. _proto.stopLoad = function stopLoad() {
  19395. var levels = this._levels;
  19396. // clean up live level details to force reload them, and reset load errors
  19397. levels.forEach(function (level) {
  19398. level.loadError = 0;
  19399. level.fragmentError = 0;
  19400. });
  19401. _BasePlaylistControll.prototype.stopLoad.call(this);
  19402. };
  19403. _proto.resetLevels = function resetLevels() {
  19404. this._startLevel = undefined;
  19405. this.manualLevelIndex = -1;
  19406. this.currentLevelIndex = -1;
  19407. this.currentLevel = null;
  19408. this._levels = [];
  19409. this._maxAutoLevel = -1;
  19410. };
  19411. _proto.onManifestLoading = function onManifestLoading(event, data) {
  19412. this.resetLevels();
  19413. };
  19414. _proto.onManifestLoaded = function onManifestLoaded(event, data) {
  19415. var _this2 = this;
  19416. var preferManagedMediaSource = this.hls.config.preferManagedMediaSource;
  19417. var levels = [];
  19418. var redundantSet = {};
  19419. var generatePathwaySet = {};
  19420. var resolutionFound = false;
  19421. var videoCodecFound = false;
  19422. var audioCodecFound = false;
  19423. data.levels.forEach(function (levelParsed) {
  19424. var attributes = levelParsed.attrs;
  19425. var audioCodec = levelParsed.audioCodec,
  19426. videoCodec = levelParsed.videoCodec;
  19427. if (audioCodec) {
  19428. // Returns empty and set to undefined for 'mp4a.40.34' with fallback to 'audio/mpeg' SourceBuffer
  19429. levelParsed.audioCodec = audioCodec = getCodecCompatibleName(audioCodec, preferManagedMediaSource) || undefined;
  19430. }
  19431. if (videoCodec) {
  19432. videoCodec = levelParsed.videoCodec = convertAVC1ToAVCOTI(videoCodec);
  19433. }
  19434. // only keep levels with supported audio/video codecs
  19435. var width = levelParsed.width,
  19436. height = levelParsed.height,
  19437. unknownCodecs = levelParsed.unknownCodecs;
  19438. var unknownUnsupportedCodecCount = unknownCodecs ? unknownCodecs.length : 0;
  19439. if (unknownCodecs) {
  19440. // Treat unknown codec as audio or video codec based on passing `isTypeSupported` check
  19441. // (allows for playback of any supported codec even if not indexed in utils/codecs)
  19442. for (var i = unknownUnsupportedCodecCount; i--;) {
  19443. var unknownCodec = unknownCodecs[i];
  19444. if (_this2.isAudioSupported(unknownCodec)) {
  19445. levelParsed.audioCodec = audioCodec = audioCodec ? audioCodec + "," + unknownCodec : unknownCodec;
  19446. unknownUnsupportedCodecCount--;
  19447. sampleEntryCodesISO.audio[audioCodec.substring(0, 4)] = 2;
  19448. } else if (_this2.isVideoSupported(unknownCodec)) {
  19449. levelParsed.videoCodec = videoCodec = videoCodec ? videoCodec + "," + unknownCodec : unknownCodec;
  19450. unknownUnsupportedCodecCount--;
  19451. sampleEntryCodesISO.video[videoCodec.substring(0, 4)] = 2;
  19452. }
  19453. }
  19454. }
  19455. resolutionFound || (resolutionFound = !!(width && height));
  19456. videoCodecFound || (videoCodecFound = !!videoCodec);
  19457. audioCodecFound || (audioCodecFound = !!audioCodec);
  19458. if (unknownUnsupportedCodecCount || audioCodec && !_this2.isAudioSupported(audioCodec) || videoCodec && !_this2.isVideoSupported(videoCodec)) {
  19459. _this2.log("Some or all CODECS not supported \"" + attributes.CODECS + "\"");
  19460. return;
  19461. }
  19462. var CODECS = attributes.CODECS,
  19463. FRAMERATE = attributes['FRAME-RATE'],
  19464. HDCP = attributes['HDCP-LEVEL'],
  19465. PATHWAY = attributes['PATHWAY-ID'],
  19466. RESOLUTION = attributes.RESOLUTION,
  19467. VIDEO_RANGE = attributes['VIDEO-RANGE'];
  19468. var contentSteeringPrefix = (PATHWAY || '.') + "-";
  19469. var levelKey = "" + contentSteeringPrefix + levelParsed.bitrate + "-" + RESOLUTION + "-" + FRAMERATE + "-" + CODECS + "-" + VIDEO_RANGE + "-" + HDCP;
  19470. if (!redundantSet[levelKey]) {
  19471. var level = _this2.createLevel(levelParsed);
  19472. redundantSet[levelKey] = level;
  19473. generatePathwaySet[levelKey] = 1;
  19474. levels.push(level);
  19475. } else if (redundantSet[levelKey].uri !== levelParsed.url && !levelParsed.attrs['PATHWAY-ID']) {
  19476. // Assign Pathway IDs to Redundant Streams (default Pathways is ".". Redundant Streams "..", "...", and so on.)
  19477. // Content Steering controller to handles Pathway fallback on error
  19478. var pathwayCount = generatePathwaySet[levelKey] += 1;
  19479. levelParsed.attrs['PATHWAY-ID'] = new Array(pathwayCount + 1).join('.');
  19480. var _level = _this2.createLevel(levelParsed);
  19481. redundantSet[levelKey] = _level;
  19482. levels.push(_level);
  19483. } else {
  19484. redundantSet[levelKey].addGroupId('audio', attributes.AUDIO);
  19485. redundantSet[levelKey].addGroupId('text', attributes.SUBTITLES);
  19486. }
  19487. });
  19488. this.filterAndSortMediaOptions(levels, data, resolutionFound, videoCodecFound, audioCodecFound);
  19489. };
  19490. _proto.createLevel = function createLevel(levelParsed) {
  19491. var level = new Level(levelParsed);
  19492. var supplemental = levelParsed.supplemental;
  19493. if (supplemental != null && supplemental.videoCodec && !this.isVideoSupported(supplemental.videoCodec)) {
  19494. var error = new Error("SUPPLEMENTAL-CODECS not supported \"" + supplemental.videoCodec + "\"");
  19495. this.log(error.message);
  19496. level.supportedResult = emptyExports.getUnsupportedResult(error, []);
  19497. }
  19498. return level;
  19499. };
  19500. _proto.isAudioSupported = function isAudioSupported(codec) {
  19501. return areCodecsMediaSourceSupported(codec, 'audio', this.hls.config.preferManagedMediaSource);
  19502. };
  19503. _proto.isVideoSupported = function isVideoSupported(codec) {
  19504. return areCodecsMediaSourceSupported(codec, 'video', this.hls.config.preferManagedMediaSource);
  19505. };
  19506. _proto.filterAndSortMediaOptions = function filterAndSortMediaOptions(filteredLevels, data, resolutionFound, videoCodecFound, audioCodecFound) {
  19507. var _this3 = this;
  19508. var audioTracks = [];
  19509. var subtitleTracks = [];
  19510. var levels = filteredLevels;
  19511. // remove audio-only and invalid video-range levels if we also have levels with video codecs or RESOLUTION signalled
  19512. if ((resolutionFound || videoCodecFound) && audioCodecFound) {
  19513. levels = levels.filter(function (_ref) {
  19514. var videoCodec = _ref.videoCodec,
  19515. videoRange = _ref.videoRange,
  19516. width = _ref.width,
  19517. height = _ref.height;
  19518. return (!!videoCodec || !!(width && height)) && isVideoRange(videoRange);
  19519. });
  19520. }
  19521. if (levels.length === 0) {
  19522. // Dispatch error after MANIFEST_LOADED is done propagating
  19523. Promise.resolve().then(function () {
  19524. if (_this3.hls) {
  19525. var message = 'no level with compatible codecs found in manifest';
  19526. var reason = message;
  19527. if (data.levels.length) {
  19528. reason = "one or more CODECS in variant not supported: " + stringify(data.levels.map(function (level) {
  19529. return level.attrs.CODECS;
  19530. }).filter(function (value, index, array) {
  19531. return array.indexOf(value) === index;
  19532. }));
  19533. _this3.warn(reason);
  19534. message += " (" + reason + ")";
  19535. }
  19536. var error = new Error(message);
  19537. _this3.hls.trigger(Events.ERROR, {
  19538. type: ErrorTypes.MEDIA_ERROR,
  19539. details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,
  19540. fatal: true,
  19541. url: data.url,
  19542. error: error,
  19543. reason: reason
  19544. });
  19545. }
  19546. });
  19547. return;
  19548. }
  19549. if (data.audioTracks) {
  19550. audioTracks = data.audioTracks.filter(function (track) {
  19551. return !track.audioCodec || _this3.isAudioSupported(track.audioCodec);
  19552. });
  19553. // Assign ids after filtering as array indices by group-id
  19554. assignTrackIdsByGroup(audioTracks);
  19555. }
  19556. if (data.subtitles) {
  19557. subtitleTracks = data.subtitles;
  19558. assignTrackIdsByGroup(subtitleTracks);
  19559. }
  19560. // start bitrate is the first bitrate of the manifest
  19561. var unsortedLevels = levels.slice(0);
  19562. // sort levels from lowest to highest
  19563. levels.sort(function (a, b) {
  19564. if (a.attrs['HDCP-LEVEL'] !== b.attrs['HDCP-LEVEL']) {
  19565. return (a.attrs['HDCP-LEVEL'] || '') > (b.attrs['HDCP-LEVEL'] || '') ? 1 : -1;
  19566. }
  19567. // sort on height before bitrate for cap-level-controller
  19568. if (resolutionFound && a.height !== b.height) {
  19569. return a.height - b.height;
  19570. }
  19571. if (a.frameRate !== b.frameRate) {
  19572. return a.frameRate - b.frameRate;
  19573. }
  19574. if (a.videoRange !== b.videoRange) {
  19575. return VideoRangeValues.indexOf(a.videoRange) - VideoRangeValues.indexOf(b.videoRange);
  19576. }
  19577. if (a.videoCodec !== b.videoCodec) {
  19578. var valueA = videoCodecPreferenceValue(a.videoCodec);
  19579. var valueB = videoCodecPreferenceValue(b.videoCodec);
  19580. if (valueA !== valueB) {
  19581. return valueB - valueA;
  19582. }
  19583. }
  19584. if (a.uri === b.uri && a.codecSet !== b.codecSet) {
  19585. var _valueA = codecsSetSelectionPreferenceValue(a.codecSet);
  19586. var _valueB = codecsSetSelectionPreferenceValue(b.codecSet);
  19587. if (_valueA !== _valueB) {
  19588. return _valueB - _valueA;
  19589. }
  19590. }
  19591. if (a.averageBitrate !== b.averageBitrate) {
  19592. return a.averageBitrate - b.averageBitrate;
  19593. }
  19594. return 0;
  19595. });
  19596. var firstLevelInPlaylist = unsortedLevels[0];
  19597. if (this.steering) {
  19598. levels = this.steering.filterParsedLevels(levels);
  19599. if (levels.length !== unsortedLevels.length) {
  19600. for (var i = 0; i < unsortedLevels.length; i++) {
  19601. if (unsortedLevels[i].pathwayId === levels[0].pathwayId) {
  19602. firstLevelInPlaylist = unsortedLevels[i];
  19603. break;
  19604. }
  19605. }
  19606. }
  19607. }
  19608. this._levels = levels;
  19609. // find index of first level in sorted levels
  19610. for (var _i = 0; _i < levels.length; _i++) {
  19611. if (levels[_i] === firstLevelInPlaylist) {
  19612. var _this$hls$userConfig;
  19613. this._firstLevel = _i;
  19614. var firstLevelBitrate = firstLevelInPlaylist.bitrate;
  19615. var bandwidthEstimate = this.hls.bandwidthEstimate;
  19616. this.log("manifest loaded, " + levels.length + " level(s) found, first bitrate: " + firstLevelBitrate);
  19617. // Update default bwe to first variant bitrate as long it has not been configured or set
  19618. if (((_this$hls$userConfig = this.hls.userConfig) == null ? void 0 : _this$hls$userConfig.abrEwmaDefaultEstimate) === undefined) {
  19619. var startingBwEstimate = Math.min(firstLevelBitrate, this.hls.config.abrEwmaDefaultEstimateMax);
  19620. if (startingBwEstimate > bandwidthEstimate && bandwidthEstimate === this.hls.abrEwmaDefaultEstimate) {
  19621. this.hls.bandwidthEstimate = startingBwEstimate;
  19622. }
  19623. }
  19624. break;
  19625. }
  19626. }
  19627. // Audio is only alternate if manifest include a URI along with the audio group tag,
  19628. // and this is not an audio-only stream where levels contain audio-only
  19629. var audioOnly = audioCodecFound && !videoCodecFound;
  19630. var config = this.hls.config;
  19631. var altAudioEnabled = !!(config.audioStreamController && config.audioTrackController);
  19632. var edata = {
  19633. levels: levels,
  19634. audioTracks: audioTracks,
  19635. subtitleTracks: subtitleTracks,
  19636. sessionData: data.sessionData,
  19637. sessionKeys: data.sessionKeys,
  19638. firstLevel: this._firstLevel,
  19639. stats: data.stats,
  19640. audio: audioCodecFound,
  19641. video: videoCodecFound,
  19642. altAudio: altAudioEnabled && !audioOnly && audioTracks.some(function (t) {
  19643. return !!t.url;
  19644. })
  19645. };
  19646. this.hls.trigger(Events.MANIFEST_PARSED, edata);
  19647. };
  19648. _proto.onError = function onError(event, data) {
  19649. if (data.fatal || !data.context) {
  19650. return;
  19651. }
  19652. if (data.context.type === PlaylistContextType.LEVEL && data.context.level === this.level) {
  19653. this.checkRetry(data);
  19654. }
  19655. }
  19656. // reset errors on the successful load of a fragment
  19657. ;
  19658. _proto.onFragBuffered = function onFragBuffered(event, _ref2) {
  19659. var frag = _ref2.frag;
  19660. if (frag !== undefined && frag.type === PlaylistLevelType.MAIN) {
  19661. var el = frag.elementaryStreams;
  19662. if (!Object.keys(el).some(function (type) {
  19663. return !!el[type];
  19664. })) {
  19665. return;
  19666. }
  19667. var level = this._levels[frag.level];
  19668. if (level != null && level.loadError) {
  19669. this.log("Resetting level error count of " + level.loadError + " on frag buffered");
  19670. level.loadError = 0;
  19671. }
  19672. }
  19673. };
  19674. _proto.onLevelLoaded = function onLevelLoaded(event, data) {
  19675. var _data$deliveryDirecti2;
  19676. var level = data.level,
  19677. details = data.details;
  19678. var curLevel = data.levelInfo;
  19679. if (!curLevel) {
  19680. var _data$deliveryDirecti;
  19681. this.warn("Invalid level index " + level);
  19682. if ((_data$deliveryDirecti = data.deliveryDirectives) != null && _data$deliveryDirecti.skip) {
  19683. details.deltaUpdateFailed = true;
  19684. }
  19685. return;
  19686. }
  19687. // only process level loaded events matching with expected level or prior to switch when media playlist is loaded directly
  19688. if (curLevel === this.currentLevel || data.withoutMultiVariant) {
  19689. // reset level load error counter on successful level loaded only if there is no issues with fragments
  19690. if (curLevel.fragmentError === 0) {
  19691. curLevel.loadError = 0;
  19692. }
  19693. // Ignore matching details populated by loading a Media Playlist directly
  19694. var previousDetails = curLevel.details;
  19695. if (previousDetails === data.details && previousDetails.advanced) {
  19696. previousDetails = undefined;
  19697. }
  19698. this.playlistLoaded(level, data, previousDetails);
  19699. } else if ((_data$deliveryDirecti2 = data.deliveryDirectives) != null && _data$deliveryDirecti2.skip) {
  19700. // received a delta playlist update that cannot be merged
  19701. details.deltaUpdateFailed = true;
  19702. }
  19703. };
  19704. _proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {
  19705. _BasePlaylistControll.prototype.loadPlaylist.call(this);
  19706. if (this.shouldLoadPlaylist(this.currentLevel)) {
  19707. this.scheduleLoading(this.currentLevel, hlsUrlParameters);
  19708. }
  19709. };
  19710. _proto.loadingPlaylist = function loadingPlaylist(currentLevel, hlsUrlParameters) {
  19711. _BasePlaylistControll.prototype.loadingPlaylist.call(this, currentLevel, hlsUrlParameters);
  19712. var url = this.getUrlWithDirectives(currentLevel.uri, hlsUrlParameters);
  19713. var currentLevelIndex = this.currentLevelIndex;
  19714. var pathwayId = currentLevel.attrs['PATHWAY-ID'];
  19715. var details = currentLevel.details;
  19716. var age = details == null ? void 0 : details.age;
  19717. this.log("Loading level index " + currentLevelIndex + ((hlsUrlParameters == null ? void 0 : hlsUrlParameters.msn) !== undefined ? ' at sn ' + hlsUrlParameters.msn + ' part ' + hlsUrlParameters.part : '') + (pathwayId ? ' Pathway ' + pathwayId : '') + (age && details.live ? ' age ' + age.toFixed(1) + (details.type ? ' ' + details.type || '' : '') : '') + " " + url);
  19718. this.hls.trigger(Events.LEVEL_LOADING, {
  19719. url: url,
  19720. level: currentLevelIndex,
  19721. levelInfo: currentLevel,
  19722. pathwayId: currentLevel.attrs['PATHWAY-ID'],
  19723. id: 0,
  19724. // Deprecated Level urlId
  19725. deliveryDirectives: hlsUrlParameters || null
  19726. });
  19727. };
  19728. _proto.removeLevel = function removeLevel(levelIndex) {
  19729. var _this4 = this,
  19730. _this$currentLevel;
  19731. if (this._levels.length === 1) {
  19732. return;
  19733. }
  19734. var levels = this._levels.filter(function (level, index) {
  19735. if (index !== levelIndex) {
  19736. return true;
  19737. }
  19738. if (_this4.steering) {
  19739. _this4.steering.removeLevel(level);
  19740. }
  19741. if (level === _this4.currentLevel) {
  19742. _this4.currentLevel = null;
  19743. _this4.currentLevelIndex = -1;
  19744. if (level.details) {
  19745. level.details.fragments.forEach(function (f) {
  19746. return f.level = -1;
  19747. });
  19748. }
  19749. }
  19750. return false;
  19751. });
  19752. reassignFragmentLevelIndexes(levels);
  19753. this._levels = levels;
  19754. if (this.currentLevelIndex > -1 && (_this$currentLevel = this.currentLevel) != null && _this$currentLevel.details) {
  19755. this.currentLevelIndex = this.currentLevel.details.fragments[0].level;
  19756. }
  19757. if (this.manualLevelIndex > -1) {
  19758. this.manualLevelIndex = this.currentLevelIndex;
  19759. }
  19760. var maxLevel = levels.length - 1;
  19761. this._firstLevel = Math.min(this._firstLevel, maxLevel);
  19762. if (this._startLevel) {
  19763. this._startLevel = Math.min(this._startLevel, maxLevel);
  19764. }
  19765. this.hls.trigger(Events.LEVELS_UPDATED, {
  19766. levels: levels
  19767. });
  19768. };
  19769. _proto.onLevelsUpdated = function onLevelsUpdated(event, _ref3) {
  19770. var levels = _ref3.levels;
  19771. this._levels = levels;
  19772. };
  19773. _proto.checkMaxAutoUpdated = function checkMaxAutoUpdated() {
  19774. var _this$hls = this.hls,
  19775. autoLevelCapping = _this$hls.autoLevelCapping,
  19776. maxAutoLevel = _this$hls.maxAutoLevel,
  19777. maxHdcpLevel = _this$hls.maxHdcpLevel;
  19778. if (this._maxAutoLevel !== maxAutoLevel) {
  19779. this._maxAutoLevel = maxAutoLevel;
  19780. this.hls.trigger(Events.MAX_AUTO_LEVEL_UPDATED, {
  19781. autoLevelCapping: autoLevelCapping,
  19782. levels: this.levels,
  19783. maxAutoLevel: maxAutoLevel,
  19784. minAutoLevel: this.hls.minAutoLevel,
  19785. maxHdcpLevel: maxHdcpLevel
  19786. });
  19787. }
  19788. };
  19789. return _createClass(LevelController, [{
  19790. key: "levels",
  19791. get: function get() {
  19792. if (this._levels.length === 0) {
  19793. return null;
  19794. }
  19795. return this._levels;
  19796. }
  19797. }, {
  19798. key: "loadLevelObj",
  19799. get: function get() {
  19800. return this.currentLevel;
  19801. }
  19802. }, {
  19803. key: "level",
  19804. get: function get() {
  19805. return this.currentLevelIndex;
  19806. },
  19807. set: function set(newLevel) {
  19808. var levels = this._levels;
  19809. if (levels.length === 0) {
  19810. return;
  19811. }
  19812. // check if level idx is valid
  19813. if (newLevel < 0 || newLevel >= levels.length) {
  19814. // invalid level id given, trigger error
  19815. var error = new Error('invalid level idx');
  19816. var fatal = newLevel < 0;
  19817. this.hls.trigger(Events.ERROR, {
  19818. type: ErrorTypes.OTHER_ERROR,
  19819. details: ErrorDetails.LEVEL_SWITCH_ERROR,
  19820. level: newLevel,
  19821. fatal: fatal,
  19822. error: error,
  19823. reason: error.message
  19824. });
  19825. if (fatal) {
  19826. return;
  19827. }
  19828. newLevel = Math.min(newLevel, levels.length - 1);
  19829. }
  19830. var lastLevelIndex = this.currentLevelIndex;
  19831. var lastLevel = this.currentLevel;
  19832. var lastPathwayId = lastLevel ? lastLevel.attrs['PATHWAY-ID'] : undefined;
  19833. var level = levels[newLevel];
  19834. var pathwayId = level.attrs['PATHWAY-ID'];
  19835. this.currentLevelIndex = newLevel;
  19836. this.currentLevel = level;
  19837. if (lastLevelIndex === newLevel && lastLevel && lastPathwayId === pathwayId) {
  19838. return;
  19839. }
  19840. this.log("Switching to level " + newLevel + " (" + (level.height ? level.height + 'p ' : '') + (level.videoRange ? level.videoRange + ' ' : '') + (level.codecSet ? level.codecSet + ' ' : '') + "@" + level.bitrate + ")" + (pathwayId ? ' with Pathway ' + pathwayId : '') + " from level " + lastLevelIndex + (lastPathwayId ? ' with Pathway ' + lastPathwayId : ''));
  19841. var levelSwitchingData = {
  19842. level: newLevel,
  19843. attrs: level.attrs,
  19844. details: level.details,
  19845. bitrate: level.bitrate,
  19846. averageBitrate: level.averageBitrate,
  19847. maxBitrate: level.maxBitrate,
  19848. realBitrate: level.realBitrate,
  19849. width: level.width,
  19850. height: level.height,
  19851. codecSet: level.codecSet,
  19852. audioCodec: level.audioCodec,
  19853. videoCodec: level.videoCodec,
  19854. audioGroups: level.audioGroups,
  19855. subtitleGroups: level.subtitleGroups,
  19856. loaded: level.loaded,
  19857. loadError: level.loadError,
  19858. fragmentError: level.fragmentError,
  19859. name: level.name,
  19860. id: level.id,
  19861. uri: level.uri,
  19862. url: level.url,
  19863. urlId: 0,
  19864. audioGroupIds: level.audioGroupIds,
  19865. textGroupIds: level.textGroupIds
  19866. };
  19867. this.hls.trigger(Events.LEVEL_SWITCHING, levelSwitchingData);
  19868. // check if we need to load playlist for this level
  19869. var levelDetails = level.details;
  19870. if (!levelDetails || levelDetails.live) {
  19871. // level not retrieved yet, or live playlist we need to (re)load it
  19872. var hlsUrlParameters = this.switchParams(level.uri, lastLevel == null ? void 0 : lastLevel.details, levelDetails);
  19873. this.loadPlaylist(hlsUrlParameters);
  19874. }
  19875. }
  19876. }, {
  19877. key: "manualLevel",
  19878. get: function get() {
  19879. return this.manualLevelIndex;
  19880. },
  19881. set: function set(newLevel) {
  19882. this.manualLevelIndex = newLevel;
  19883. if (this._startLevel === undefined) {
  19884. this._startLevel = newLevel;
  19885. }
  19886. if (newLevel !== -1) {
  19887. this.level = newLevel;
  19888. }
  19889. }
  19890. }, {
  19891. key: "firstLevel",
  19892. get: function get() {
  19893. return this._firstLevel;
  19894. },
  19895. set: function set(newLevel) {
  19896. this._firstLevel = newLevel;
  19897. }
  19898. }, {
  19899. key: "startLevel",
  19900. get: function get() {
  19901. // Setting hls.startLevel (this._startLevel) overrides config.startLevel
  19902. if (this._startLevel === undefined) {
  19903. var configStartLevel = this.hls.config.startLevel;
  19904. if (configStartLevel !== undefined) {
  19905. return configStartLevel;
  19906. }
  19907. return this.hls.firstAutoLevel;
  19908. }
  19909. return this._startLevel;
  19910. },
  19911. set: function set(newLevel) {
  19912. this._startLevel = newLevel;
  19913. }
  19914. }, {
  19915. key: "pathways",
  19916. get: function get() {
  19917. if (this.steering) {
  19918. return this.steering.pathways();
  19919. }
  19920. return [];
  19921. }
  19922. }, {
  19923. key: "pathwayPriority",
  19924. get: function get() {
  19925. if (this.steering) {
  19926. return this.steering.pathwayPriority;
  19927. }
  19928. return null;
  19929. },
  19930. set: function set(pathwayPriority) {
  19931. if (this.steering) {
  19932. var pathwaysList = this.steering.pathways();
  19933. var filteredPathwayPriority = pathwayPriority.filter(function (pathwayId) {
  19934. return pathwaysList.indexOf(pathwayId) !== -1;
  19935. });
  19936. if (pathwayPriority.length < 1) {
  19937. this.warn("pathwayPriority " + pathwayPriority + " should contain at least one pathway from list: " + pathwaysList);
  19938. return;
  19939. }
  19940. this.steering.pathwayPriority = filteredPathwayPriority;
  19941. }
  19942. }
  19943. }, {
  19944. key: "nextLoadLevel",
  19945. get: function get() {
  19946. if (this.manualLevelIndex !== -1) {
  19947. return this.manualLevelIndex;
  19948. } else {
  19949. return this.hls.nextAutoLevel;
  19950. }
  19951. },
  19952. set: function set(nextLevel) {
  19953. this.level = nextLevel;
  19954. if (this.manualLevelIndex === -1) {
  19955. this.hls.nextAutoLevel = nextLevel;
  19956. }
  19957. }
  19958. }]);
  19959. }(BasePlaylistController);
  19960. function assignTrackIdsByGroup(tracks) {
  19961. var groups = {};
  19962. tracks.forEach(function (track) {
  19963. var groupId = track.groupId || '';
  19964. track.id = groups[groupId] = groups[groupId] || 0;
  19965. groups[groupId]++;
  19966. });
  19967. }
  19968. var transmuxers = [];
  19969. if (typeof __IN_WORKER__ !== 'undefined' && __IN_WORKER__) {
  19970. startWorker();
  19971. }
  19972. function startWorker() {
  19973. self.addEventListener('message', function (ev) {
  19974. var data = ev.data;
  19975. var instanceNo = data.instanceNo;
  19976. if (instanceNo === undefined) {
  19977. return;
  19978. }
  19979. var transmuxer = transmuxers[instanceNo];
  19980. if (data.cmd === 'reset') {
  19981. delete transmuxers[data.resetNo];
  19982. if (transmuxer) {
  19983. transmuxer.destroy();
  19984. }
  19985. data.cmd = 'init';
  19986. }
  19987. if (data.cmd === 'init') {
  19988. var config = JSON.parse(data.config);
  19989. var observer = new EventEmitter();
  19990. observer.on(Events.FRAG_DECRYPTED, forwardMessage);
  19991. observer.on(Events.ERROR, forwardMessage);
  19992. var logger = enableLogs(config.debug, data.id);
  19993. forwardWorkerLogs(logger, instanceNo);
  19994. transmuxers[instanceNo] = new Transmuxer(observer, data.typeSupported, config, '', data.id, logger);
  19995. forwardMessage('init', null, instanceNo);
  19996. return;
  19997. }
  19998. if (!transmuxer) {
  19999. return;
  20000. }
  20001. switch (data.cmd) {
  20002. case 'configure':
  20003. {
  20004. transmuxer.configure(data.config);
  20005. break;
  20006. }
  20007. case 'demux':
  20008. {
  20009. var transmuxResult = transmuxer.push(data.data, data.decryptdata, data.chunkMeta, data.state);
  20010. if (isPromise(transmuxResult)) {
  20011. transmuxResult.then(function (data) {
  20012. emitTransmuxComplete(self, data, instanceNo);
  20013. }).catch(function (error) {
  20014. forwardMessage(Events.ERROR, {
  20015. instanceNo: instanceNo,
  20016. type: ErrorTypes.MEDIA_ERROR,
  20017. details: ErrorDetails.FRAG_PARSING_ERROR,
  20018. chunkMeta: data.chunkMeta,
  20019. fatal: false,
  20020. error: error,
  20021. err: error,
  20022. reason: "transmuxer-worker push error"
  20023. }, instanceNo);
  20024. });
  20025. } else {
  20026. emitTransmuxComplete(self, transmuxResult, instanceNo);
  20027. }
  20028. break;
  20029. }
  20030. case 'flush':
  20031. {
  20032. var chunkMeta = data.chunkMeta;
  20033. var _transmuxResult = transmuxer.flush(chunkMeta);
  20034. if (isPromise(_transmuxResult)) {
  20035. _transmuxResult.then(function (results) {
  20036. handleFlushResult(self, results, chunkMeta, instanceNo);
  20037. }).catch(function (error) {
  20038. forwardMessage(Events.ERROR, {
  20039. type: ErrorTypes.MEDIA_ERROR,
  20040. details: ErrorDetails.FRAG_PARSING_ERROR,
  20041. chunkMeta: data.chunkMeta,
  20042. fatal: false,
  20043. error: error,
  20044. err: error,
  20045. reason: "transmuxer-worker flush error"
  20046. }, instanceNo);
  20047. });
  20048. } else {
  20049. handleFlushResult(self, _transmuxResult, chunkMeta, instanceNo);
  20050. }
  20051. break;
  20052. }
  20053. }
  20054. });
  20055. }
  20056. function emitTransmuxComplete(self, transmuxResult, instanceNo) {
  20057. if (isEmptyResult(transmuxResult.remuxResult)) {
  20058. return false;
  20059. }
  20060. var transferable = [];
  20061. var _transmuxResult$remux = transmuxResult.remuxResult,
  20062. audio = _transmuxResult$remux.audio,
  20063. video = _transmuxResult$remux.video;
  20064. if (audio) {
  20065. addToTransferable(transferable, audio);
  20066. }
  20067. if (video) {
  20068. addToTransferable(transferable, video);
  20069. }
  20070. self.postMessage({
  20071. event: 'transmuxComplete',
  20072. data: transmuxResult,
  20073. instanceNo: instanceNo
  20074. }, transferable);
  20075. return true;
  20076. }
  20077. // Converts data to a transferable object https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast)
  20078. // in order to minimize message passing overhead
  20079. function addToTransferable(transferable, track) {
  20080. if (track.data1) {
  20081. transferable.push(track.data1.buffer);
  20082. }
  20083. if (track.data2) {
  20084. transferable.push(track.data2.buffer);
  20085. }
  20086. }
  20087. function handleFlushResult(self, results, chunkMeta, instanceNo) {
  20088. var parsed = results.reduce(function (parsed, result) {
  20089. return emitTransmuxComplete(self, result, instanceNo) || parsed;
  20090. }, false);
  20091. if (!parsed) {
  20092. // Emit at least one "transmuxComplete" message even if media is not found to update stream-controller state to PARSING
  20093. self.postMessage({
  20094. event: 'transmuxComplete',
  20095. data: results[0],
  20096. instanceNo: instanceNo
  20097. });
  20098. }
  20099. self.postMessage({
  20100. event: 'flush',
  20101. data: chunkMeta,
  20102. instanceNo: instanceNo
  20103. });
  20104. }
  20105. function forwardMessage(event, data, instanceNo) {
  20106. self.postMessage({
  20107. event: event,
  20108. data: data,
  20109. instanceNo: instanceNo
  20110. });
  20111. }
  20112. function forwardWorkerLogs(logger, instanceNo) {
  20113. var _loop = function _loop(logFn) {
  20114. logger[logFn] = function () {
  20115. var message = Array.prototype.join.call(arguments, ' ');
  20116. forwardMessage('workerLog', {
  20117. logType: logFn,
  20118. message: message
  20119. }, instanceNo);
  20120. };
  20121. };
  20122. for (var logFn in logger) {
  20123. _loop(logFn);
  20124. }
  20125. }
  20126. function isEmptyResult(remuxResult) {
  20127. return !remuxResult.audio && !remuxResult.video && !remuxResult.text && !remuxResult.id3 && !remuxResult.initSegment;
  20128. }
  20129. var version = "1.6.7";
  20130. // ensure the worker ends up in the bundle
  20131. // If the worker should not be included this gets aliased to empty.js
  20132. var workerStore = {};
  20133. function hasUMDWorker() {
  20134. return typeof __HLS_WORKER_BUNDLE__ === 'function';
  20135. }
  20136. function injectWorker() {
  20137. var workerContext = workerStore[version];
  20138. if (workerContext) {
  20139. workerContext.clientCount++;
  20140. return workerContext;
  20141. }
  20142. var blob = new self.Blob(["var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(" + __HLS_WORKER_BUNDLE__.toString() + ")(true);"], {
  20143. type: 'text/javascript'
  20144. });
  20145. var objectURL = self.URL.createObjectURL(blob);
  20146. var worker = new self.Worker(objectURL);
  20147. var result = {
  20148. worker: worker,
  20149. objectURL: objectURL,
  20150. clientCount: 1
  20151. };
  20152. workerStore[version] = result;
  20153. return result;
  20154. }
  20155. function loadWorker(path) {
  20156. var workerContext = workerStore[path];
  20157. if (workerContext) {
  20158. workerContext.clientCount++;
  20159. return workerContext;
  20160. }
  20161. var scriptURL = new self.URL(path, self.location.href).href;
  20162. var worker = new self.Worker(scriptURL);
  20163. var result = {
  20164. worker: worker,
  20165. scriptURL: scriptURL,
  20166. clientCount: 1
  20167. };
  20168. workerStore[path] = result;
  20169. return result;
  20170. }
  20171. function removeWorkerFromStore(path) {
  20172. var workerContext = workerStore[path || version];
  20173. if (workerContext) {
  20174. var clientCount = workerContext.clientCount--;
  20175. if (clientCount === 1) {
  20176. var worker = workerContext.worker,
  20177. objectURL = workerContext.objectURL;
  20178. delete workerStore[path || version];
  20179. if (objectURL) {
  20180. // revoke the Object URL that was used to create transmuxer worker, so as not to leak it
  20181. self.URL.revokeObjectURL(objectURL);
  20182. }
  20183. worker.terminate();
  20184. }
  20185. }
  20186. }
  20187. var transmuxerInstanceCount = 0;
  20188. var TransmuxerInterface = /*#__PURE__*/function () {
  20189. function TransmuxerInterface(_hls, id, onTransmuxComplete, onFlush) {
  20190. var _this = this;
  20191. this.error = null;
  20192. this.hls = void 0;
  20193. this.id = void 0;
  20194. this.instanceNo = transmuxerInstanceCount++;
  20195. this.observer = void 0;
  20196. this.frag = null;
  20197. this.part = null;
  20198. this.useWorker = void 0;
  20199. this.workerContext = null;
  20200. this.transmuxer = null;
  20201. this.onTransmuxComplete = void 0;
  20202. this.onFlush = void 0;
  20203. this.onWorkerMessage = function (event) {
  20204. var data = event.data;
  20205. var hls = _this.hls;
  20206. if (!hls || !(data != null && data.event) || data.instanceNo !== _this.instanceNo) {
  20207. return;
  20208. }
  20209. switch (data.event) {
  20210. case 'init':
  20211. {
  20212. var _this$workerContext;
  20213. var objectURL = (_this$workerContext = _this.workerContext) == null ? void 0 : _this$workerContext.objectURL;
  20214. if (objectURL) {
  20215. // revoke the Object URL that was used to create transmuxer worker, so as not to leak it
  20216. self.URL.revokeObjectURL(objectURL);
  20217. }
  20218. break;
  20219. }
  20220. case 'transmuxComplete':
  20221. {
  20222. _this.handleTransmuxComplete(data.data);
  20223. break;
  20224. }
  20225. case 'flush':
  20226. {
  20227. _this.onFlush(data.data);
  20228. break;
  20229. }
  20230. // pass logs from the worker thread to the main logger
  20231. case 'workerLog':
  20232. {
  20233. if (hls.logger[data.data.logType]) {
  20234. hls.logger[data.data.logType](data.data.message);
  20235. }
  20236. break;
  20237. }
  20238. default:
  20239. {
  20240. data.data = data.data || {};
  20241. data.data.frag = _this.frag;
  20242. data.data.part = _this.part;
  20243. data.data.id = _this.id;
  20244. hls.trigger(data.event, data.data);
  20245. break;
  20246. }
  20247. }
  20248. };
  20249. this.onWorkerError = function (event) {
  20250. if (!_this.hls) {
  20251. return;
  20252. }
  20253. var error = new Error(event.message + " (" + event.filename + ":" + event.lineno + ")");
  20254. _this.hls.config.enableWorker = false;
  20255. _this.hls.logger.warn("Error in \"" + _this.id + "\" Web Worker, fallback to inline");
  20256. _this.hls.trigger(Events.ERROR, {
  20257. type: ErrorTypes.OTHER_ERROR,
  20258. details: ErrorDetails.INTERNAL_EXCEPTION,
  20259. fatal: false,
  20260. event: 'demuxerWorker',
  20261. error: error
  20262. });
  20263. };
  20264. var config = _hls.config;
  20265. this.hls = _hls;
  20266. this.id = id;
  20267. this.useWorker = !!config.enableWorker;
  20268. this.onTransmuxComplete = onTransmuxComplete;
  20269. this.onFlush = onFlush;
  20270. var forwardMessage = function forwardMessage(ev, data) {
  20271. data = data || {};
  20272. data.frag = _this.frag || undefined;
  20273. if (ev === Events.ERROR) {
  20274. data = data;
  20275. data.parent = _this.id;
  20276. data.part = _this.part;
  20277. _this.error = data.error;
  20278. }
  20279. _this.hls.trigger(ev, data);
  20280. };
  20281. // forward events to main thread
  20282. this.observer = new EventEmitter();
  20283. this.observer.on(Events.FRAG_DECRYPTED, forwardMessage);
  20284. this.observer.on(Events.ERROR, forwardMessage);
  20285. var m2tsTypeSupported = getM2TSSupportedAudioTypes(config.preferManagedMediaSource);
  20286. if (this.useWorker && typeof Worker !== 'undefined') {
  20287. var logger = this.hls.logger;
  20288. var canCreateWorker = config.workerPath || hasUMDWorker();
  20289. if (canCreateWorker) {
  20290. try {
  20291. if (config.workerPath) {
  20292. logger.log("loading Web Worker " + config.workerPath + " for \"" + id + "\"");
  20293. this.workerContext = loadWorker(config.workerPath);
  20294. } else {
  20295. logger.log("injecting Web Worker for \"" + id + "\"");
  20296. this.workerContext = injectWorker();
  20297. }
  20298. var worker = this.workerContext.worker;
  20299. worker.addEventListener('message', this.onWorkerMessage);
  20300. worker.addEventListener('error', this.onWorkerError);
  20301. worker.postMessage({
  20302. instanceNo: this.instanceNo,
  20303. cmd: 'init',
  20304. typeSupported: m2tsTypeSupported,
  20305. id: id,
  20306. config: stringify(config)
  20307. });
  20308. } catch (err) {
  20309. logger.warn("Error setting up \"" + id + "\" Web Worker, fallback to inline", err);
  20310. this.terminateWorker();
  20311. this.error = null;
  20312. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, '', id, _hls.logger);
  20313. }
  20314. return;
  20315. }
  20316. }
  20317. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, '', id, _hls.logger);
  20318. }
  20319. var _proto = TransmuxerInterface.prototype;
  20320. _proto.reset = function reset() {
  20321. this.frag = null;
  20322. this.part = null;
  20323. if (this.workerContext) {
  20324. var instanceNo = this.instanceNo;
  20325. this.instanceNo = transmuxerInstanceCount++;
  20326. var config = this.hls.config;
  20327. var m2tsTypeSupported = getM2TSSupportedAudioTypes(config.preferManagedMediaSource);
  20328. this.workerContext.worker.postMessage({
  20329. instanceNo: this.instanceNo,
  20330. cmd: 'reset',
  20331. resetNo: instanceNo,
  20332. typeSupported: m2tsTypeSupported,
  20333. id: this.id,
  20334. config: stringify(config)
  20335. });
  20336. }
  20337. };
  20338. _proto.terminateWorker = function terminateWorker() {
  20339. if (this.workerContext) {
  20340. var worker = this.workerContext.worker;
  20341. this.workerContext = null;
  20342. worker.removeEventListener('message', this.onWorkerMessage);
  20343. worker.removeEventListener('error', this.onWorkerError);
  20344. removeWorkerFromStore(this.hls.config.workerPath);
  20345. }
  20346. };
  20347. _proto.destroy = function destroy() {
  20348. if (this.workerContext) {
  20349. this.terminateWorker();
  20350. // @ts-ignore
  20351. this.onWorkerMessage = this.onWorkerError = null;
  20352. } else {
  20353. var transmuxer = this.transmuxer;
  20354. if (transmuxer) {
  20355. transmuxer.destroy();
  20356. this.transmuxer = null;
  20357. }
  20358. }
  20359. var observer = this.observer;
  20360. if (observer) {
  20361. observer.removeAllListeners();
  20362. }
  20363. this.frag = null;
  20364. this.part = null;
  20365. // @ts-ignore
  20366. this.observer = null;
  20367. // @ts-ignore
  20368. this.hls = null;
  20369. };
  20370. _proto.push = function push(data, initSegmentData, audioCodec, videoCodec, frag, part, duration, accurateTimeOffset, chunkMeta, defaultInitPTS) {
  20371. var _frag$initSegment,
  20372. _lastFrag$initSegment,
  20373. _this2 = this;
  20374. chunkMeta.transmuxing.start = self.performance.now();
  20375. var instanceNo = this.instanceNo,
  20376. transmuxer = this.transmuxer;
  20377. var timeOffset = part ? part.start : frag.start;
  20378. // TODO: push "clear-lead" decrypt data for unencrypted fragments in streams with encrypted ones
  20379. var decryptdata = frag.decryptdata;
  20380. var lastFrag = this.frag;
  20381. var discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
  20382. var trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level);
  20383. var snDiff = lastFrag ? chunkMeta.sn - lastFrag.sn : -1;
  20384. var partDiff = this.part ? chunkMeta.part - this.part.index : -1;
  20385. var progressive = snDiff === 0 && chunkMeta.id > 1 && chunkMeta.id === (lastFrag == null ? void 0 : lastFrag.stats.chunkCount);
  20386. var contiguous = !trackSwitch && (snDiff === 1 || snDiff === 0 && (partDiff === 1 || progressive && partDiff <= 0));
  20387. var now = self.performance.now();
  20388. if (trackSwitch || snDiff || frag.stats.parsing.start === 0) {
  20389. frag.stats.parsing.start = now;
  20390. }
  20391. if (part && (partDiff || !contiguous)) {
  20392. part.stats.parsing.start = now;
  20393. }
  20394. var initSegmentChange = !(lastFrag && ((_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.url) === ((_lastFrag$initSegment = lastFrag.initSegment) == null ? void 0 : _lastFrag$initSegment.url));
  20395. var state = new TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange);
  20396. if (!contiguous || discontinuity || initSegmentChange) {
  20397. this.hls.logger.log("[transmuxer-interface]: Starting new transmux session for " + frag.type + " sn: " + chunkMeta.sn + (chunkMeta.part > -1 ? ' part: ' + chunkMeta.part : '') + " " + (this.id === PlaylistLevelType.MAIN ? 'level' : 'track') + ": " + chunkMeta.level + " id: " + chunkMeta.id + "\n discontinuity: " + discontinuity + "\n trackSwitch: " + trackSwitch + "\n contiguous: " + contiguous + "\n accurateTimeOffset: " + accurateTimeOffset + "\n timeOffset: " + timeOffset + "\n initSegmentChange: " + initSegmentChange);
  20398. var config = new TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPTS);
  20399. this.configureTransmuxer(config);
  20400. }
  20401. this.frag = frag;
  20402. this.part = part;
  20403. // Frags with sn of 'initSegment' are not transmuxed
  20404. if (this.workerContext) {
  20405. // post fragment payload as transferable objects for ArrayBuffer (no copy)
  20406. this.workerContext.worker.postMessage({
  20407. instanceNo: instanceNo,
  20408. cmd: 'demux',
  20409. data: data,
  20410. decryptdata: decryptdata,
  20411. chunkMeta: chunkMeta,
  20412. state: state
  20413. }, data instanceof ArrayBuffer ? [data] : []);
  20414. } else if (transmuxer) {
  20415. var transmuxResult = transmuxer.push(data, decryptdata, chunkMeta, state);
  20416. if (isPromise(transmuxResult)) {
  20417. transmuxResult.then(function (data) {
  20418. _this2.handleTransmuxComplete(data);
  20419. }).catch(function (error) {
  20420. _this2.transmuxerError(error, chunkMeta, 'transmuxer-interface push error');
  20421. });
  20422. } else {
  20423. this.handleTransmuxComplete(transmuxResult);
  20424. }
  20425. }
  20426. };
  20427. _proto.flush = function flush(chunkMeta) {
  20428. var _this3 = this;
  20429. chunkMeta.transmuxing.start = self.performance.now();
  20430. var instanceNo = this.instanceNo,
  20431. transmuxer = this.transmuxer;
  20432. if (this.workerContext) {
  20433. this.workerContext.worker.postMessage({
  20434. instanceNo: instanceNo,
  20435. cmd: 'flush',
  20436. chunkMeta: chunkMeta
  20437. });
  20438. } else if (transmuxer) {
  20439. var transmuxResult = transmuxer.flush(chunkMeta);
  20440. if (isPromise(transmuxResult)) {
  20441. transmuxResult.then(function (data) {
  20442. _this3.handleFlushResult(data, chunkMeta);
  20443. }).catch(function (error) {
  20444. _this3.transmuxerError(error, chunkMeta, 'transmuxer-interface flush error');
  20445. });
  20446. } else {
  20447. this.handleFlushResult(transmuxResult, chunkMeta);
  20448. }
  20449. }
  20450. };
  20451. _proto.transmuxerError = function transmuxerError(error, chunkMeta, reason) {
  20452. if (!this.hls) {
  20453. return;
  20454. }
  20455. this.error = error;
  20456. this.hls.trigger(Events.ERROR, {
  20457. type: ErrorTypes.MEDIA_ERROR,
  20458. details: ErrorDetails.FRAG_PARSING_ERROR,
  20459. chunkMeta: chunkMeta,
  20460. frag: this.frag || undefined,
  20461. part: this.part || undefined,
  20462. fatal: false,
  20463. error: error,
  20464. err: error,
  20465. reason: reason
  20466. });
  20467. };
  20468. _proto.handleFlushResult = function handleFlushResult(results, chunkMeta) {
  20469. var _this4 = this;
  20470. results.forEach(function (result) {
  20471. _this4.handleTransmuxComplete(result);
  20472. });
  20473. this.onFlush(chunkMeta);
  20474. };
  20475. _proto.configureTransmuxer = function configureTransmuxer(config) {
  20476. var instanceNo = this.instanceNo,
  20477. transmuxer = this.transmuxer;
  20478. if (this.workerContext) {
  20479. this.workerContext.worker.postMessage({
  20480. instanceNo: instanceNo,
  20481. cmd: 'configure',
  20482. config: config
  20483. });
  20484. } else if (transmuxer) {
  20485. transmuxer.configure(config);
  20486. }
  20487. };
  20488. _proto.handleTransmuxComplete = function handleTransmuxComplete(result) {
  20489. result.chunkMeta.transmuxing.end = self.performance.now();
  20490. this.onTransmuxComplete(result);
  20491. };
  20492. return TransmuxerInterface;
  20493. }();
  20494. function getSourceBuffer() {
  20495. return self.SourceBuffer || self.WebKitSourceBuffer;
  20496. }
  20497. function isMSESupported() {
  20498. var mediaSource = getMediaSource();
  20499. if (!mediaSource) {
  20500. return false;
  20501. }
  20502. // if SourceBuffer is exposed ensure its API is valid
  20503. // Older browsers do not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible
  20504. var sourceBuffer = getSourceBuffer();
  20505. return !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function';
  20506. }
  20507. function isSupported() {
  20508. if (!isMSESupported()) {
  20509. return false;
  20510. }
  20511. var mediaSource = getMediaSource();
  20512. return typeof (mediaSource == null ? void 0 : mediaSource.isTypeSupported) === 'function' && (['avc1.42E01E,mp4a.40.2', 'av01.0.01M.08', 'vp09.00.50.08'].some(function (codecsForVideoContainer) {
  20513. return mediaSource.isTypeSupported(mimeTypeForCodec(codecsForVideoContainer, 'video'));
  20514. }) || ['mp4a.40.2', 'fLaC'].some(function (codecForAudioContainer) {
  20515. return mediaSource.isTypeSupported(mimeTypeForCodec(codecForAudioContainer, 'audio'));
  20516. }));
  20517. }
  20518. function changeTypeSupported() {
  20519. var _sourceBuffer$prototy;
  20520. var sourceBuffer = getSourceBuffer();
  20521. return typeof (sourceBuffer == null ? void 0 : (_sourceBuffer$prototy = sourceBuffer.prototype) == null ? void 0 : _sourceBuffer$prototy.changeType) === 'function';
  20522. }
  20523. var TICK_INTERVAL = 100; // how often to tick in ms
  20524. var StreamController = /*#__PURE__*/function (_BaseStreamController) {
  20525. function StreamController(hls, fragmentTracker, keyLoader) {
  20526. var _this;
  20527. _this = _BaseStreamController.call(this, hls, fragmentTracker, keyLoader, 'stream-controller', PlaylistLevelType.MAIN) || this;
  20528. _this.audioCodecSwap = false;
  20529. _this.level = -1;
  20530. _this._forceStartLoad = false;
  20531. _this._hasEnoughToStart = false;
  20532. _this.altAudio = 0;
  20533. _this.audioOnly = false;
  20534. _this.fragPlaying = null;
  20535. _this.fragLastKbps = 0;
  20536. _this.couldBacktrack = false;
  20537. _this.backtrackFragment = null;
  20538. _this.audioCodecSwitch = false;
  20539. _this.videoBuffer = null;
  20540. _this.onMediaPlaying = function () {
  20541. // tick to speed up FRAG_CHANGED triggering
  20542. _this.tick();
  20543. };
  20544. _this.onMediaSeeked = function () {
  20545. var media = _this.media;
  20546. var currentTime = media ? media.currentTime : null;
  20547. if (currentTime === null || !isFiniteNumber(currentTime)) {
  20548. return;
  20549. }
  20550. _this.log("Media seeked to " + currentTime.toFixed(3));
  20551. // If seeked was issued before buffer was appended do not tick immediately
  20552. if (!_this.getBufferedFrag(currentTime)) {
  20553. return;
  20554. }
  20555. var bufferInfo = _this.getFwdBufferInfoAtPos(media, currentTime, PlaylistLevelType.MAIN, 0);
  20556. if (bufferInfo === null || bufferInfo.len === 0) {
  20557. _this.warn("Main forward buffer length at " + currentTime + " on \"seeked\" event " + (bufferInfo ? bufferInfo.len : 'empty') + ")");
  20558. return;
  20559. }
  20560. // tick to speed up FRAG_CHANGED triggering
  20561. _this.tick();
  20562. };
  20563. _this.registerListeners();
  20564. return _this;
  20565. }
  20566. _inheritsLoose(StreamController, _BaseStreamController);
  20567. var _proto = StreamController.prototype;
  20568. _proto.registerListeners = function registerListeners() {
  20569. _BaseStreamController.prototype.registerListeners.call(this);
  20570. var hls = this.hls;
  20571. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  20572. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  20573. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  20574. hls.on(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  20575. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  20576. hls.on(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  20577. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  20578. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  20579. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  20580. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  20581. };
  20582. _proto.unregisterListeners = function unregisterListeners() {
  20583. _BaseStreamController.prototype.unregisterListeners.call(this);
  20584. var hls = this.hls;
  20585. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  20586. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  20587. hls.off(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  20588. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  20589. hls.off(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  20590. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  20591. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  20592. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  20593. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  20594. };
  20595. _proto.onHandlerDestroying = function onHandlerDestroying() {
  20596. // @ts-ignore
  20597. this.onMediaPlaying = this.onMediaSeeked = null;
  20598. this.unregisterListeners();
  20599. _BaseStreamController.prototype.onHandlerDestroying.call(this);
  20600. };
  20601. _proto.startLoad = function startLoad(startPosition, skipSeekToStartPosition) {
  20602. if (this.levels) {
  20603. var lastCurrentTime = this.lastCurrentTime,
  20604. hls = this.hls;
  20605. this.stopLoad();
  20606. this.setInterval(TICK_INTERVAL);
  20607. this.level = -1;
  20608. if (!this.startFragRequested) {
  20609. // determine load level
  20610. var startLevel = hls.startLevel;
  20611. if (startLevel === -1) {
  20612. if (hls.config.testBandwidth && this.levels.length > 1) {
  20613. // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
  20614. startLevel = 0;
  20615. this.bitrateTest = true;
  20616. } else {
  20617. startLevel = hls.firstAutoLevel;
  20618. }
  20619. }
  20620. // set new level to playlist loader : this will trigger start level load
  20621. // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
  20622. hls.nextLoadLevel = startLevel;
  20623. this.level = hls.loadLevel;
  20624. this._hasEnoughToStart = !!skipSeekToStartPosition;
  20625. }
  20626. // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime
  20627. if (lastCurrentTime > 0 && startPosition === -1 && !skipSeekToStartPosition) {
  20628. this.log("Override startPosition with lastCurrentTime @" + lastCurrentTime.toFixed(3));
  20629. startPosition = lastCurrentTime;
  20630. }
  20631. this.state = State.IDLE;
  20632. this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;
  20633. this.startPosition = skipSeekToStartPosition ? -1 : startPosition;
  20634. this.tick();
  20635. } else {
  20636. this._forceStartLoad = true;
  20637. this.state = State.STOPPED;
  20638. }
  20639. };
  20640. _proto.stopLoad = function stopLoad() {
  20641. this._forceStartLoad = false;
  20642. _BaseStreamController.prototype.stopLoad.call(this);
  20643. };
  20644. _proto.doTick = function doTick() {
  20645. switch (this.state) {
  20646. case State.WAITING_LEVEL:
  20647. {
  20648. var levels = this.levels,
  20649. level = this.level;
  20650. var currentLevel = levels == null ? void 0 : levels[level];
  20651. var details = currentLevel == null ? void 0 : currentLevel.details;
  20652. if (details && (!details.live || this.levelLastLoaded === currentLevel && !this.waitForLive(currentLevel))) {
  20653. if (this.waitForCdnTuneIn(details)) {
  20654. break;
  20655. }
  20656. this.state = State.IDLE;
  20657. break;
  20658. } else if (this.hls.nextLoadLevel !== this.level) {
  20659. this.state = State.IDLE;
  20660. break;
  20661. }
  20662. break;
  20663. }
  20664. case State.FRAG_LOADING_WAITING_RETRY:
  20665. {
  20666. var _this$media;
  20667. var now = self.performance.now();
  20668. var retryDate = this.retryDate;
  20669. // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  20670. if (!retryDate || now >= retryDate || (_this$media = this.media) != null && _this$media.seeking) {
  20671. var _levels = this.levels,
  20672. _level = this.level;
  20673. var _currentLevel = _levels == null ? void 0 : _levels[_level];
  20674. this.resetStartWhenNotLoaded(_currentLevel || null);
  20675. this.state = State.IDLE;
  20676. }
  20677. }
  20678. break;
  20679. }
  20680. if (this.state === State.IDLE) {
  20681. this.doTickIdle();
  20682. }
  20683. this.onTickEnd();
  20684. };
  20685. _proto.onTickEnd = function onTickEnd() {
  20686. var _this$media2;
  20687. _BaseStreamController.prototype.onTickEnd.call(this);
  20688. if ((_this$media2 = this.media) != null && _this$media2.readyState && this.media.seeking === false) {
  20689. this.lastCurrentTime = this.media.currentTime;
  20690. }
  20691. this.checkFragmentChanged();
  20692. };
  20693. _proto.doTickIdle = function doTickIdle() {
  20694. var hls = this.hls,
  20695. levelLastLoaded = this.levelLastLoaded,
  20696. levels = this.levels,
  20697. media = this.media;
  20698. // if start level not parsed yet OR
  20699. // if video not attached AND start fragment already requested OR start frag prefetch not enabled
  20700. // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment
  20701. if (levelLastLoaded === null || !media && !this.primaryPrefetch && (this.startFragRequested || !hls.config.startFragPrefetch)) {
  20702. return;
  20703. }
  20704. // If the "main" level is audio-only but we are loading an alternate track in the same group, do not load anything
  20705. if (this.altAudio && this.audioOnly) {
  20706. return;
  20707. }
  20708. var level = this.buffering ? hls.nextLoadLevel : hls.loadLevel;
  20709. if (!(levels != null && levels[level])) {
  20710. return;
  20711. }
  20712. var levelInfo = levels[level];
  20713. // if buffer length is less than maxBufLen try to load a new fragment
  20714. var bufferInfo = this.getMainFwdBufferInfo();
  20715. if (bufferInfo === null) {
  20716. return;
  20717. }
  20718. var lastDetails = this.getLevelDetails();
  20719. if (lastDetails && this._streamEnded(bufferInfo, lastDetails)) {
  20720. var data = {};
  20721. if (this.altAudio === 2) {
  20722. data.type = 'video';
  20723. }
  20724. this.hls.trigger(Events.BUFFER_EOS, data);
  20725. this.state = State.ENDED;
  20726. return;
  20727. }
  20728. if (!this.buffering) {
  20729. return;
  20730. }
  20731. // set next load level : this will trigger a playlist load if needed
  20732. if (hls.loadLevel !== level && hls.manualLevel === -1) {
  20733. this.log("Adapting to level " + level + " from level " + this.level);
  20734. }
  20735. this.level = hls.nextLoadLevel = level;
  20736. var levelDetails = levelInfo.details;
  20737. // if level info not retrieved yet, switch state and wait for level retrieval
  20738. // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
  20739. // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
  20740. if (!levelDetails || this.state === State.WAITING_LEVEL || this.waitForLive(levelInfo)) {
  20741. this.level = level;
  20742. this.state = State.WAITING_LEVEL;
  20743. this.startFragRequested = false;
  20744. return;
  20745. }
  20746. var bufferLen = bufferInfo.len;
  20747. // 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
  20748. var maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate);
  20749. // Stay idle if we are still with buffer margins
  20750. if (bufferLen >= maxBufLen) {
  20751. return;
  20752. }
  20753. if (this.backtrackFragment && this.backtrackFragment.start > bufferInfo.end) {
  20754. this.backtrackFragment = null;
  20755. }
  20756. var targetBufferTime = this.backtrackFragment ? this.backtrackFragment.start : bufferInfo.end;
  20757. var frag = this.getNextFragment(targetBufferTime, levelDetails);
  20758. // Avoid backtracking by loading an earlier segment in streams with segments that do not start with a key frame (flagged by `couldBacktrack`)
  20759. if (this.couldBacktrack && !this.fragPrevious && frag && isMediaFragment(frag) && this.fragmentTracker.getState(frag) !== FragmentState.OK) {
  20760. var _this$backtrackFragme;
  20761. var backtrackSn = ((_this$backtrackFragme = this.backtrackFragment) != null ? _this$backtrackFragme : frag).sn;
  20762. var fragIdx = backtrackSn - levelDetails.startSN;
  20763. var backtrackFrag = levelDetails.fragments[fragIdx - 1];
  20764. if (backtrackFrag && frag.cc === backtrackFrag.cc) {
  20765. frag = backtrackFrag;
  20766. this.fragmentTracker.removeFragment(backtrackFrag);
  20767. }
  20768. } else if (this.backtrackFragment && bufferInfo.len) {
  20769. this.backtrackFragment = null;
  20770. }
  20771. // Avoid loop loading by using nextLoadPosition set for backtracking and skipping consecutive GAP tags
  20772. if (frag && this.isLoopLoading(frag, targetBufferTime)) {
  20773. var gapStart = frag.gap;
  20774. if (!gapStart) {
  20775. // Cleanup the fragment tracker before trying to find the next unbuffered fragment
  20776. var type = this.audioOnly && !this.altAudio ? ElementaryStreamTypes.AUDIO : ElementaryStreamTypes.VIDEO;
  20777. var mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  20778. if (mediaBuffer) {
  20779. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  20780. }
  20781. }
  20782. frag = this.getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen);
  20783. }
  20784. if (!frag) {
  20785. return;
  20786. }
  20787. if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) {
  20788. frag = frag.initSegment;
  20789. }
  20790. this.loadFragment(frag, levelInfo, targetBufferTime);
  20791. };
  20792. _proto.loadFragment = function loadFragment(frag, level, targetBufferTime) {
  20793. // Check if fragment is not loaded
  20794. var fragState = this.fragmentTracker.getState(frag);
  20795. if (fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
  20796. if (!isMediaFragment(frag)) {
  20797. this._loadInitSegment(frag, level);
  20798. } else if (this.bitrateTest) {
  20799. this.log("Fragment " + frag.sn + " of level " + frag.level + " is being downloaded to test bitrate and will not be buffered");
  20800. this._loadBitrateTestFrag(frag, level);
  20801. } else {
  20802. _BaseStreamController.prototype.loadFragment.call(this, frag, level, targetBufferTime);
  20803. }
  20804. } else {
  20805. this.clearTrackerIfNeeded(frag);
  20806. }
  20807. };
  20808. _proto.getBufferedFrag = function getBufferedFrag(position) {
  20809. return this.fragmentTracker.getBufferedFrag(position, PlaylistLevelType.MAIN);
  20810. };
  20811. _proto.followingBufferedFrag = function followingBufferedFrag(frag) {
  20812. if (frag) {
  20813. // try to get range of next fragment (500ms after this range)
  20814. return this.getBufferedFrag(frag.end + 0.5);
  20815. }
  20816. return null;
  20817. }
  20818. /*
  20819. on immediate level switch :
  20820. - pause playback if playing
  20821. - cancel any pending load request
  20822. - and trigger a buffer flush
  20823. */;
  20824. _proto.immediateLevelSwitch = function immediateLevelSwitch() {
  20825. this.abortCurrentFrag();
  20826. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  20827. }
  20828. /**
  20829. * try to switch ASAP without breaking video playback:
  20830. * in order to ensure smooth but quick level switching,
  20831. * we need to find the next flushable buffer range
  20832. * we should take into account new segment fetch time
  20833. */;
  20834. _proto.nextLevelSwitch = function nextLevelSwitch() {
  20835. var levels = this.levels,
  20836. media = this.media;
  20837. // ensure that media is defined and that metadata are available (to retrieve currentTime)
  20838. if (media != null && media.readyState) {
  20839. var fetchdelay;
  20840. var fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
  20841. if (fragPlayingCurrent && fragPlayingCurrent.start > 1) {
  20842. // flush buffer preceding current fragment (flush until current fragment start offset)
  20843. // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
  20844. this.flushMainBuffer(0, fragPlayingCurrent.start - 1);
  20845. }
  20846. var levelDetails = this.getLevelDetails();
  20847. if (levelDetails != null && levelDetails.live) {
  20848. var bufferInfo = this.getMainFwdBufferInfo();
  20849. // Do not flush in live stream with low buffer
  20850. if (!bufferInfo || bufferInfo.len < levelDetails.targetduration * 2) {
  20851. return;
  20852. }
  20853. }
  20854. if (!media.paused && levels) {
  20855. // add a safety delay of 1s
  20856. var nextLevelId = this.hls.nextLoadLevel;
  20857. var nextLevel = levels[nextLevelId];
  20858. var fragLastKbps = this.fragLastKbps;
  20859. if (fragLastKbps && this.fragCurrent) {
  20860. fetchdelay = this.fragCurrent.duration * nextLevel.maxBitrate / (1000 * fragLastKbps) + 1;
  20861. } else {
  20862. fetchdelay = 0;
  20863. }
  20864. } else {
  20865. fetchdelay = 0;
  20866. }
  20867. // this.log('fetchdelay:'+fetchdelay);
  20868. // find buffer range that will be reached once new fragment will be fetched
  20869. var bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
  20870. if (bufferedFrag) {
  20871. // we can flush buffer range following this one without stalling playback
  20872. var nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);
  20873. if (nextBufferedFrag) {
  20874. // if we are here, we can also cancel any loading/demuxing in progress, as they are useless
  20875. this.abortCurrentFrag();
  20876. // start flush position is in next buffered frag. Leave some padding for non-independent segments and smoother playback.
  20877. var maxStart = nextBufferedFrag.maxStartPTS ? nextBufferedFrag.maxStartPTS : nextBufferedFrag.start;
  20878. var fragDuration = nextBufferedFrag.duration;
  20879. var startPts = Math.max(bufferedFrag.end, maxStart + Math.min(Math.max(fragDuration - this.config.maxFragLookUpTolerance, fragDuration * (this.couldBacktrack ? 0.5 : 0.125)), fragDuration * (this.couldBacktrack ? 0.75 : 0.25)));
  20880. this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);
  20881. }
  20882. }
  20883. }
  20884. };
  20885. _proto.abortCurrentFrag = function abortCurrentFrag() {
  20886. var fragCurrent = this.fragCurrent;
  20887. this.fragCurrent = null;
  20888. this.backtrackFragment = null;
  20889. if (fragCurrent) {
  20890. fragCurrent.abortRequests();
  20891. this.fragmentTracker.removeFragment(fragCurrent);
  20892. }
  20893. switch (this.state) {
  20894. case State.KEY_LOADING:
  20895. case State.FRAG_LOADING:
  20896. case State.FRAG_LOADING_WAITING_RETRY:
  20897. case State.PARSING:
  20898. case State.PARSED:
  20899. this.state = State.IDLE;
  20900. break;
  20901. }
  20902. this.nextLoadPosition = this.getLoadPosition();
  20903. };
  20904. _proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset) {
  20905. _BaseStreamController.prototype.flushMainBuffer.call(this, startOffset, endOffset, this.altAudio === 2 ? 'video' : null);
  20906. };
  20907. _proto.onMediaAttached = function onMediaAttached(event, data) {
  20908. _BaseStreamController.prototype.onMediaAttached.call(this, event, data);
  20909. var media = data.media;
  20910. addEventListener(media, 'playing', this.onMediaPlaying);
  20911. addEventListener(media, 'seeked', this.onMediaSeeked);
  20912. };
  20913. _proto.onMediaDetaching = function onMediaDetaching(event, data) {
  20914. var media = this.media;
  20915. if (media) {
  20916. removeEventListener(media, 'playing', this.onMediaPlaying);
  20917. removeEventListener(media, 'seeked', this.onMediaSeeked);
  20918. }
  20919. this.videoBuffer = null;
  20920. this.fragPlaying = null;
  20921. _BaseStreamController.prototype.onMediaDetaching.call(this, event, data);
  20922. var transferringMedia = !!data.transferMedia;
  20923. if (transferringMedia) {
  20924. return;
  20925. }
  20926. this._hasEnoughToStart = false;
  20927. };
  20928. _proto.onManifestLoading = function onManifestLoading() {
  20929. _BaseStreamController.prototype.onManifestLoading.call(this);
  20930. // reset buffer on manifest loading
  20931. this.log('Trigger BUFFER_RESET');
  20932. this.hls.trigger(Events.BUFFER_RESET, undefined);
  20933. this.couldBacktrack = false;
  20934. this.fragLastKbps = 0;
  20935. this.fragPlaying = this.backtrackFragment = null;
  20936. this.altAudio = 0;
  20937. this.audioOnly = false;
  20938. };
  20939. _proto.onManifestParsed = function onManifestParsed(event, data) {
  20940. // detect if we have different kind of audio codecs used amongst playlists
  20941. var aac = false;
  20942. var heaac = false;
  20943. data.levels.forEach(function (level) {
  20944. var codec = level.audioCodec;
  20945. if (codec) {
  20946. aac = aac || codec.indexOf('mp4a.40.2') !== -1;
  20947. heaac = heaac || codec.indexOf('mp4a.40.5') !== -1;
  20948. }
  20949. });
  20950. this.audioCodecSwitch = aac && heaac && !changeTypeSupported();
  20951. if (this.audioCodecSwitch) {
  20952. this.log('Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
  20953. }
  20954. this.levels = data.levels;
  20955. this.startFragRequested = false;
  20956. };
  20957. _proto.onLevelLoading = function onLevelLoading(event, data) {
  20958. var levels = this.levels;
  20959. if (!levels || this.state !== State.IDLE) {
  20960. return;
  20961. }
  20962. var level = data.levelInfo;
  20963. if (!level.details || level.details.live && (this.levelLastLoaded !== level || level.details.expired) || this.waitForCdnTuneIn(level.details)) {
  20964. this.state = State.WAITING_LEVEL;
  20965. }
  20966. };
  20967. _proto.onLevelLoaded = function onLevelLoaded(event, data) {
  20968. var _curLevel$details;
  20969. var levels = this.levels,
  20970. startFragRequested = this.startFragRequested;
  20971. var newLevelId = data.level;
  20972. var newDetails = data.details;
  20973. var duration = newDetails.totalduration;
  20974. if (!levels) {
  20975. this.warn("Levels were reset while loading level " + newLevelId);
  20976. return;
  20977. }
  20978. this.log("Level " + newLevelId + " loaded [" + newDetails.startSN + "," + newDetails.endSN + "]" + (newDetails.lastPartSn ? "[part-" + newDetails.lastPartSn + "-" + newDetails.lastPartIndex + "]" : '') + ", cc [" + newDetails.startCC + ", " + newDetails.endCC + "] duration:" + duration);
  20979. var curLevel = data.levelInfo;
  20980. var fragCurrent = this.fragCurrent;
  20981. if (fragCurrent && (this.state === State.FRAG_LOADING || this.state === State.FRAG_LOADING_WAITING_RETRY)) {
  20982. if (fragCurrent.level !== data.level && fragCurrent.loader) {
  20983. this.abortCurrentFrag();
  20984. }
  20985. }
  20986. var sliding = 0;
  20987. if (newDetails.live || (_curLevel$details = curLevel.details) != null && _curLevel$details.live) {
  20988. var _this$levelLastLoaded;
  20989. this.checkLiveUpdate(newDetails);
  20990. if (newDetails.deltaUpdateFailed) {
  20991. return;
  20992. }
  20993. sliding = this.alignPlaylists(newDetails, curLevel.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  20994. }
  20995. // override level info
  20996. curLevel.details = newDetails;
  20997. this.levelLastLoaded = curLevel;
  20998. if (!startFragRequested) {
  20999. this.setStartPosition(newDetails, sliding);
  21000. }
  21001. this.hls.trigger(Events.LEVEL_UPDATED, {
  21002. details: newDetails,
  21003. level: newLevelId
  21004. });
  21005. // only switch back to IDLE state if we were waiting for level to start downloading a new fragment
  21006. if (this.state === State.WAITING_LEVEL) {
  21007. if (this.waitForCdnTuneIn(newDetails)) {
  21008. // Wait for Low-Latency CDN Tune-in
  21009. return;
  21010. }
  21011. this.state = State.IDLE;
  21012. }
  21013. if (startFragRequested && newDetails.live) {
  21014. this.synchronizeToLiveEdge(newDetails);
  21015. }
  21016. // trigger handler right now
  21017. this.tick();
  21018. };
  21019. _proto.synchronizeToLiveEdge = function synchronizeToLiveEdge(levelDetails) {
  21020. var config = this.config,
  21021. media = this.media;
  21022. if (!media) {
  21023. return;
  21024. }
  21025. var liveSyncPosition = this.hls.liveSyncPosition;
  21026. var currentTime = this.getLoadPosition();
  21027. var start = levelDetails.fragmentStart;
  21028. var end = levelDetails.edge;
  21029. var withinSlidingWindow = currentTime >= start - config.maxFragLookUpTolerance && currentTime <= end;
  21030. // Continue if we can seek forward to sync position or if current time is outside of sliding window
  21031. if (liveSyncPosition !== null && media.duration > liveSyncPosition && (currentTime < liveSyncPosition || !withinSlidingWindow)) {
  21032. // Continue if buffer is starving or if current time is behind max latency
  21033. var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
  21034. if (!withinSlidingWindow && media.readyState < 4 || currentTime < end - maxLatency) {
  21035. if (!this._hasEnoughToStart) {
  21036. this.nextLoadPosition = liveSyncPosition;
  21037. }
  21038. // Only seek if ready and there is not a significant forward buffer available for playback
  21039. if (media.readyState) {
  21040. this.warn("Playback: " + currentTime.toFixed(3) + " is located too far from the end of live sliding playlist: " + end + ", reset currentTime to : " + liveSyncPosition.toFixed(3));
  21041. if (this.config.liveSyncMode === 'buffered') {
  21042. var _bufferInfo$buffered;
  21043. var bufferInfo = BufferHelper.bufferInfo(media, liveSyncPosition, 0);
  21044. if (!(bufferInfo != null && (_bufferInfo$buffered = bufferInfo.buffered) != null && _bufferInfo$buffered.length)) {
  21045. media.currentTime = liveSyncPosition;
  21046. return;
  21047. }
  21048. var isLiveSyncInBuffer = bufferInfo.start <= currentTime;
  21049. if (isLiveSyncInBuffer) {
  21050. media.currentTime = liveSyncPosition;
  21051. return;
  21052. }
  21053. var _BufferHelper$buffere = BufferHelper.bufferedInfo(bufferInfo.buffered, currentTime, 0),
  21054. nextStart = _BufferHelper$buffere.nextStart;
  21055. if (nextStart) {
  21056. media.currentTime = nextStart;
  21057. }
  21058. } else {
  21059. media.currentTime = liveSyncPosition;
  21060. }
  21061. }
  21062. }
  21063. }
  21064. };
  21065. _proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(data) {
  21066. var _frag$initSegment;
  21067. var frag = data.frag;
  21068. var part = data.part,
  21069. payload = data.payload;
  21070. var levels = this.levels;
  21071. if (!levels) {
  21072. this.warn("Levels were reset while fragment load was in progress. Fragment " + frag.sn + " of level " + frag.level + " will not be buffered");
  21073. return;
  21074. }
  21075. var currentLevel = levels[frag.level];
  21076. if (!currentLevel) {
  21077. this.warn("Level " + frag.level + " not found on progress");
  21078. return;
  21079. }
  21080. var details = currentLevel.details;
  21081. if (!details) {
  21082. this.warn("Dropping fragment " + frag.sn + " of level " + frag.level + " after level details were reset");
  21083. this.fragmentTracker.removeFragment(frag);
  21084. return;
  21085. }
  21086. var videoCodec = currentLevel.videoCodec;
  21087. // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
  21088. var accurateTimeOffset = details.PTSKnown || !details.live;
  21089. var initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data;
  21090. var audioCodec = this._getAudioCodec(currentLevel);
  21091. // transmux the MPEG-TS data to ISO-BMFF segments
  21092. // this.log(`Transmuxing ${frag.sn} of [${details.startSN} ,${details.endSN}],level ${frag.level}, cc ${frag.cc}`);
  21093. var transmuxer = this.transmuxer = this.transmuxer || new TransmuxerInterface(this.hls, PlaylistLevelType.MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
  21094. var partIndex = part ? part.index : -1;
  21095. var partial = partIndex !== -1;
  21096. var chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
  21097. var initPTS = this.initPTS[frag.cc];
  21098. transmuxer.push(payload, initSegmentData, audioCodec, videoCodec, frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
  21099. };
  21100. _proto.onAudioTrackSwitching = function onAudioTrackSwitching(event, data) {
  21101. var _this2 = this;
  21102. var hls = this.hls;
  21103. // if any URL found on new audio track, it is an alternate audio track
  21104. var fromAltAudio = this.altAudio === 2;
  21105. var altAudio = useAlternateAudio(data.url, hls);
  21106. // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered
  21107. // don't do anything if we switch to alt audio: audio stream controller is handling it.
  21108. // we will just have to change buffer scheduling on audioTrackSwitched
  21109. if (!altAudio) {
  21110. if (this.mediaBuffer !== this.media) {
  21111. this.log('Switching on main audio, use media.buffered to schedule main fragment loading');
  21112. this.mediaBuffer = this.media;
  21113. var fragCurrent = this.fragCurrent;
  21114. // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch
  21115. if (fragCurrent) {
  21116. this.log('Switching to main audio track, cancel main fragment load');
  21117. fragCurrent.abortRequests();
  21118. this.fragmentTracker.removeFragment(fragCurrent);
  21119. }
  21120. // destroy transmuxer to force init segment generation (following audio switch)
  21121. this.resetTransmuxer();
  21122. // switch to IDLE state to load new fragment
  21123. this.resetLoadingState();
  21124. } else if (this.audioOnly) {
  21125. // Reset audio transmuxer so when switching back to main audio we're not still appending where we left off
  21126. this.resetTransmuxer();
  21127. }
  21128. // If switching from alt to main audio, flush all audio and trigger track switched
  21129. if (fromAltAudio) {
  21130. this.fragmentTracker.removeAllFragments();
  21131. hls.once(Events.BUFFER_FLUSHED, function () {
  21132. var _this2$hls;
  21133. (_this2$hls = _this2.hls) == null ? void 0 : _this2$hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);
  21134. });
  21135. hls.trigger(Events.BUFFER_FLUSHING, {
  21136. startOffset: 0,
  21137. endOffset: Number.POSITIVE_INFINITY,
  21138. type: null
  21139. });
  21140. return;
  21141. }
  21142. hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);
  21143. } else {
  21144. this.altAudio = 1;
  21145. }
  21146. };
  21147. _proto.onAudioTrackSwitched = function onAudioTrackSwitched(event, data) {
  21148. var altAudio = useAlternateAudio(data.url, this.hls);
  21149. if (altAudio) {
  21150. var videoBuffer = this.videoBuffer;
  21151. // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered
  21152. if (videoBuffer && this.mediaBuffer !== videoBuffer) {
  21153. this.log('Switching on alternate audio, use video.buffered to schedule main fragment loading');
  21154. this.mediaBuffer = videoBuffer;
  21155. }
  21156. }
  21157. this.altAudio = altAudio ? 2 : 0;
  21158. this.tick();
  21159. };
  21160. _proto.onBufferCreated = function onBufferCreated(event, data) {
  21161. var tracks = data.tracks;
  21162. var mediaTrack;
  21163. var name;
  21164. var alternate = false;
  21165. for (var type in tracks) {
  21166. var track = tracks[type];
  21167. if (track.id === 'main') {
  21168. name = type;
  21169. mediaTrack = track;
  21170. // keep video source buffer reference
  21171. if (type === 'video') {
  21172. var videoTrack = tracks[type];
  21173. if (videoTrack) {
  21174. this.videoBuffer = videoTrack.buffer;
  21175. }
  21176. }
  21177. } else {
  21178. alternate = true;
  21179. }
  21180. }
  21181. if (alternate && mediaTrack) {
  21182. this.log("Alternate track found, use " + name + ".buffered to schedule main fragment loading");
  21183. this.mediaBuffer = mediaTrack.buffer;
  21184. } else {
  21185. this.mediaBuffer = this.media;
  21186. }
  21187. };
  21188. _proto.onFragBuffered = function onFragBuffered(event, data) {
  21189. var frag = data.frag,
  21190. part = data.part;
  21191. var bufferedMainFragment = frag.type === PlaylistLevelType.MAIN;
  21192. if (bufferedMainFragment) {
  21193. if (this.fragContextChanged(frag)) {
  21194. // If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion
  21195. // Avoid setting state back to IDLE, since that will interfere with a level switch
  21196. this.warn("Fragment " + frag.sn + (part ? ' p: ' + part.index : '') + " of level " + frag.level + " finished buffering, but was aborted. state: " + this.state);
  21197. if (this.state === State.PARSED) {
  21198. this.state = State.IDLE;
  21199. }
  21200. return;
  21201. }
  21202. var stats = part ? part.stats : frag.stats;
  21203. this.fragLastKbps = Math.round(8 * stats.total / (stats.buffering.end - stats.loading.first));
  21204. if (isMediaFragment(frag)) {
  21205. this.fragPrevious = frag;
  21206. }
  21207. this.fragBufferedComplete(frag, part);
  21208. }
  21209. var media = this.media;
  21210. if (!media) {
  21211. return;
  21212. }
  21213. if (!this._hasEnoughToStart && BufferHelper.getBuffered(media).length) {
  21214. this._hasEnoughToStart = true;
  21215. this.seekToStartPos();
  21216. }
  21217. if (bufferedMainFragment) {
  21218. this.tick();
  21219. }
  21220. };
  21221. _proto.onError = function onError(event, data) {
  21222. var _data$context;
  21223. if (data.fatal) {
  21224. this.state = State.ERROR;
  21225. return;
  21226. }
  21227. switch (data.details) {
  21228. case ErrorDetails.FRAG_GAP:
  21229. case ErrorDetails.FRAG_PARSING_ERROR:
  21230. case ErrorDetails.FRAG_DECRYPT_ERROR:
  21231. case ErrorDetails.FRAG_LOAD_ERROR:
  21232. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  21233. case ErrorDetails.KEY_LOAD_ERROR:
  21234. case ErrorDetails.KEY_LOAD_TIMEOUT:
  21235. this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN, data);
  21236. break;
  21237. case ErrorDetails.LEVEL_LOAD_ERROR:
  21238. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  21239. case ErrorDetails.LEVEL_PARSING_ERROR:
  21240. // in case of non fatal error while loading level, if level controller is not retrying to load level, switch back to IDLE
  21241. if (!data.levelRetry && this.state === State.WAITING_LEVEL && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.LEVEL) {
  21242. this.state = State.IDLE;
  21243. }
  21244. break;
  21245. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  21246. case ErrorDetails.BUFFER_APPEND_ERROR:
  21247. if (data.parent !== 'main') {
  21248. return;
  21249. }
  21250. if (this.reduceLengthAndFlushBuffer(data)) {
  21251. this.resetLoadingState();
  21252. }
  21253. break;
  21254. case ErrorDetails.BUFFER_FULL_ERROR:
  21255. if (data.parent !== 'main') {
  21256. return;
  21257. }
  21258. if (this.reduceLengthAndFlushBuffer(data)) {
  21259. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  21260. }
  21261. break;
  21262. case ErrorDetails.INTERNAL_EXCEPTION:
  21263. this.recoverWorkerError(data);
  21264. break;
  21265. }
  21266. };
  21267. _proto.onFragLoadEmergencyAborted = function onFragLoadEmergencyAborted() {
  21268. this.state = State.IDLE;
  21269. // if loadedmetadata is not set, it means that we are emergency switch down on first frag
  21270. // in that case, reset startFragRequested flag
  21271. if (!this._hasEnoughToStart) {
  21272. this.startFragRequested = false;
  21273. this.nextLoadPosition = this.lastCurrentTime;
  21274. }
  21275. this.tickImmediate();
  21276. };
  21277. _proto.onBufferFlushed = function onBufferFlushed(event, _ref) {
  21278. var type = _ref.type;
  21279. if (type !== ElementaryStreamTypes.AUDIO || !this.altAudio) {
  21280. var mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  21281. if (mediaBuffer) {
  21282. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  21283. this.tick();
  21284. }
  21285. }
  21286. };
  21287. _proto.onLevelsUpdated = function onLevelsUpdated(event, data) {
  21288. if (this.level > -1 && this.fragCurrent) {
  21289. this.level = this.fragCurrent.level;
  21290. if (this.level === -1) {
  21291. this.resetWhenMissingContext(this.fragCurrent);
  21292. }
  21293. }
  21294. this.levels = data.levels;
  21295. };
  21296. _proto.swapAudioCodec = function swapAudioCodec() {
  21297. this.audioCodecSwap = !this.audioCodecSwap;
  21298. }
  21299. /**
  21300. * Seeks to the set startPosition if not equal to the mediaElement's current time.
  21301. */;
  21302. _proto.seekToStartPos = function seekToStartPos() {
  21303. var media = this.media;
  21304. if (!media) {
  21305. return;
  21306. }
  21307. var currentTime = media.currentTime;
  21308. var startPosition = this.startPosition;
  21309. // only adjust currentTime if different from startPosition or if startPosition not buffered
  21310. // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered
  21311. if (startPosition >= 0 && currentTime < startPosition) {
  21312. if (media.seeking) {
  21313. this.log("could not seek to " + startPosition + ", already seeking at " + currentTime);
  21314. return;
  21315. }
  21316. // Offset start position by timeline offset
  21317. var timelineOffset = this.timelineOffset;
  21318. if (timelineOffset && startPosition) {
  21319. startPosition += timelineOffset;
  21320. }
  21321. var details = this.getLevelDetails();
  21322. var buffered = BufferHelper.getBuffered(media);
  21323. var bufferStart = buffered.length ? buffered.start(0) : 0;
  21324. var delta = bufferStart - startPosition;
  21325. var skipTolerance = Math.max(this.config.maxBufferHole, this.config.maxFragLookUpTolerance);
  21326. if (this.config.startOnSegmentBoundary || delta > 0 && (delta < skipTolerance || this.loadingParts && delta < 2 * ((details == null ? void 0 : details.partTarget) || 0))) {
  21327. this.log("adjusting start position by " + delta + " to match buffer start");
  21328. startPosition += delta;
  21329. this.startPosition = startPosition;
  21330. }
  21331. if (currentTime < startPosition) {
  21332. this.log("seek to target start position " + startPosition + " from current time " + currentTime + " buffer start " + bufferStart);
  21333. media.currentTime = startPosition;
  21334. }
  21335. }
  21336. };
  21337. _proto._getAudioCodec = function _getAudioCodec(currentLevel) {
  21338. var audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
  21339. if (this.audioCodecSwap && audioCodec) {
  21340. this.log('Swapping audio codec');
  21341. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  21342. audioCodec = 'mp4a.40.2';
  21343. } else {
  21344. audioCodec = 'mp4a.40.5';
  21345. }
  21346. }
  21347. return audioCodec;
  21348. };
  21349. _proto._loadBitrateTestFrag = function _loadBitrateTestFrag(fragment, level) {
  21350. var _this3 = this;
  21351. fragment.bitrateTest = true;
  21352. this._doFragLoad(fragment, level).then(function (data) {
  21353. var hls = _this3.hls;
  21354. var frag = data == null ? void 0 : data.frag;
  21355. if (!frag || _this3.fragContextChanged(frag)) {
  21356. return;
  21357. }
  21358. level.fragmentError = 0;
  21359. _this3.state = State.IDLE;
  21360. _this3.startFragRequested = false;
  21361. _this3.bitrateTest = false;
  21362. var stats = frag.stats;
  21363. // Bitrate tests fragments are neither parsed nor buffered
  21364. stats.parsing.start = stats.parsing.end = stats.buffering.start = stats.buffering.end = self.performance.now();
  21365. hls.trigger(Events.FRAG_LOADED, data);
  21366. frag.bitrateTest = false;
  21367. });
  21368. };
  21369. _proto._handleTransmuxComplete = function _handleTransmuxComplete(transmuxResult) {
  21370. var _id3$samples;
  21371. var id = this.playlistType;
  21372. var hls = this.hls;
  21373. var remuxResult = transmuxResult.remuxResult,
  21374. chunkMeta = transmuxResult.chunkMeta;
  21375. var context = this.getCurrentContext(chunkMeta);
  21376. if (!context) {
  21377. this.resetWhenMissingContext(chunkMeta);
  21378. return;
  21379. }
  21380. var frag = context.frag,
  21381. part = context.part,
  21382. level = context.level;
  21383. var video = remuxResult.video,
  21384. text = remuxResult.text,
  21385. id3 = remuxResult.id3,
  21386. initSegment = remuxResult.initSegment;
  21387. var details = level.details;
  21388. // The audio-stream-controller handles audio buffering if Hls.js is playing an alternate audio track
  21389. var audio = this.altAudio ? undefined : remuxResult.audio;
  21390. // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.
  21391. // If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.
  21392. if (this.fragContextChanged(frag)) {
  21393. this.fragmentTracker.removeFragment(frag);
  21394. return;
  21395. }
  21396. this.state = State.PARSING;
  21397. if (initSegment) {
  21398. if (initSegment != null && initSegment.tracks) {
  21399. var mapFragment = frag.initSegment || frag;
  21400. this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta);
  21401. hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {
  21402. frag: mapFragment,
  21403. id: id,
  21404. tracks: initSegment.tracks
  21405. });
  21406. }
  21407. // This would be nice if Number.isFinite acted as a typeguard, but it doesn't. See: https://github.com/Microsoft/TypeScript/issues/10038
  21408. var baseTime = initSegment.initPTS;
  21409. var timescale = initSegment.timescale;
  21410. var initPTS = this.initPTS[frag.cc];
  21411. if (isFiniteNumber(baseTime) && (!initPTS || initPTS.baseTime !== baseTime || initPTS.timescale !== timescale)) {
  21412. this.initPTS[frag.cc] = {
  21413. baseTime: baseTime,
  21414. timescale: timescale
  21415. };
  21416. hls.trigger(Events.INIT_PTS_FOUND, {
  21417. frag: frag,
  21418. id: id,
  21419. initPTS: baseTime,
  21420. timescale: timescale
  21421. });
  21422. }
  21423. }
  21424. // Avoid buffering if backtracking this fragment
  21425. if (video && details) {
  21426. if (audio && video.type === 'audiovideo') {
  21427. this.logMuxedErr(frag);
  21428. }
  21429. var prevFrag = details.fragments[frag.sn - 1 - details.startSN];
  21430. var isFirstFragment = frag.sn === details.startSN;
  21431. var isFirstInDiscontinuity = !prevFrag || frag.cc > prevFrag.cc;
  21432. if (remuxResult.independent !== false) {
  21433. var startPTS = video.startPTS,
  21434. endPTS = video.endPTS,
  21435. startDTS = video.startDTS,
  21436. endDTS = video.endDTS;
  21437. if (part) {
  21438. part.elementaryStreams[video.type] = {
  21439. startPTS: startPTS,
  21440. endPTS: endPTS,
  21441. startDTS: startDTS,
  21442. endDTS: endDTS
  21443. };
  21444. } else {
  21445. if (video.firstKeyFrame && video.independent && chunkMeta.id === 1 && !isFirstInDiscontinuity) {
  21446. this.couldBacktrack = true;
  21447. }
  21448. if (video.dropped && video.independent) {
  21449. // Backtrack if dropped frames create a gap after currentTime
  21450. var bufferInfo = this.getMainFwdBufferInfo();
  21451. var targetBufferTime = (bufferInfo ? bufferInfo.end : this.getLoadPosition()) + this.config.maxBufferHole;
  21452. var startTime = video.firstKeyFramePTS ? video.firstKeyFramePTS : startPTS;
  21453. if (!isFirstFragment && targetBufferTime < startTime - this.config.maxBufferHole && !isFirstInDiscontinuity) {
  21454. this.backtrack(frag);
  21455. return;
  21456. } else if (isFirstInDiscontinuity) {
  21457. // Mark segment with a gap to avoid loop loading
  21458. frag.gap = true;
  21459. }
  21460. // Set video stream start to fragment start so that truncated samples do not distort the timeline, and mark it partial
  21461. frag.setElementaryStreamInfo(video.type, frag.start, endPTS, frag.start, endDTS, true);
  21462. } else if (isFirstFragment && startPTS - (details.appliedTimelineOffset || 0) > MAX_START_GAP_JUMP) {
  21463. // Mark segment with a gap to skip large start gap
  21464. frag.gap = true;
  21465. }
  21466. }
  21467. frag.setElementaryStreamInfo(video.type, startPTS, endPTS, startDTS, endDTS);
  21468. if (this.backtrackFragment) {
  21469. this.backtrackFragment = frag;
  21470. }
  21471. this.bufferFragmentData(video, frag, part, chunkMeta, isFirstFragment || isFirstInDiscontinuity);
  21472. } else if (isFirstFragment || isFirstInDiscontinuity) {
  21473. // Mark segment with a gap to avoid loop loading
  21474. frag.gap = true;
  21475. } else {
  21476. this.backtrack(frag);
  21477. return;
  21478. }
  21479. }
  21480. if (audio) {
  21481. var _startPTS = audio.startPTS,
  21482. _endPTS = audio.endPTS,
  21483. _startDTS = audio.startDTS,
  21484. _endDTS = audio.endDTS;
  21485. if (part) {
  21486. part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {
  21487. startPTS: _startPTS,
  21488. endPTS: _endPTS,
  21489. startDTS: _startDTS,
  21490. endDTS: _endDTS
  21491. };
  21492. }
  21493. frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, _startPTS, _endPTS, _startDTS, _endDTS);
  21494. this.bufferFragmentData(audio, frag, part, chunkMeta);
  21495. }
  21496. if (details && id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) {
  21497. var emittedID3 = {
  21498. id: id,
  21499. frag: frag,
  21500. details: details,
  21501. samples: id3.samples
  21502. };
  21503. hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);
  21504. }
  21505. if (details && text) {
  21506. var emittedText = {
  21507. id: id,
  21508. frag: frag,
  21509. details: details,
  21510. samples: text.samples
  21511. };
  21512. hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);
  21513. }
  21514. };
  21515. _proto.logMuxedErr = function logMuxedErr(frag) {
  21516. this.warn((isMediaFragment(frag) ? 'Media' : 'Init') + " segment with muxed audiovideo where only video expected: " + frag.url);
  21517. };
  21518. _proto._bufferInitSegment = function _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
  21519. var _this4 = this;
  21520. if (this.state !== State.PARSING) {
  21521. return;
  21522. }
  21523. this.audioOnly = !!tracks.audio && !tracks.video;
  21524. // if audio track is expected to come from audio stream controller, discard any coming from main
  21525. if (this.altAudio && !this.audioOnly) {
  21526. delete tracks.audio;
  21527. if (tracks.audiovideo) {
  21528. this.logMuxedErr(frag);
  21529. }
  21530. }
  21531. // include levelCodec in audio and video tracks
  21532. var audio = tracks.audio,
  21533. video = tracks.video,
  21534. audiovideo = tracks.audiovideo;
  21535. if (audio) {
  21536. var levelCodec = currentLevel.audioCodec;
  21537. var audioCodec = pickMostCompleteCodecName(audio.codec, levelCodec);
  21538. // Add level and profile to make up for remuxer not being able to parse full codec
  21539. // (logger warning "Unhandled audio codec...")
  21540. if (audioCodec === 'mp4a') {
  21541. audioCodec = 'mp4a.40.5';
  21542. }
  21543. // Handle `audioCodecSwitch`
  21544. var ua = navigator.userAgent.toLowerCase();
  21545. if (this.audioCodecSwitch) {
  21546. if (audioCodec) {
  21547. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  21548. audioCodec = 'mp4a.40.2';
  21549. } else {
  21550. audioCodec = 'mp4a.40.5';
  21551. }
  21552. }
  21553. // In the case that AAC and HE-AAC audio codecs are signalled in manifest,
  21554. // force HE-AAC, as it seems that most browsers prefers it.
  21555. // don't force HE-AAC if mono stream, or in Firefox
  21556. var audioMetadata = audio.metadata;
  21557. if (audioMetadata && 'channelCount' in audioMetadata && (audioMetadata.channelCount || 1) !== 1 && ua.indexOf('firefox') === -1) {
  21558. audioCodec = 'mp4a.40.5';
  21559. }
  21560. }
  21561. // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise
  21562. if (audioCodec && audioCodec.indexOf('mp4a.40.5') !== -1 && ua.indexOf('android') !== -1 && audio.container !== 'audio/mpeg') {
  21563. // Exclude mpeg audio
  21564. audioCodec = 'mp4a.40.2';
  21565. this.log("Android: force audio codec to " + audioCodec);
  21566. }
  21567. if (levelCodec && levelCodec !== audioCodec) {
  21568. this.log("Swapping manifest audio codec \"" + levelCodec + "\" for \"" + audioCodec + "\"");
  21569. }
  21570. audio.levelCodec = audioCodec;
  21571. audio.id = PlaylistLevelType.MAIN;
  21572. this.log("Init audio buffer, container:" + audio.container + ", codecs[selected/level/parsed]=[" + (audioCodec || '') + "/" + (levelCodec || '') + "/" + audio.codec + "]");
  21573. delete tracks.audiovideo;
  21574. }
  21575. if (video) {
  21576. video.levelCodec = currentLevel.videoCodec;
  21577. video.id = PlaylistLevelType.MAIN;
  21578. var parsedVideoCodec = video.codec;
  21579. if ((parsedVideoCodec == null ? void 0 : parsedVideoCodec.length) === 4) {
  21580. // Make up for passthrough-remuxer not being able to parse full codec
  21581. // (logger warning "Unhandled video codec...")
  21582. switch (parsedVideoCodec) {
  21583. case 'hvc1':
  21584. case 'hev1':
  21585. video.codec = 'hvc1.1.6.L120.90';
  21586. break;
  21587. case 'av01':
  21588. video.codec = 'av01.0.04M.08';
  21589. break;
  21590. case 'avc1':
  21591. video.codec = 'avc1.42e01e';
  21592. break;
  21593. }
  21594. }
  21595. this.log("Init video buffer, container:" + video.container + ", codecs[level/parsed]=[" + (currentLevel.videoCodec || '') + "/" + parsedVideoCodec + "]" + (video.codec !== parsedVideoCodec ? ' parsed-corrected=' + video.codec : '') + (video.supplemental ? ' supplemental=' + video.supplemental : ''));
  21596. delete tracks.audiovideo;
  21597. }
  21598. if (audiovideo) {
  21599. this.log("Init audiovideo buffer, container:" + audiovideo.container + ", codecs[level/parsed]=[" + currentLevel.codecs + "/" + audiovideo.codec + "]");
  21600. delete tracks.video;
  21601. delete tracks.audio;
  21602. }
  21603. var trackTypes = Object.keys(tracks);
  21604. if (trackTypes.length) {
  21605. this.hls.trigger(Events.BUFFER_CODECS, tracks);
  21606. if (!this.hls) {
  21607. // Exit after fatal tracks error
  21608. return;
  21609. }
  21610. // loop through tracks that are going to be provided to bufferController
  21611. trackTypes.forEach(function (trackName) {
  21612. var track = tracks[trackName];
  21613. var initSegment = track.initSegment;
  21614. if (initSegment != null && initSegment.byteLength) {
  21615. _this4.hls.trigger(Events.BUFFER_APPENDING, {
  21616. type: trackName,
  21617. data: initSegment,
  21618. frag: frag,
  21619. part: null,
  21620. chunkMeta: chunkMeta,
  21621. parent: frag.type
  21622. });
  21623. }
  21624. });
  21625. }
  21626. // trigger handler right now
  21627. this.tickImmediate();
  21628. };
  21629. _proto.getMainFwdBufferInfo = function getMainFwdBufferInfo() {
  21630. // Observe video SourceBuffer (this.mediaBuffer) only when alt-audio is used, otherwise observe combined media buffer
  21631. var bufferOutput = this.mediaBuffer && this.altAudio === 2 ? this.mediaBuffer : this.media;
  21632. return this.getFwdBufferInfo(bufferOutput, PlaylistLevelType.MAIN);
  21633. };
  21634. _proto.backtrack = function backtrack(frag) {
  21635. this.couldBacktrack = true;
  21636. // Causes findFragments to backtrack through fragments to find the keyframe
  21637. this.backtrackFragment = frag;
  21638. this.resetTransmuxer();
  21639. this.flushBufferGap(frag);
  21640. this.fragmentTracker.removeFragment(frag);
  21641. this.fragPrevious = null;
  21642. this.nextLoadPosition = frag.start;
  21643. this.state = State.IDLE;
  21644. };
  21645. _proto.checkFragmentChanged = function checkFragmentChanged() {
  21646. var video = this.media;
  21647. var fragPlayingCurrent = null;
  21648. if (video && video.readyState > 1 && video.seeking === false) {
  21649. var currentTime = video.currentTime;
  21650. /* if video element is in seeked state, currentTime can only increase.
  21651. (assuming that playback rate is positive ...)
  21652. As sometimes currentTime jumps back to zero after a
  21653. media decode error, check this, to avoid seeking back to
  21654. wrong position after a media decode error
  21655. */
  21656. if (BufferHelper.isBuffered(video, currentTime)) {
  21657. fragPlayingCurrent = this.getAppendedFrag(currentTime);
  21658. } else if (BufferHelper.isBuffered(video, currentTime + 0.1)) {
  21659. /* ensure that FRAG_CHANGED event is triggered at startup,
  21660. when first video frame is displayed and playback is paused.
  21661. add a tolerance of 100ms, in case current position is not buffered,
  21662. check if current pos+100ms is buffered and use that buffer range
  21663. for FRAG_CHANGED event reporting */
  21664. fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1);
  21665. }
  21666. if (fragPlayingCurrent) {
  21667. this.backtrackFragment = null;
  21668. var fragPlaying = this.fragPlaying;
  21669. var fragCurrentLevel = fragPlayingCurrent.level;
  21670. if (!fragPlaying || fragPlayingCurrent.sn !== fragPlaying.sn || fragPlaying.level !== fragCurrentLevel) {
  21671. this.fragPlaying = fragPlayingCurrent;
  21672. this.hls.trigger(Events.FRAG_CHANGED, {
  21673. frag: fragPlayingCurrent
  21674. });
  21675. if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) {
  21676. this.hls.trigger(Events.LEVEL_SWITCHED, {
  21677. level: fragCurrentLevel
  21678. });
  21679. }
  21680. }
  21681. }
  21682. }
  21683. };
  21684. return _createClass(StreamController, [{
  21685. key: "hasEnoughToStart",
  21686. get: function get() {
  21687. return this._hasEnoughToStart;
  21688. }
  21689. }, {
  21690. key: "maxBufferLength",
  21691. get: function get() {
  21692. var levels = this.levels,
  21693. level = this.level;
  21694. var levelInfo = levels == null ? void 0 : levels[level];
  21695. if (!levelInfo) {
  21696. return this.config.maxBufferLength;
  21697. }
  21698. return this.getMaxBufferLength(levelInfo.maxBitrate);
  21699. }
  21700. }, {
  21701. key: "nextLevel",
  21702. get: function get() {
  21703. var frag = this.nextBufferedFrag;
  21704. if (frag) {
  21705. return frag.level;
  21706. }
  21707. return -1;
  21708. }
  21709. }, {
  21710. key: "currentFrag",
  21711. get: function get() {
  21712. var _this$media3;
  21713. if (this.fragPlaying) {
  21714. return this.fragPlaying;
  21715. }
  21716. var currentTime = ((_this$media3 = this.media) == null ? void 0 : _this$media3.currentTime) || this.lastCurrentTime;
  21717. if (isFiniteNumber(currentTime)) {
  21718. return this.getAppendedFrag(currentTime);
  21719. }
  21720. return null;
  21721. }
  21722. }, {
  21723. key: "currentProgramDateTime",
  21724. get: function get() {
  21725. var _this$media4;
  21726. var currentTime = ((_this$media4 = this.media) == null ? void 0 : _this$media4.currentTime) || this.lastCurrentTime;
  21727. if (isFiniteNumber(currentTime)) {
  21728. var details = this.getLevelDetails();
  21729. var frag = this.currentFrag || (details ? findFragmentByPTS(null, details.fragments, currentTime) : null);
  21730. if (frag) {
  21731. var programDateTime = frag.programDateTime;
  21732. if (programDateTime !== null) {
  21733. var epocMs = programDateTime + (currentTime - frag.start) * 1000;
  21734. return new Date(epocMs);
  21735. }
  21736. }
  21737. }
  21738. return null;
  21739. }
  21740. }, {
  21741. key: "currentLevel",
  21742. get: function get() {
  21743. var frag = this.currentFrag;
  21744. if (frag) {
  21745. return frag.level;
  21746. }
  21747. return -1;
  21748. }
  21749. }, {
  21750. key: "nextBufferedFrag",
  21751. get: function get() {
  21752. var frag = this.currentFrag;
  21753. if (frag) {
  21754. return this.followingBufferedFrag(frag);
  21755. }
  21756. return null;
  21757. }
  21758. }, {
  21759. key: "forceStartLoad",
  21760. get: function get() {
  21761. return this._forceStartLoad;
  21762. }
  21763. }]);
  21764. }(BaseStreamController);
  21765. var KeyLoader = /*#__PURE__*/function () {
  21766. function KeyLoader(config) {
  21767. this.config = void 0;
  21768. this.keyUriToKeyInfo = {};
  21769. this.emeController = null;
  21770. this.config = config;
  21771. }
  21772. var _proto = KeyLoader.prototype;
  21773. _proto.abort = function abort(type) {
  21774. for (var uri in this.keyUriToKeyInfo) {
  21775. var loader = this.keyUriToKeyInfo[uri].loader;
  21776. if (loader) {
  21777. var _loader$context;
  21778. if (type && type !== ((_loader$context = loader.context) == null ? void 0 : _loader$context.frag.type)) {
  21779. return;
  21780. }
  21781. loader.abort();
  21782. }
  21783. }
  21784. };
  21785. _proto.detach = function detach() {
  21786. for (var uri in this.keyUriToKeyInfo) {
  21787. var keyInfo = this.keyUriToKeyInfo[uri];
  21788. // Remove cached EME keys on detach
  21789. if (keyInfo.mediaKeySessionContext || keyInfo.decryptdata.isCommonEncryption) {
  21790. delete this.keyUriToKeyInfo[uri];
  21791. }
  21792. }
  21793. };
  21794. _proto.destroy = function destroy() {
  21795. this.detach();
  21796. for (var uri in this.keyUriToKeyInfo) {
  21797. var loader = this.keyUriToKeyInfo[uri].loader;
  21798. if (loader) {
  21799. loader.destroy();
  21800. }
  21801. }
  21802. this.keyUriToKeyInfo = {};
  21803. };
  21804. _proto.createKeyLoadError = function createKeyLoadError(frag, details, error, networkDetails, response) {
  21805. if (details === void 0) {
  21806. details = ErrorDetails.KEY_LOAD_ERROR;
  21807. }
  21808. return new LoadError({
  21809. type: ErrorTypes.NETWORK_ERROR,
  21810. details: details,
  21811. fatal: false,
  21812. frag: frag,
  21813. response: response,
  21814. error: error,
  21815. networkDetails: networkDetails
  21816. });
  21817. };
  21818. _proto.loadClear = function loadClear(loadingFrag, encryptedFragments, startFragRequested) {
  21819. var _this = this;
  21820. if (this.emeController && this.config.emeEnabled && !this.emeController.getSelectedKeySystemFormats().length) {
  21821. // Access key-system with nearest key on start (loading frag is unencrypted)
  21822. if (encryptedFragments.length) {
  21823. var _loop = function _loop() {
  21824. var frag = encryptedFragments[i];
  21825. // Loading at or before segment with EXT-X-KEY, or first frag loading and last EXT-X-KEY
  21826. if (loadingFrag.cc <= frag.cc && (!isMediaFragment(loadingFrag) || !isMediaFragment(frag) || loadingFrag.sn < frag.sn) || !startFragRequested && i == l - 1) {
  21827. return {
  21828. v: _this.emeController.selectKeySystemFormat(frag).then(function (keySystemFormat) {
  21829. if (!_this.emeController) {
  21830. return;
  21831. }
  21832. frag.setKeyFormat(keySystemFormat);
  21833. var keySystem = emptyExports.keySystemFormatToKeySystemDomain(keySystemFormat);
  21834. if (keySystem) {
  21835. return _this.emeController.getKeySystemAccess([keySystem]);
  21836. }
  21837. })
  21838. };
  21839. }
  21840. },
  21841. _ret;
  21842. for (var i = 0, l = encryptedFragments.length; i < l; i++) {
  21843. _ret = _loop();
  21844. if (_ret) return _ret.v;
  21845. }
  21846. }
  21847. if (this.config.requireKeySystemAccessOnStart) {
  21848. var keySystemsInConfig = emptyExports.getKeySystemsForConfig(this.config);
  21849. if (keySystemsInConfig.length) {
  21850. return this.emeController.getKeySystemAccess(keySystemsInConfig);
  21851. }
  21852. }
  21853. }
  21854. return null;
  21855. };
  21856. _proto.load = function load(frag) {
  21857. var _this2 = this;
  21858. if (!frag.decryptdata && frag.encrypted && this.emeController && this.config.emeEnabled) {
  21859. // Multiple keys, but none selected, resolve in eme-controller
  21860. return this.emeController.selectKeySystemFormat(frag).then(function (keySystemFormat) {
  21861. return _this2.loadInternal(frag, keySystemFormat);
  21862. });
  21863. }
  21864. return this.loadInternal(frag);
  21865. };
  21866. _proto.loadInternal = function loadInternal(frag, keySystemFormat) {
  21867. var _keyInfo, _keyInfo2;
  21868. if (keySystemFormat) {
  21869. frag.setKeyFormat(keySystemFormat);
  21870. }
  21871. var decryptdata = frag.decryptdata;
  21872. if (!decryptdata) {
  21873. var error = new Error(keySystemFormat ? "Expected frag.decryptdata to be defined after setting format " + keySystemFormat : 'Missing decryption data on fragment in onKeyLoading');
  21874. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, error));
  21875. }
  21876. var uri = decryptdata.uri;
  21877. if (!uri) {
  21878. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error("Invalid key URI: \"" + uri + "\"")));
  21879. }
  21880. var keyInfo = this.keyUriToKeyInfo[uri];
  21881. if ((_keyInfo = keyInfo) != null && _keyInfo.decryptdata.key) {
  21882. decryptdata.key = keyInfo.decryptdata.key;
  21883. return Promise.resolve({
  21884. frag: frag,
  21885. keyInfo: keyInfo
  21886. });
  21887. }
  21888. // Return key load promise as long as it does not have a mediakey session with an unusable key status
  21889. if ((_keyInfo2 = keyInfo) != null && _keyInfo2.keyLoadPromise) {
  21890. var _keyInfo$mediaKeySess;
  21891. switch ((_keyInfo$mediaKeySess = keyInfo.mediaKeySessionContext) == null ? void 0 : _keyInfo$mediaKeySess.keyStatus) {
  21892. case undefined:
  21893. case 'status-pending':
  21894. case 'usable':
  21895. case 'usable-in-future':
  21896. return keyInfo.keyLoadPromise.then(function (keyLoadedData) {
  21897. // Return the correct fragment with updated decryptdata key and loaded keyInfo
  21898. decryptdata.key = keyLoadedData.keyInfo.decryptdata.key;
  21899. return {
  21900. frag: frag,
  21901. keyInfo: keyInfo
  21902. };
  21903. });
  21904. }
  21905. // If we have a key session and status and it is not pending or usable, continue
  21906. // This will go back to the eme-controller for expired keys to get a new keyLoadPromise
  21907. }
  21908. // Load the key or return the loading promise
  21909. keyInfo = this.keyUriToKeyInfo[uri] = {
  21910. decryptdata: decryptdata,
  21911. keyLoadPromise: null,
  21912. loader: null,
  21913. mediaKeySessionContext: null
  21914. };
  21915. switch (decryptdata.method) {
  21916. case 'ISO-23001-7':
  21917. case 'SAMPLE-AES':
  21918. case 'SAMPLE-AES-CENC':
  21919. case 'SAMPLE-AES-CTR':
  21920. if (decryptdata.keyFormat === 'identity') {
  21921. // loadKeyHTTP handles http(s) and data URLs
  21922. return this.loadKeyHTTP(keyInfo, frag);
  21923. }
  21924. return this.loadKeyEME(keyInfo, frag);
  21925. case 'AES-128':
  21926. case 'AES-256':
  21927. case 'AES-256-CTR':
  21928. return this.loadKeyHTTP(keyInfo, frag);
  21929. default:
  21930. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error("Key supplied with unsupported METHOD: \"" + decryptdata.method + "\"")));
  21931. }
  21932. };
  21933. _proto.loadKeyEME = function loadKeyEME(keyInfo, frag) {
  21934. var keyLoadedData = {
  21935. frag: frag,
  21936. keyInfo: keyInfo
  21937. };
  21938. if (this.emeController && this.config.emeEnabled) {
  21939. var keySessionContextPromise = this.emeController.loadKey(keyLoadedData);
  21940. if (keySessionContextPromise) {
  21941. return (keyInfo.keyLoadPromise = keySessionContextPromise.then(function (keySessionContext) {
  21942. keyInfo.mediaKeySessionContext = keySessionContext;
  21943. return keyLoadedData;
  21944. })).catch(function (error) {
  21945. // Remove promise for license renewal or retry
  21946. keyInfo.keyLoadPromise = null;
  21947. throw error;
  21948. });
  21949. }
  21950. }
  21951. return Promise.resolve(keyLoadedData);
  21952. };
  21953. _proto.loadKeyHTTP = function loadKeyHTTP(keyInfo, frag) {
  21954. var _this3 = this;
  21955. var config = this.config;
  21956. var Loader = config.loader;
  21957. var keyLoader = new Loader(config);
  21958. frag.keyLoader = keyInfo.loader = keyLoader;
  21959. return keyInfo.keyLoadPromise = new Promise(function (resolve, reject) {
  21960. var loaderContext = {
  21961. keyInfo: keyInfo,
  21962. frag: frag,
  21963. responseType: 'arraybuffer',
  21964. url: keyInfo.decryptdata.uri
  21965. };
  21966. // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,
  21967. // key-loader will trigger an error and rely on stream-controller to handle retry logic.
  21968. // this will also align retry logic with fragment-loader
  21969. var loadPolicy = config.keyLoadPolicy.default;
  21970. var loaderConfig = {
  21971. loadPolicy: loadPolicy,
  21972. timeout: loadPolicy.maxLoadTimeMs,
  21973. maxRetry: 0,
  21974. retryDelay: 0,
  21975. maxRetryDelay: 0
  21976. };
  21977. var loaderCallbacks = {
  21978. onSuccess: function onSuccess(response, stats, context, networkDetails) {
  21979. var frag = context.frag,
  21980. keyInfo = context.keyInfo,
  21981. uri = context.url;
  21982. if (!frag.decryptdata || keyInfo !== _this3.keyUriToKeyInfo[uri]) {
  21983. return reject(_this3.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error('after key load, decryptdata unset or changed'), networkDetails));
  21984. }
  21985. keyInfo.decryptdata.key = frag.decryptdata.key = new Uint8Array(response.data);
  21986. // detach fragment key loader on load success
  21987. frag.keyLoader = null;
  21988. keyInfo.loader = null;
  21989. resolve({
  21990. frag: frag,
  21991. keyInfo: keyInfo
  21992. });
  21993. },
  21994. onError: function onError(response, context, networkDetails, stats) {
  21995. _this3.resetLoader(context);
  21996. reject(_this3.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error("HTTP Error " + response.code + " loading key " + response.text), networkDetails, _objectSpread2({
  21997. url: loaderContext.url,
  21998. data: undefined
  21999. }, response)));
  22000. },
  22001. onTimeout: function onTimeout(stats, context, networkDetails) {
  22002. _this3.resetLoader(context);
  22003. reject(_this3.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_TIMEOUT, new Error('key loading timed out'), networkDetails));
  22004. },
  22005. onAbort: function onAbort(stats, context, networkDetails) {
  22006. _this3.resetLoader(context);
  22007. reject(_this3.createKeyLoadError(frag, ErrorDetails.INTERNAL_ABORTED, new Error('key loading aborted'), networkDetails));
  22008. }
  22009. };
  22010. keyLoader.load(loaderContext, loaderConfig, loaderCallbacks);
  22011. });
  22012. };
  22013. _proto.resetLoader = function resetLoader(context) {
  22014. var frag = context.frag,
  22015. keyInfo = context.keyInfo,
  22016. uri = context.url;
  22017. var loader = keyInfo.loader;
  22018. if (frag.keyLoader === loader) {
  22019. frag.keyLoader = null;
  22020. keyInfo.loader = null;
  22021. }
  22022. delete this.keyUriToKeyInfo[uri];
  22023. if (loader) {
  22024. loader.destroy();
  22025. }
  22026. };
  22027. return KeyLoader;
  22028. }();
  22029. function mapContextToLevelType(context) {
  22030. var type = context.type;
  22031. switch (type) {
  22032. case PlaylistContextType.AUDIO_TRACK:
  22033. return PlaylistLevelType.AUDIO;
  22034. case PlaylistContextType.SUBTITLE_TRACK:
  22035. return PlaylistLevelType.SUBTITLE;
  22036. default:
  22037. return PlaylistLevelType.MAIN;
  22038. }
  22039. }
  22040. function getResponseUrl(response, context) {
  22041. var url = response.url;
  22042. // responseURL not supported on some browsers (it is used to detect URL redirection)
  22043. // data-uri mode also not supported (but no need to detect redirection)
  22044. if (url === undefined || url.indexOf('data:') === 0) {
  22045. // fallback to initial URL
  22046. url = context.url;
  22047. }
  22048. return url;
  22049. }
  22050. var PlaylistLoader = /*#__PURE__*/function () {
  22051. function PlaylistLoader(hls) {
  22052. this.hls = void 0;
  22053. this.loaders = Object.create(null);
  22054. this.variableList = null;
  22055. this.onManifestLoaded = this.checkAutostartLoad;
  22056. this.hls = hls;
  22057. this.registerListeners();
  22058. }
  22059. var _proto = PlaylistLoader.prototype;
  22060. _proto.startLoad = function startLoad(startPosition) {};
  22061. _proto.stopLoad = function stopLoad() {
  22062. this.destroyInternalLoaders();
  22063. };
  22064. _proto.registerListeners = function registerListeners() {
  22065. var hls = this.hls;
  22066. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  22067. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  22068. hls.on(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  22069. hls.on(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  22070. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  22071. };
  22072. _proto.unregisterListeners = function unregisterListeners() {
  22073. var hls = this.hls;
  22074. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  22075. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  22076. hls.off(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  22077. hls.off(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  22078. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  22079. }
  22080. /**
  22081. * Returns defaults or configured loader-type overloads (pLoader and loader config params)
  22082. */;
  22083. _proto.createInternalLoader = function createInternalLoader(context) {
  22084. var config = this.hls.config;
  22085. var PLoader = config.pLoader;
  22086. var Loader = config.loader;
  22087. var InternalLoader = PLoader || Loader;
  22088. var loader = new InternalLoader(config);
  22089. this.loaders[context.type] = loader;
  22090. return loader;
  22091. };
  22092. _proto.getInternalLoader = function getInternalLoader(context) {
  22093. return this.loaders[context.type];
  22094. };
  22095. _proto.resetInternalLoader = function resetInternalLoader(contextType) {
  22096. if (this.loaders[contextType]) {
  22097. delete this.loaders[contextType];
  22098. }
  22099. }
  22100. /**
  22101. * Call `destroy` on all internal loader instances mapped (one per context type)
  22102. */;
  22103. _proto.destroyInternalLoaders = function destroyInternalLoaders() {
  22104. for (var contextType in this.loaders) {
  22105. var loader = this.loaders[contextType];
  22106. if (loader) {
  22107. loader.destroy();
  22108. }
  22109. this.resetInternalLoader(contextType);
  22110. }
  22111. };
  22112. _proto.destroy = function destroy() {
  22113. this.variableList = null;
  22114. this.unregisterListeners();
  22115. this.destroyInternalLoaders();
  22116. };
  22117. _proto.onManifestLoading = function onManifestLoading(event, data) {
  22118. var url = data.url;
  22119. this.variableList = null;
  22120. this.load({
  22121. id: null,
  22122. level: 0,
  22123. responseType: 'text',
  22124. type: PlaylistContextType.MANIFEST,
  22125. url: url,
  22126. deliveryDirectives: null,
  22127. levelOrTrack: null
  22128. });
  22129. };
  22130. _proto.onLevelLoading = function onLevelLoading(event, data) {
  22131. var id = data.id,
  22132. level = data.level,
  22133. pathwayId = data.pathwayId,
  22134. url = data.url,
  22135. deliveryDirectives = data.deliveryDirectives,
  22136. levelInfo = data.levelInfo;
  22137. this.load({
  22138. id: id,
  22139. level: level,
  22140. pathwayId: pathwayId,
  22141. responseType: 'text',
  22142. type: PlaylistContextType.LEVEL,
  22143. url: url,
  22144. deliveryDirectives: deliveryDirectives,
  22145. levelOrTrack: levelInfo
  22146. });
  22147. };
  22148. _proto.onAudioTrackLoading = function onAudioTrackLoading(event, data) {
  22149. var id = data.id,
  22150. groupId = data.groupId,
  22151. url = data.url,
  22152. deliveryDirectives = data.deliveryDirectives,
  22153. track = data.track;
  22154. this.load({
  22155. id: id,
  22156. groupId: groupId,
  22157. level: null,
  22158. responseType: 'text',
  22159. type: PlaylistContextType.AUDIO_TRACK,
  22160. url: url,
  22161. deliveryDirectives: deliveryDirectives,
  22162. levelOrTrack: track
  22163. });
  22164. };
  22165. _proto.onSubtitleTrackLoading = function onSubtitleTrackLoading(event, data) {
  22166. var id = data.id,
  22167. groupId = data.groupId,
  22168. url = data.url,
  22169. deliveryDirectives = data.deliveryDirectives,
  22170. track = data.track;
  22171. this.load({
  22172. id: id,
  22173. groupId: groupId,
  22174. level: null,
  22175. responseType: 'text',
  22176. type: PlaylistContextType.SUBTITLE_TRACK,
  22177. url: url,
  22178. deliveryDirectives: deliveryDirectives,
  22179. levelOrTrack: track
  22180. });
  22181. };
  22182. _proto.onLevelsUpdated = function onLevelsUpdated(event, data) {
  22183. // abort and delete loader of removed levels
  22184. var loader = this.loaders[PlaylistContextType.LEVEL];
  22185. if (loader) {
  22186. var context = loader.context;
  22187. if (context && !data.levels.some(function (lvl) {
  22188. return lvl === context.levelOrTrack;
  22189. })) {
  22190. loader.abort();
  22191. delete this.loaders[PlaylistContextType.LEVEL];
  22192. }
  22193. }
  22194. };
  22195. _proto.load = function load(context) {
  22196. var _context$deliveryDire,
  22197. _this = this;
  22198. var config = this.hls.config;
  22199. // logger.debug(`[playlist-loader]: Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);
  22200. // Check if a loader for this context already exists
  22201. var loader = this.getInternalLoader(context);
  22202. if (loader) {
  22203. var logger = this.hls.logger;
  22204. var loaderContext = loader.context;
  22205. if (loaderContext && loaderContext.levelOrTrack === context.levelOrTrack && (loaderContext.url === context.url || loaderContext.deliveryDirectives && !context.deliveryDirectives)) {
  22206. // same URL can't overlap, or wait for blocking request
  22207. if (loaderContext.url === context.url) {
  22208. logger.log("[playlist-loader]: ignore " + context.url + " ongoing request");
  22209. } else {
  22210. logger.log("[playlist-loader]: ignore " + context.url + " in favor of " + loaderContext.url);
  22211. }
  22212. return;
  22213. }
  22214. logger.log("[playlist-loader]: aborting previous loader for type: " + context.type);
  22215. loader.abort();
  22216. }
  22217. // apply different configs for retries depending on
  22218. // context (manifest, level, audio/subs playlist)
  22219. var loadPolicy;
  22220. if (context.type === PlaylistContextType.MANIFEST) {
  22221. loadPolicy = config.manifestLoadPolicy.default;
  22222. } else {
  22223. loadPolicy = _extends({}, config.playlistLoadPolicy.default, {
  22224. timeoutRetry: null,
  22225. errorRetry: null
  22226. });
  22227. }
  22228. loader = this.createInternalLoader(context);
  22229. // Override level/track timeout for LL-HLS requests
  22230. // (the default of 10000ms is counter productive to blocking playlist reload requests)
  22231. if (isFiniteNumber((_context$deliveryDire = context.deliveryDirectives) == null ? void 0 : _context$deliveryDire.part)) {
  22232. var levelDetails;
  22233. if (context.type === PlaylistContextType.LEVEL && context.level !== null) {
  22234. levelDetails = this.hls.levels[context.level].details;
  22235. } else if (context.type === PlaylistContextType.AUDIO_TRACK && context.id !== null) {
  22236. levelDetails = this.hls.audioTracks[context.id].details;
  22237. } else if (context.type === PlaylistContextType.SUBTITLE_TRACK && context.id !== null) {
  22238. levelDetails = this.hls.subtitleTracks[context.id].details;
  22239. }
  22240. if (levelDetails) {
  22241. var partTarget = levelDetails.partTarget;
  22242. var targetDuration = levelDetails.targetduration;
  22243. if (partTarget && targetDuration) {
  22244. var maxLowLatencyPlaylistRefresh = Math.max(partTarget * 3, targetDuration * 0.8) * 1000;
  22245. loadPolicy = _extends({}, loadPolicy, {
  22246. maxTimeToFirstByteMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs),
  22247. maxLoadTimeMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs)
  22248. });
  22249. }
  22250. }
  22251. }
  22252. var legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  22253. var loaderConfig = {
  22254. loadPolicy: loadPolicy,
  22255. timeout: loadPolicy.maxLoadTimeMs,
  22256. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  22257. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  22258. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  22259. };
  22260. var loaderCallbacks = {
  22261. onSuccess: function onSuccess(response, stats, context, networkDetails) {
  22262. var loader = _this.getInternalLoader(context);
  22263. _this.resetInternalLoader(context.type);
  22264. var string = response.data;
  22265. // Validate if it is an M3U8 at all
  22266. if (string.indexOf('#EXTM3U') !== 0) {
  22267. _this.handleManifestParsingError(response, context, new Error('no EXTM3U delimiter'), networkDetails || null, stats);
  22268. return;
  22269. }
  22270. stats.parsing.start = performance.now();
  22271. if (M3U8Parser.isMediaPlaylist(string) || context.type !== PlaylistContextType.MANIFEST) {
  22272. _this.handleTrackOrLevelPlaylist(response, stats, context, networkDetails || null, loader);
  22273. } else {
  22274. _this.handleMasterPlaylist(response, stats, context, networkDetails);
  22275. }
  22276. },
  22277. onError: function onError(response, context, networkDetails, stats) {
  22278. _this.handleNetworkError(context, networkDetails, false, response, stats);
  22279. },
  22280. onTimeout: function onTimeout(stats, context, networkDetails) {
  22281. _this.handleNetworkError(context, networkDetails, true, undefined, stats);
  22282. }
  22283. };
  22284. // logger.debug(`[playlist-loader]: Calling internal loader delegate for URL: ${context.url}`);
  22285. loader.load(context, loaderConfig, loaderCallbacks);
  22286. };
  22287. _proto.checkAutostartLoad = function checkAutostartLoad() {
  22288. if (!this.hls) {
  22289. return;
  22290. }
  22291. var _this$hls = this.hls,
  22292. _this$hls$config = _this$hls.config,
  22293. autoStartLoad = _this$hls$config.autoStartLoad,
  22294. startPosition = _this$hls$config.startPosition,
  22295. forceStartLoad = _this$hls.forceStartLoad;
  22296. if (autoStartLoad || forceStartLoad) {
  22297. this.hls.logger.log((autoStartLoad ? 'auto' : 'force') + " startLoad with configured startPosition " + startPosition);
  22298. this.hls.startLoad(startPosition);
  22299. }
  22300. };
  22301. _proto.handleMasterPlaylist = function handleMasterPlaylist(response, stats, context, networkDetails) {
  22302. var hls = this.hls;
  22303. var string = response.data;
  22304. var url = getResponseUrl(response, context);
  22305. var parsedResult = M3U8Parser.parseMasterPlaylist(string, url);
  22306. if (parsedResult.playlistParsingError) {
  22307. this.handleManifestParsingError(response, context, parsedResult.playlistParsingError, networkDetails, stats);
  22308. return;
  22309. }
  22310. var contentSteering = parsedResult.contentSteering,
  22311. levels = parsedResult.levels,
  22312. sessionData = parsedResult.sessionData,
  22313. sessionKeys = parsedResult.sessionKeys,
  22314. startTimeOffset = parsedResult.startTimeOffset,
  22315. variableList = parsedResult.variableList;
  22316. this.variableList = variableList;
  22317. var _M3U8Parser$parseMast = M3U8Parser.parseMasterPlaylistMedia(string, url, parsedResult),
  22318. _M3U8Parser$parseMast2 = _M3U8Parser$parseMast.AUDIO,
  22319. audioTracks = _M3U8Parser$parseMast2 === void 0 ? [] : _M3U8Parser$parseMast2,
  22320. subtitles = _M3U8Parser$parseMast.SUBTITLES,
  22321. captions = _M3U8Parser$parseMast['CLOSED-CAPTIONS'];
  22322. if (audioTracks.length) {
  22323. // check if we have found an audio track embedded in main playlist (audio track without URI attribute)
  22324. var embeddedAudioFound = audioTracks.some(function (audioTrack) {
  22325. return !audioTrack.url;
  22326. });
  22327. // if no embedded audio track defined, but audio codec signaled in quality level,
  22328. // we need to signal this main audio track this could happen with playlists with
  22329. // alt audio rendition in which quality levels (main)
  22330. // contains both audio+video. but with mixed audio track not signaled
  22331. if (!embeddedAudioFound && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
  22332. this.hls.logger.log('[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one');
  22333. audioTracks.unshift({
  22334. type: 'main',
  22335. name: 'main',
  22336. groupId: 'main',
  22337. default: false,
  22338. autoselect: false,
  22339. forced: false,
  22340. id: -1,
  22341. attrs: new AttrList({}),
  22342. bitrate: 0,
  22343. url: ''
  22344. });
  22345. }
  22346. }
  22347. hls.trigger(Events.MANIFEST_LOADED, {
  22348. levels: levels,
  22349. audioTracks: audioTracks,
  22350. subtitles: subtitles,
  22351. captions: captions,
  22352. contentSteering: contentSteering,
  22353. url: url,
  22354. stats: stats,
  22355. networkDetails: networkDetails,
  22356. sessionData: sessionData,
  22357. sessionKeys: sessionKeys,
  22358. startTimeOffset: startTimeOffset,
  22359. variableList: variableList
  22360. });
  22361. };
  22362. _proto.handleTrackOrLevelPlaylist = function handleTrackOrLevelPlaylist(response, stats, context, networkDetails, loader) {
  22363. var hls = this.hls;
  22364. var id = context.id,
  22365. level = context.level,
  22366. type = context.type;
  22367. var url = getResponseUrl(response, context);
  22368. var levelId = isFiniteNumber(level) ? level : isFiniteNumber(id) ? id : 0;
  22369. var levelType = mapContextToLevelType(context);
  22370. var levelDetails = M3U8Parser.parseLevelPlaylist(response.data, url, levelId, levelType, 0, this.variableList);
  22371. // We have done our first request (Manifest-type) and receive
  22372. // not a master playlist but a chunk-list (track/level)
  22373. // We fire the manifest-loaded event anyway with the parsed level-details
  22374. // by creating a single-level structure for it.
  22375. if (type === PlaylistContextType.MANIFEST) {
  22376. var singleLevel = {
  22377. attrs: new AttrList({}),
  22378. bitrate: 0,
  22379. details: levelDetails,
  22380. name: '',
  22381. url: url
  22382. };
  22383. levelDetails.requestScheduled = stats.loading.start + computeReloadInterval(levelDetails, 0);
  22384. hls.trigger(Events.MANIFEST_LOADED, {
  22385. levels: [singleLevel],
  22386. audioTracks: [],
  22387. url: url,
  22388. stats: stats,
  22389. networkDetails: networkDetails,
  22390. sessionData: null,
  22391. sessionKeys: null,
  22392. contentSteering: null,
  22393. startTimeOffset: null,
  22394. variableList: null
  22395. });
  22396. }
  22397. // save parsing time
  22398. stats.parsing.end = performance.now();
  22399. // extend the context with the new levelDetails property
  22400. context.levelDetails = levelDetails;
  22401. this.handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader);
  22402. };
  22403. _proto.handleManifestParsingError = function handleManifestParsingError(response, context, error, networkDetails, stats) {
  22404. this.hls.trigger(Events.ERROR, {
  22405. type: ErrorTypes.NETWORK_ERROR,
  22406. details: ErrorDetails.MANIFEST_PARSING_ERROR,
  22407. fatal: context.type === PlaylistContextType.MANIFEST,
  22408. url: response.url,
  22409. err: error,
  22410. error: error,
  22411. reason: error.message,
  22412. response: response,
  22413. context: context,
  22414. networkDetails: networkDetails,
  22415. stats: stats
  22416. });
  22417. };
  22418. _proto.handleNetworkError = function handleNetworkError(context, networkDetails, timeout, response, stats) {
  22419. if (timeout === void 0) {
  22420. timeout = false;
  22421. }
  22422. var message = "A network " + (timeout ? 'timeout' : 'error' + (response ? ' (status ' + response.code + ')' : '')) + " occurred while loading " + context.type;
  22423. if (context.type === PlaylistContextType.LEVEL) {
  22424. message += ": " + context.level + " id: " + context.id;
  22425. } else if (context.type === PlaylistContextType.AUDIO_TRACK || context.type === PlaylistContextType.SUBTITLE_TRACK) {
  22426. message += " id: " + context.id + " group-id: \"" + context.groupId + "\"";
  22427. }
  22428. var error = new Error(message);
  22429. this.hls.logger.warn("[playlist-loader]: " + message);
  22430. var details = ErrorDetails.UNKNOWN;
  22431. var fatal = false;
  22432. var loader = this.getInternalLoader(context);
  22433. switch (context.type) {
  22434. case PlaylistContextType.MANIFEST:
  22435. details = timeout ? ErrorDetails.MANIFEST_LOAD_TIMEOUT : ErrorDetails.MANIFEST_LOAD_ERROR;
  22436. fatal = true;
  22437. break;
  22438. case PlaylistContextType.LEVEL:
  22439. details = timeout ? ErrorDetails.LEVEL_LOAD_TIMEOUT : ErrorDetails.LEVEL_LOAD_ERROR;
  22440. fatal = false;
  22441. break;
  22442. case PlaylistContextType.AUDIO_TRACK:
  22443. details = timeout ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : ErrorDetails.AUDIO_TRACK_LOAD_ERROR;
  22444. fatal = false;
  22445. break;
  22446. case PlaylistContextType.SUBTITLE_TRACK:
  22447. details = timeout ? ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT : ErrorDetails.SUBTITLE_LOAD_ERROR;
  22448. fatal = false;
  22449. break;
  22450. }
  22451. if (loader) {
  22452. this.resetInternalLoader(context.type);
  22453. }
  22454. var errorData = {
  22455. type: ErrorTypes.NETWORK_ERROR,
  22456. details: details,
  22457. fatal: fatal,
  22458. url: context.url,
  22459. loader: loader,
  22460. context: context,
  22461. error: error,
  22462. networkDetails: networkDetails,
  22463. stats: stats
  22464. };
  22465. if (response) {
  22466. var url = (networkDetails == null ? void 0 : networkDetails.url) || context.url;
  22467. errorData.response = _objectSpread2({
  22468. url: url,
  22469. data: undefined
  22470. }, response);
  22471. }
  22472. this.hls.trigger(Events.ERROR, errorData);
  22473. };
  22474. _proto.handlePlaylistLoaded = function handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader) {
  22475. var hls = this.hls;
  22476. var type = context.type,
  22477. level = context.level,
  22478. id = context.id,
  22479. groupId = context.groupId,
  22480. deliveryDirectives = context.deliveryDirectives;
  22481. var url = getResponseUrl(response, context);
  22482. var parent = mapContextToLevelType(context);
  22483. var levelIndex = typeof context.level === 'number' && parent === PlaylistLevelType.MAIN ? level : undefined;
  22484. if (!levelDetails.fragments.length) {
  22485. var _error = levelDetails.playlistParsingError = new Error('No Segments found in Playlist');
  22486. hls.trigger(Events.ERROR, {
  22487. type: ErrorTypes.NETWORK_ERROR,
  22488. details: ErrorDetails.LEVEL_EMPTY_ERROR,
  22489. fatal: false,
  22490. url: url,
  22491. error: _error,
  22492. reason: _error.message,
  22493. response: response,
  22494. context: context,
  22495. level: levelIndex,
  22496. parent: parent,
  22497. networkDetails: networkDetails,
  22498. stats: stats
  22499. });
  22500. return;
  22501. }
  22502. if (!levelDetails.targetduration) {
  22503. levelDetails.playlistParsingError = new Error('Missing Target Duration');
  22504. }
  22505. var error = levelDetails.playlistParsingError;
  22506. if (error) {
  22507. this.hls.logger.warn(error);
  22508. if (!hls.config.ignorePlaylistParsingErrors) {
  22509. hls.trigger(Events.ERROR, {
  22510. type: ErrorTypes.NETWORK_ERROR,
  22511. details: ErrorDetails.LEVEL_PARSING_ERROR,
  22512. fatal: false,
  22513. url: url,
  22514. error: error,
  22515. reason: error.message,
  22516. response: response,
  22517. context: context,
  22518. level: levelIndex,
  22519. parent: parent,
  22520. networkDetails: networkDetails,
  22521. stats: stats
  22522. });
  22523. return;
  22524. }
  22525. levelDetails.playlistParsingError = null;
  22526. }
  22527. if (levelDetails.live && loader) {
  22528. if (loader.getCacheAge) {
  22529. levelDetails.ageHeader = loader.getCacheAge() || 0;
  22530. }
  22531. if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) {
  22532. levelDetails.ageHeader = 0;
  22533. }
  22534. }
  22535. switch (type) {
  22536. case PlaylistContextType.MANIFEST:
  22537. case PlaylistContextType.LEVEL:
  22538. hls.trigger(Events.LEVEL_LOADED, {
  22539. details: levelDetails,
  22540. levelInfo: context.levelOrTrack || hls.levels[0],
  22541. level: levelIndex || 0,
  22542. id: id || 0,
  22543. stats: stats,
  22544. networkDetails: networkDetails,
  22545. deliveryDirectives: deliveryDirectives,
  22546. withoutMultiVariant: type === PlaylistContextType.MANIFEST
  22547. });
  22548. break;
  22549. case PlaylistContextType.AUDIO_TRACK:
  22550. hls.trigger(Events.AUDIO_TRACK_LOADED, {
  22551. details: levelDetails,
  22552. track: context.levelOrTrack,
  22553. id: id || 0,
  22554. groupId: groupId || '',
  22555. stats: stats,
  22556. networkDetails: networkDetails,
  22557. deliveryDirectives: deliveryDirectives
  22558. });
  22559. break;
  22560. case PlaylistContextType.SUBTITLE_TRACK:
  22561. hls.trigger(Events.SUBTITLE_TRACK_LOADED, {
  22562. details: levelDetails,
  22563. track: context.levelOrTrack,
  22564. id: id || 0,
  22565. groupId: groupId || '',
  22566. stats: stats,
  22567. networkDetails: networkDetails,
  22568. deliveryDirectives: deliveryDirectives
  22569. });
  22570. break;
  22571. }
  22572. };
  22573. return PlaylistLoader;
  22574. }();
  22575. var SUPPORTED_INFO_DEFAULT = {
  22576. supported: true,
  22577. configurations: [],
  22578. decodingInfoResults: [{
  22579. supported: true,
  22580. powerEfficient: true,
  22581. smooth: true
  22582. }]
  22583. };
  22584. function getUnsupportedResult(error, configurations) {
  22585. return {
  22586. supported: false,
  22587. configurations: configurations,
  22588. decodingInfoResults: [{
  22589. supported: false,
  22590. smooth: false,
  22591. powerEfficient: false
  22592. }],
  22593. error: error
  22594. };
  22595. }
  22596. function getMediaDecodingInfoPromise(level, audioTracksByGroup, mediaCapabilities, cache) {
  22597. if (cache === void 0) {
  22598. cache = {};
  22599. }
  22600. var videoCodecs = level.videoCodec;
  22601. if (!videoCodecs && !level.audioCodec || !mediaCapabilities) {
  22602. return Promise.resolve(SUPPORTED_INFO_DEFAULT);
  22603. }
  22604. var configurations = [];
  22605. var videoDecodeList = makeVideoConfigurations(level);
  22606. var videoCount = videoDecodeList.length;
  22607. var audioDecodeList = makeAudioConfigurations(level, audioTracksByGroup, videoCount > 0);
  22608. var audioCount = audioDecodeList.length;
  22609. for (var i = videoCount || 1 * audioCount || 1; i--;) {
  22610. var configuration = {
  22611. type: 'media-source'
  22612. };
  22613. if (videoCount) {
  22614. configuration.video = videoDecodeList[i % videoCount];
  22615. }
  22616. if (audioCount) {
  22617. configuration.audio = audioDecodeList[i % audioCount];
  22618. var audioBitrate = configuration.audio.bitrate;
  22619. if (configuration.video && audioBitrate) {
  22620. configuration.video.bitrate -= audioBitrate;
  22621. }
  22622. }
  22623. configurations.push(configuration);
  22624. }
  22625. if (videoCodecs) {
  22626. // Override Windows Firefox HEVC MediaCapabilities result (https://github.com/video-dev/hls.js/issues/7046)
  22627. var ua = navigator.userAgent;
  22628. if (videoCodecs.split(',').some(function (videoCodec) {
  22629. return isHEVC(videoCodec);
  22630. }) && userAgentHevcSupportIsInaccurate()) {
  22631. return Promise.resolve(getUnsupportedResult(new Error("Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (" + ua + ")"), configurations));
  22632. }
  22633. }
  22634. return Promise.all(configurations.map(function (configuration) {
  22635. // Cache MediaCapabilities promises
  22636. var decodingInfoKey = getMediaDecodingInfoKey(configuration);
  22637. return cache[decodingInfoKey] || (cache[decodingInfoKey] = mediaCapabilities.decodingInfo(configuration));
  22638. })).then(function (decodingInfoResults) {
  22639. return {
  22640. supported: !decodingInfoResults.some(function (info) {
  22641. return !info.supported;
  22642. }),
  22643. configurations: configurations,
  22644. decodingInfoResults: decodingInfoResults
  22645. };
  22646. }).catch(function (error) {
  22647. return {
  22648. supported: false,
  22649. configurations: configurations,
  22650. decodingInfoResults: [],
  22651. error: error
  22652. };
  22653. });
  22654. }
  22655. function makeVideoConfigurations(level) {
  22656. var _level$videoCodec;
  22657. var videoCodecs = (_level$videoCodec = level.videoCodec) == null ? void 0 : _level$videoCodec.split(',');
  22658. var bitrate = getVariantDecodingBitrate(level);
  22659. var width = level.width || 640;
  22660. var height = level.height || 480;
  22661. // Assume a framerate of 30fps since MediaCapabilities will not accept Level default of 0.
  22662. var framerate = level.frameRate || 30;
  22663. var videoRange = level.videoRange.toLowerCase();
  22664. return videoCodecs ? videoCodecs.map(function (videoCodec) {
  22665. var videoConfiguration = {
  22666. contentType: mimeTypeForCodec(fillInMissingAV01Params(videoCodec), 'video'),
  22667. width: width,
  22668. height: height,
  22669. bitrate: bitrate,
  22670. framerate: framerate
  22671. };
  22672. if (videoRange !== 'sdr') {
  22673. videoConfiguration.transferFunction = videoRange;
  22674. }
  22675. return videoConfiguration;
  22676. }) : [];
  22677. }
  22678. function makeAudioConfigurations(level, audioTracksByGroup, hasVideo) {
  22679. var _level$audioCodec;
  22680. var audioCodecs = (_level$audioCodec = level.audioCodec) == null ? void 0 : _level$audioCodec.split(',');
  22681. var combinedBitrate = getVariantDecodingBitrate(level);
  22682. if (audioCodecs && level.audioGroups) {
  22683. return level.audioGroups.reduce(function (configurations, audioGroupId) {
  22684. var _audioTracksByGroup$g;
  22685. var tracks = audioGroupId ? (_audioTracksByGroup$g = audioTracksByGroup.groups[audioGroupId]) == null ? void 0 : _audioTracksByGroup$g.tracks : null;
  22686. if (tracks) {
  22687. return tracks.reduce(function (configs, audioTrack) {
  22688. if (audioTrack.groupId === audioGroupId) {
  22689. var channelsNumber = parseFloat(audioTrack.channels || '');
  22690. audioCodecs.forEach(function (audioCodec) {
  22691. var audioConfiguration = {
  22692. contentType: mimeTypeForCodec(audioCodec, 'audio'),
  22693. bitrate: hasVideo ? estimatedAudioBitrate(audioCodec, combinedBitrate) : combinedBitrate
  22694. };
  22695. if (channelsNumber) {
  22696. audioConfiguration.channels = '' + channelsNumber;
  22697. }
  22698. configs.push(audioConfiguration);
  22699. });
  22700. }
  22701. return configs;
  22702. }, configurations);
  22703. }
  22704. return configurations;
  22705. }, []);
  22706. }
  22707. return [];
  22708. }
  22709. function estimatedAudioBitrate(audioCodec, levelBitrate) {
  22710. if (levelBitrate <= 1) {
  22711. return 1;
  22712. }
  22713. var audioBitrate = 128000;
  22714. if (audioCodec === 'ec-3') {
  22715. audioBitrate = 768000;
  22716. } else if (audioCodec === 'ac-3') {
  22717. audioBitrate = 640000;
  22718. }
  22719. return Math.min(levelBitrate / 2, audioBitrate); // Don't exceed some % of level bitrate
  22720. }
  22721. function getVariantDecodingBitrate(level) {
  22722. return Math.ceil(Math.max(level.bitrate * 0.9, level.averageBitrate) / 1000) * 1000 || 1;
  22723. }
  22724. function getMediaDecodingInfoKey(config) {
  22725. var key = '';
  22726. var audio = config.audio,
  22727. video = config.video;
  22728. if (video) {
  22729. var codec = getCodecsForMimeType(video.contentType);
  22730. key += codec + "_r" + video.height + "x" + video.width + "f" + Math.ceil(video.framerate) + (video.transferFunction || 'sd') + "_" + Math.ceil(video.bitrate / 1e5);
  22731. }
  22732. if (audio) {
  22733. var _codec = getCodecsForMimeType(audio.contentType);
  22734. key += "" + (video ? '_' : '') + _codec + "_c" + audio.channels;
  22735. }
  22736. return key;
  22737. }
  22738. /**
  22739. * The `Hls` class is the core of the HLS.js library used to instantiate player instances.
  22740. * @public
  22741. */
  22742. var Hls = /*#__PURE__*/function () {
  22743. /**
  22744. * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
  22745. * @param userConfig - Configuration options applied over `Hls.DefaultConfig`
  22746. */
  22747. function Hls(userConfig) {
  22748. if (userConfig === void 0) {
  22749. userConfig = {};
  22750. }
  22751. /**
  22752. * The runtime configuration used by the player. At instantiation this is combination of `hls.userConfig` merged over `Hls.DefaultConfig`.
  22753. */
  22754. this.config = void 0;
  22755. /**
  22756. * The configuration object provided on player instantiation.
  22757. */
  22758. this.userConfig = void 0;
  22759. /**
  22760. * The logger functions used by this player instance, configured on player instantiation.
  22761. */
  22762. this.logger = void 0;
  22763. this.coreComponents = void 0;
  22764. this.networkControllers = void 0;
  22765. this._emitter = new EventEmitter();
  22766. this._autoLevelCapping = -1;
  22767. this._maxHdcpLevel = null;
  22768. this.abrController = void 0;
  22769. this.bufferController = void 0;
  22770. this.capLevelController = void 0;
  22771. this.latencyController = void 0;
  22772. this.levelController = void 0;
  22773. this.streamController = void 0;
  22774. this.audioStreamController = void 0;
  22775. this.subtititleStreamController = void 0;
  22776. this.audioTrackController = void 0;
  22777. this.subtitleTrackController = void 0;
  22778. this.interstitialsController = void 0;
  22779. this.gapController = void 0;
  22780. this.emeController = void 0;
  22781. this.cmcdController = void 0;
  22782. this._media = null;
  22783. this._url = null;
  22784. this._sessionId = void 0;
  22785. this.triggeringException = void 0;
  22786. this.started = false;
  22787. var logger = this.logger = enableLogs(userConfig.debug || false, 'Hls instance', userConfig.assetPlayerId);
  22788. var config = this.config = mergeConfig(Hls.DefaultConfig, userConfig, logger);
  22789. this.userConfig = userConfig;
  22790. if (config.progressive) {
  22791. enableStreamingMode(config, logger);
  22792. }
  22793. // core controllers and network loaders
  22794. var _AbrController = config.abrController,
  22795. _BufferController = config.bufferController,
  22796. _CapLevelController = config.capLevelController,
  22797. _ErrorController = config.errorController,
  22798. _FpsController = config.fpsController;
  22799. var errorController = new _ErrorController(this);
  22800. var abrController = this.abrController = new _AbrController(this);
  22801. // FragmentTracker must be defined before StreamController because the order of event handling is important
  22802. var fragmentTracker = new FragmentTracker(this);
  22803. var _InterstitialsController = config.interstitialsController;
  22804. var interstitialsController = _InterstitialsController ? this.interstitialsController = new _InterstitialsController(this, Hls) : null;
  22805. var bufferController = this.bufferController = new _BufferController(this, fragmentTracker);
  22806. var capLevelController = this.capLevelController = new _CapLevelController(this);
  22807. var fpsController = new _FpsController(this);
  22808. var playListLoader = new PlaylistLoader(this);
  22809. var _ContentSteeringController = config.contentSteeringController;
  22810. // Instantiate ConentSteeringController before LevelController to receive Multivariant Playlist events first
  22811. var contentSteering = _ContentSteeringController ? new _ContentSteeringController(this) : null;
  22812. var levelController = this.levelController = new LevelController(this, contentSteering);
  22813. var id3TrackController = new ID3TrackController(this);
  22814. var keyLoader = new KeyLoader(this.config);
  22815. var streamController = this.streamController = new StreamController(this, fragmentTracker, keyLoader);
  22816. var gapController = this.gapController = new GapController(this, fragmentTracker);
  22817. // Cap level controller uses streamController to flush the buffer
  22818. capLevelController.setStreamController(streamController);
  22819. // fpsController uses streamController to switch when frames are being dropped
  22820. fpsController.setStreamController(streamController);
  22821. var networkControllers = [playListLoader, levelController, streamController];
  22822. if (interstitialsController) {
  22823. networkControllers.splice(1, 0, interstitialsController);
  22824. }
  22825. if (contentSteering) {
  22826. networkControllers.splice(1, 0, contentSteering);
  22827. }
  22828. this.networkControllers = networkControllers;
  22829. var coreComponents = [abrController, bufferController, gapController, capLevelController, fpsController, id3TrackController, fragmentTracker];
  22830. this.audioTrackController = this.createController(config.audioTrackController, networkControllers);
  22831. var AudioStreamControllerClass = config.audioStreamController;
  22832. if (AudioStreamControllerClass) {
  22833. networkControllers.push(this.audioStreamController = new AudioStreamControllerClass(this, fragmentTracker, keyLoader));
  22834. }
  22835. // Instantiate subtitleTrackController before SubtitleStreamController to receive level events first
  22836. this.subtitleTrackController = this.createController(config.subtitleTrackController, networkControllers);
  22837. var SubtitleStreamControllerClass = config.subtitleStreamController;
  22838. if (SubtitleStreamControllerClass) {
  22839. networkControllers.push(this.subtititleStreamController = new SubtitleStreamControllerClass(this, fragmentTracker, keyLoader));
  22840. }
  22841. this.createController(config.timelineController, coreComponents);
  22842. keyLoader.emeController = this.emeController = this.createController(config.emeController, coreComponents);
  22843. this.cmcdController = this.createController(config.cmcdController, coreComponents);
  22844. this.latencyController = this.createController(LatencyController, coreComponents);
  22845. this.coreComponents = coreComponents;
  22846. // Error controller handles errors before and after all other controllers
  22847. // This listener will be invoked after all other controllers error listeners
  22848. networkControllers.push(errorController);
  22849. var onErrorOut = errorController.onErrorOut;
  22850. if (typeof onErrorOut === 'function') {
  22851. this.on(Events.ERROR, onErrorOut, errorController);
  22852. }
  22853. // Autostart load handler
  22854. this.on(Events.MANIFEST_LOADED, playListLoader.onManifestLoaded, playListLoader);
  22855. }
  22856. /**
  22857. * Check if the required MediaSource Extensions are available.
  22858. */
  22859. Hls.isMSESupported = function isMSESupported$1() {
  22860. return isMSESupported();
  22861. }
  22862. /**
  22863. * Check if MediaSource Extensions are available and isTypeSupported checks pass for any baseline codecs.
  22864. */;
  22865. Hls.isSupported = function isSupported$1() {
  22866. return isSupported();
  22867. }
  22868. /**
  22869. * Get the MediaSource global used for MSE playback (ManagedMediaSource, MediaSource, or WebKitMediaSource).
  22870. */;
  22871. Hls.getMediaSource = function getMediaSource$1() {
  22872. return getMediaSource();
  22873. };
  22874. var _proto = Hls.prototype;
  22875. _proto.createController = function createController(ControllerClass, components) {
  22876. if (ControllerClass) {
  22877. var controllerInstance = new ControllerClass(this);
  22878. if (components) {
  22879. components.push(controllerInstance);
  22880. }
  22881. return controllerInstance;
  22882. }
  22883. return null;
  22884. }
  22885. // Delegate the EventEmitter through the public API of Hls.js
  22886. ;
  22887. _proto.on = function on(event, listener, context) {
  22888. if (context === void 0) {
  22889. context = this;
  22890. }
  22891. this._emitter.on(event, listener, context);
  22892. };
  22893. _proto.once = function once(event, listener, context) {
  22894. if (context === void 0) {
  22895. context = this;
  22896. }
  22897. this._emitter.once(event, listener, context);
  22898. };
  22899. _proto.removeAllListeners = function removeAllListeners(event) {
  22900. this._emitter.removeAllListeners(event);
  22901. };
  22902. _proto.off = function off(event, listener, context, once) {
  22903. if (context === void 0) {
  22904. context = this;
  22905. }
  22906. this._emitter.off(event, listener, context, once);
  22907. };
  22908. _proto.listeners = function listeners(event) {
  22909. return this._emitter.listeners(event);
  22910. };
  22911. _proto.emit = function emit(event, name, eventObject) {
  22912. return this._emitter.emit(event, name, eventObject);
  22913. };
  22914. _proto.trigger = function trigger(event, eventObject) {
  22915. if (this.config.debug) {
  22916. return this.emit(event, event, eventObject);
  22917. } else {
  22918. try {
  22919. return this.emit(event, event, eventObject);
  22920. } catch (error) {
  22921. this.logger.error('An internal error happened while handling event ' + event + '. Error message: "' + error.message + '". Here is a stacktrace:', error);
  22922. // Prevent recursion in error event handlers that throw #5497
  22923. if (!this.triggeringException) {
  22924. this.triggeringException = true;
  22925. var fatal = event === Events.ERROR;
  22926. this.trigger(Events.ERROR, {
  22927. type: ErrorTypes.OTHER_ERROR,
  22928. details: ErrorDetails.INTERNAL_EXCEPTION,
  22929. fatal: fatal,
  22930. event: event,
  22931. error: error
  22932. });
  22933. this.triggeringException = false;
  22934. }
  22935. }
  22936. }
  22937. return false;
  22938. };
  22939. _proto.listenerCount = function listenerCount(event) {
  22940. return this._emitter.listenerCount(event);
  22941. }
  22942. /**
  22943. * Dispose of the instance
  22944. */;
  22945. _proto.destroy = function destroy() {
  22946. this.logger.log('destroy');
  22947. this.trigger(Events.DESTROYING, undefined);
  22948. this.detachMedia();
  22949. this.removeAllListeners();
  22950. this._autoLevelCapping = -1;
  22951. this._url = null;
  22952. this.networkControllers.forEach(function (component) {
  22953. return component.destroy();
  22954. });
  22955. this.networkControllers.length = 0;
  22956. this.coreComponents.forEach(function (component) {
  22957. return component.destroy();
  22958. });
  22959. this.coreComponents.length = 0;
  22960. // Remove any references that could be held in config options or callbacks
  22961. var config = this.config;
  22962. config.xhrSetup = config.fetchSetup = undefined;
  22963. // @ts-ignore
  22964. this.userConfig = null;
  22965. }
  22966. /**
  22967. * Attaches Hls.js to a media element
  22968. */;
  22969. _proto.attachMedia = function attachMedia(data) {
  22970. if (!data || 'media' in data && !data.media) {
  22971. var error = new Error("attachMedia failed: invalid argument (" + data + ")");
  22972. this.trigger(Events.ERROR, {
  22973. type: ErrorTypes.OTHER_ERROR,
  22974. details: ErrorDetails.ATTACH_MEDIA_ERROR,
  22975. fatal: true,
  22976. error: error
  22977. });
  22978. return;
  22979. }
  22980. this.logger.log("attachMedia");
  22981. if (this._media) {
  22982. this.logger.warn("media must be detached before attaching");
  22983. this.detachMedia();
  22984. }
  22985. var attachMediaSource = 'media' in data;
  22986. var media = attachMediaSource ? data.media : data;
  22987. var attachingData = attachMediaSource ? data : {
  22988. media: media
  22989. };
  22990. this._media = media;
  22991. this.trigger(Events.MEDIA_ATTACHING, attachingData);
  22992. }
  22993. /**
  22994. * Detach Hls.js from the media
  22995. */;
  22996. _proto.detachMedia = function detachMedia() {
  22997. this.logger.log('detachMedia');
  22998. this.trigger(Events.MEDIA_DETACHING, {});
  22999. this._media = null;
  23000. }
  23001. /**
  23002. * Detach HTMLMediaElement, MediaSource, and SourceBuffers without reset, for attaching to another instance
  23003. */;
  23004. _proto.transferMedia = function transferMedia() {
  23005. this._media = null;
  23006. var transferMedia = this.bufferController.transferMedia();
  23007. this.trigger(Events.MEDIA_DETACHING, {
  23008. transferMedia: transferMedia
  23009. });
  23010. return transferMedia;
  23011. }
  23012. /**
  23013. * Set the source URL. Can be relative or absolute.
  23014. */;
  23015. _proto.loadSource = function loadSource(url) {
  23016. this.stopLoad();
  23017. var media = this.media;
  23018. var loadedSource = this._url;
  23019. var loadingSource = this._url = urlToolkitExports.buildAbsoluteURL(self.location.href, url, {
  23020. alwaysNormalize: true
  23021. });
  23022. this._autoLevelCapping = -1;
  23023. this._maxHdcpLevel = null;
  23024. this.logger.log("loadSource:" + loadingSource);
  23025. if (media && loadedSource && (loadedSource !== loadingSource || this.bufferController.hasSourceTypes())) {
  23026. // Remove and re-create MediaSource
  23027. this.detachMedia();
  23028. this.attachMedia(media);
  23029. }
  23030. // when attaching to a source URL, trigger a playlist load
  23031. this.trigger(Events.MANIFEST_LOADING, {
  23032. url: url
  23033. });
  23034. }
  23035. /**
  23036. * Gets the currently loaded URL
  23037. */;
  23038. /**
  23039. * Start loading data from the stream source.
  23040. * Depending on default config, client starts loading automatically when a source is set.
  23041. *
  23042. * @param startPosition - Set the start position to stream from.
  23043. * Defaults to -1 (None: starts from earliest point)
  23044. */
  23045. _proto.startLoad = function startLoad(startPosition, skipSeekToStartPosition) {
  23046. if (startPosition === void 0) {
  23047. startPosition = -1;
  23048. }
  23049. this.logger.log("startLoad(" + (startPosition + (skipSeekToStartPosition ? ', <skip seek to start>' : '')) + ")");
  23050. this.started = true;
  23051. this.resumeBuffering();
  23052. for (var i = 0; i < this.networkControllers.length; i++) {
  23053. this.networkControllers[i].startLoad(startPosition, skipSeekToStartPosition);
  23054. if (!this.started || !this.networkControllers) {
  23055. break;
  23056. }
  23057. }
  23058. }
  23059. /**
  23060. * Stop loading of any stream data.
  23061. */;
  23062. _proto.stopLoad = function stopLoad() {
  23063. this.logger.log('stopLoad');
  23064. this.started = false;
  23065. for (var i = 0; i < this.networkControllers.length; i++) {
  23066. this.networkControllers[i].stopLoad();
  23067. if (this.started || !this.networkControllers) {
  23068. break;
  23069. }
  23070. }
  23071. }
  23072. /**
  23073. * Returns whether loading, toggled with `startLoad()` and `stopLoad()`, is active or not`.
  23074. */;
  23075. /**
  23076. * Resumes stream controller segment loading after `pauseBuffering` has been called.
  23077. */
  23078. _proto.resumeBuffering = function resumeBuffering() {
  23079. if (!this.bufferingEnabled) {
  23080. this.logger.log("resume buffering");
  23081. this.networkControllers.forEach(function (controller) {
  23082. if (controller.resumeBuffering) {
  23083. controller.resumeBuffering();
  23084. }
  23085. });
  23086. }
  23087. }
  23088. /**
  23089. * Prevents stream controller from loading new segments until `resumeBuffering` is called.
  23090. * This allows for media buffering to be paused without interupting playlist loading.
  23091. */;
  23092. _proto.pauseBuffering = function pauseBuffering() {
  23093. if (this.bufferingEnabled) {
  23094. this.logger.log("pause buffering");
  23095. this.networkControllers.forEach(function (controller) {
  23096. if (controller.pauseBuffering) {
  23097. controller.pauseBuffering();
  23098. }
  23099. });
  23100. }
  23101. };
  23102. /**
  23103. * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
  23104. */
  23105. _proto.swapAudioCodec = function swapAudioCodec() {
  23106. this.logger.log('swapAudioCodec');
  23107. this.streamController.swapAudioCodec();
  23108. }
  23109. /**
  23110. * When the media-element fails, this allows to detach and then re-attach it
  23111. * as one call (convenience method).
  23112. *
  23113. * Automatic recovery of media-errors by this process is configurable.
  23114. */;
  23115. _proto.recoverMediaError = function recoverMediaError() {
  23116. this.logger.log('recoverMediaError');
  23117. var media = this._media;
  23118. var time = media == null ? void 0 : media.currentTime;
  23119. this.detachMedia();
  23120. if (media) {
  23121. this.attachMedia(media);
  23122. if (time) {
  23123. this.startLoad(time);
  23124. }
  23125. }
  23126. };
  23127. _proto.removeLevel = function removeLevel(levelIndex) {
  23128. this.levelController.removeLevel(levelIndex);
  23129. }
  23130. /**
  23131. * @returns a UUID for this player instance
  23132. */;
  23133. /**
  23134. * Find and select the best matching audio track, making a level switch when a Group change is necessary.
  23135. * Updates `hls.config.audioPreference`. Returns the selected track, or null when no matching track is found.
  23136. */
  23137. _proto.setAudioOption = function setAudioOption(audioOption) {
  23138. var _this$audioTrackContr;
  23139. return ((_this$audioTrackContr = this.audioTrackController) == null ? void 0 : _this$audioTrackContr.setAudioOption(audioOption)) || null;
  23140. }
  23141. /**
  23142. * Find and select the best matching subtitle track, making a level switch when a Group change is necessary.
  23143. * Updates `hls.config.subtitlePreference`. Returns the selected track, or null when no matching track is found.
  23144. */;
  23145. _proto.setSubtitleOption = function setSubtitleOption(subtitleOption) {
  23146. var _this$subtitleTrackCo;
  23147. return ((_this$subtitleTrackCo = this.subtitleTrackController) == null ? void 0 : _this$subtitleTrackCo.setSubtitleOption(subtitleOption)) || null;
  23148. }
  23149. /**
  23150. * Get the complete list of audio tracks across all media groups
  23151. */;
  23152. /**
  23153. * returns mediaCapabilities.decodingInfo for a variant/rendition
  23154. */
  23155. _proto.getMediaDecodingInfo = function getMediaDecodingInfo(level, audioTracks) {
  23156. if (audioTracks === void 0) {
  23157. audioTracks = this.allAudioTracks;
  23158. }
  23159. var audioTracksByGroup = getAudioTracksByGroup(audioTracks);
  23160. return getMediaDecodingInfoPromise(level, audioTracksByGroup, navigator.mediaCapabilities);
  23161. };
  23162. return _createClass(Hls, [{
  23163. key: "url",
  23164. get: function get() {
  23165. return this._url;
  23166. }
  23167. /**
  23168. * Whether or not enough has been buffered to seek to start position or use `media.currentTime` to determine next load position
  23169. */
  23170. }, {
  23171. key: "hasEnoughToStart",
  23172. get: function get() {
  23173. return this.streamController.hasEnoughToStart;
  23174. }
  23175. /**
  23176. * Get the startPosition set on startLoad(position) or on autostart with config.startPosition
  23177. */
  23178. }, {
  23179. key: "startPosition",
  23180. get: function get() {
  23181. return this.streamController.startPositionValue;
  23182. }
  23183. }, {
  23184. key: "loadingEnabled",
  23185. get: function get() {
  23186. return this.started;
  23187. }
  23188. /**
  23189. * Returns state of fragment loading toggled by calling `pauseBuffering()` and `resumeBuffering()`.
  23190. */
  23191. }, {
  23192. key: "bufferingEnabled",
  23193. get: function get() {
  23194. return this.streamController.bufferingEnabled;
  23195. }
  23196. }, {
  23197. key: "inFlightFragments",
  23198. get: function get() {
  23199. var _inFlightData;
  23200. var inFlightData = (_inFlightData = {}, _inFlightData[PlaylistLevelType.MAIN] = this.streamController.inFlightFrag, _inFlightData);
  23201. if (this.audioStreamController) {
  23202. inFlightData[PlaylistLevelType.AUDIO] = this.audioStreamController.inFlightFrag;
  23203. }
  23204. if (this.subtititleStreamController) {
  23205. inFlightData[PlaylistLevelType.SUBTITLE] = this.subtititleStreamController.inFlightFrag;
  23206. }
  23207. return inFlightData;
  23208. }
  23209. }, {
  23210. key: "sessionId",
  23211. get: function get() {
  23212. var _sessionId = this._sessionId;
  23213. if (!_sessionId) {
  23214. _sessionId = this._sessionId = uuid();
  23215. }
  23216. return _sessionId;
  23217. }
  23218. /**
  23219. * @returns an array of levels (variants) sorted by HDCP-LEVEL, RESOLUTION (height), FRAME-RATE, CODECS, VIDEO-RANGE, and BANDWIDTH
  23220. */
  23221. }, {
  23222. key: "levels",
  23223. get: function get() {
  23224. var levels = this.levelController.levels;
  23225. return levels ? levels : [];
  23226. }
  23227. /**
  23228. * @returns LevelDetails of last loaded level (variant) or `null` prior to loading a media playlist.
  23229. */
  23230. }, {
  23231. key: "latestLevelDetails",
  23232. get: function get() {
  23233. return this.streamController.getLevelDetails() || null;
  23234. }
  23235. /**
  23236. * @returns Level object of selected level (variant) or `null` prior to selecting a level or once the level is removed.
  23237. */
  23238. }, {
  23239. key: "loadLevelObj",
  23240. get: function get() {
  23241. return this.levelController.loadLevelObj;
  23242. }
  23243. /**
  23244. * Index of quality level (variant) currently played
  23245. */
  23246. }, {
  23247. key: "currentLevel",
  23248. get: function get() {
  23249. return this.streamController.currentLevel;
  23250. }
  23251. /**
  23252. * Set quality level index immediately. This will flush the current buffer to replace the quality asap. That means playback will interrupt at least shortly to re-buffer and re-sync eventually. Set to -1 for automatic level selection.
  23253. */,
  23254. set: function set(newLevel) {
  23255. this.logger.log("set currentLevel:" + newLevel);
  23256. this.levelController.manualLevel = newLevel;
  23257. this.streamController.immediateLevelSwitch();
  23258. }
  23259. /**
  23260. * Index of next quality level loaded as scheduled by stream controller.
  23261. */
  23262. }, {
  23263. key: "nextLevel",
  23264. get: function get() {
  23265. return this.streamController.nextLevel;
  23266. }
  23267. /**
  23268. * Set quality level index for next loaded data.
  23269. * This will switch the video quality asap, without interrupting playback.
  23270. * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
  23271. * @param newLevel - Pass -1 for automatic level selection
  23272. */,
  23273. set: function set(newLevel) {
  23274. this.logger.log("set nextLevel:" + newLevel);
  23275. this.levelController.manualLevel = newLevel;
  23276. this.streamController.nextLevelSwitch();
  23277. }
  23278. /**
  23279. * Return the quality level of the currently or last (of none is loaded currently) segment
  23280. */
  23281. }, {
  23282. key: "loadLevel",
  23283. get: function get() {
  23284. return this.levelController.level;
  23285. }
  23286. /**
  23287. * Set quality level index for next loaded data in a conservative way.
  23288. * This will switch the quality without flushing, but interrupt current loading.
  23289. * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
  23290. * @param newLevel - Pass -1 for automatic level selection
  23291. */,
  23292. set: function set(newLevel) {
  23293. this.logger.log("set loadLevel:" + newLevel);
  23294. this.levelController.manualLevel = newLevel;
  23295. }
  23296. /**
  23297. * get next quality level loaded
  23298. */
  23299. }, {
  23300. key: "nextLoadLevel",
  23301. get: function get() {
  23302. return this.levelController.nextLoadLevel;
  23303. }
  23304. /**
  23305. * Set quality level of next loaded segment in a fully "non-destructive" way.
  23306. * Same as `loadLevel` but will wait for next switch (until current loading is done).
  23307. */,
  23308. set: function set(level) {
  23309. this.levelController.nextLoadLevel = level;
  23310. }
  23311. /**
  23312. * Return "first level": like a default level, if not set,
  23313. * falls back to index of first level referenced in manifest
  23314. */
  23315. }, {
  23316. key: "firstLevel",
  23317. get: function get() {
  23318. return Math.max(this.levelController.firstLevel, this.minAutoLevel);
  23319. }
  23320. /**
  23321. * Sets "first-level", see getter.
  23322. */,
  23323. set: function set(newLevel) {
  23324. this.logger.log("set firstLevel:" + newLevel);
  23325. this.levelController.firstLevel = newLevel;
  23326. }
  23327. /**
  23328. * Return the desired start level for the first fragment that will be loaded.
  23329. * The default value of -1 indicates automatic start level selection.
  23330. * Setting hls.nextAutoLevel without setting a startLevel will result in
  23331. * the nextAutoLevel value being used for one fragment load.
  23332. */
  23333. }, {
  23334. key: "startLevel",
  23335. get: function get() {
  23336. var startLevel = this.levelController.startLevel;
  23337. if (startLevel === -1 && this.abrController.forcedAutoLevel > -1) {
  23338. return this.abrController.forcedAutoLevel;
  23339. }
  23340. return startLevel;
  23341. }
  23342. /**
  23343. * set start level (level of first fragment that will be played back)
  23344. * if not overrided by user, first level appearing in manifest will be used as start level
  23345. * if -1 : automatic start level selection, playback will start from level matching download bandwidth
  23346. * (determined from download of first segment)
  23347. */,
  23348. set: function set(newLevel) {
  23349. this.logger.log("set startLevel:" + newLevel);
  23350. // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel
  23351. if (newLevel !== -1) {
  23352. newLevel = Math.max(newLevel, this.minAutoLevel);
  23353. }
  23354. this.levelController.startLevel = newLevel;
  23355. }
  23356. /**
  23357. * Whether level capping is enabled.
  23358. * Default value is set via `config.capLevelToPlayerSize`.
  23359. */
  23360. }, {
  23361. key: "capLevelToPlayerSize",
  23362. get: function get() {
  23363. return this.config.capLevelToPlayerSize;
  23364. }
  23365. /**
  23366. * Enables or disables level capping. If disabled after previously enabled, `nextLevelSwitch` will be immediately called.
  23367. */,
  23368. set: function set(shouldStartCapping) {
  23369. var newCapLevelToPlayerSize = !!shouldStartCapping;
  23370. if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {
  23371. if (newCapLevelToPlayerSize) {
  23372. this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size.
  23373. } else {
  23374. this.capLevelController.stopCapping();
  23375. this.autoLevelCapping = -1;
  23376. this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap.
  23377. }
  23378. this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;
  23379. }
  23380. }
  23381. /**
  23382. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  23383. */
  23384. }, {
  23385. key: "autoLevelCapping",
  23386. get: function get() {
  23387. return this._autoLevelCapping;
  23388. }
  23389. /**
  23390. * Returns the current bandwidth estimate in bits per second, when available. Otherwise, `NaN` is returned.
  23391. */,
  23392. set:
  23393. /**
  23394. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  23395. */
  23396. function set(newLevel) {
  23397. if (this._autoLevelCapping !== newLevel) {
  23398. this.logger.log("set autoLevelCapping:" + newLevel);
  23399. this._autoLevelCapping = newLevel;
  23400. this.levelController.checkMaxAutoUpdated();
  23401. }
  23402. }
  23403. }, {
  23404. key: "bandwidthEstimate",
  23405. get: function get() {
  23406. var bwEstimator = this.abrController.bwEstimator;
  23407. if (!bwEstimator) {
  23408. return NaN;
  23409. }
  23410. return bwEstimator.getEstimate();
  23411. },
  23412. set: function set(abrEwmaDefaultEstimate) {
  23413. this.abrController.resetEstimator(abrEwmaDefaultEstimate);
  23414. }
  23415. }, {
  23416. key: "abrEwmaDefaultEstimate",
  23417. get: function get() {
  23418. var bwEstimator = this.abrController.bwEstimator;
  23419. if (!bwEstimator) {
  23420. return NaN;
  23421. }
  23422. return bwEstimator.defaultEstimate;
  23423. }
  23424. /**
  23425. * get time to first byte estimate
  23426. * @type {number}
  23427. */
  23428. }, {
  23429. key: "ttfbEstimate",
  23430. get: function get() {
  23431. var bwEstimator = this.abrController.bwEstimator;
  23432. if (!bwEstimator) {
  23433. return NaN;
  23434. }
  23435. return bwEstimator.getEstimateTTFB();
  23436. }
  23437. }, {
  23438. key: "maxHdcpLevel",
  23439. get: function get() {
  23440. return this._maxHdcpLevel;
  23441. },
  23442. set: function set(value) {
  23443. if (isHdcpLevel(value) && this._maxHdcpLevel !== value) {
  23444. this._maxHdcpLevel = value;
  23445. this.levelController.checkMaxAutoUpdated();
  23446. }
  23447. }
  23448. /**
  23449. * True when automatic level selection enabled
  23450. */
  23451. }, {
  23452. key: "autoLevelEnabled",
  23453. get: function get() {
  23454. return this.levelController.manualLevel === -1;
  23455. }
  23456. /**
  23457. * Level set manually (if any)
  23458. */
  23459. }, {
  23460. key: "manualLevel",
  23461. get: function get() {
  23462. return this.levelController.manualLevel;
  23463. }
  23464. /**
  23465. * min level selectable in auto mode according to config.minAutoBitrate
  23466. */
  23467. }, {
  23468. key: "minAutoLevel",
  23469. get: function get() {
  23470. var levels = this.levels,
  23471. minAutoBitrate = this.config.minAutoBitrate;
  23472. if (!levels) return 0;
  23473. var len = levels.length;
  23474. for (var i = 0; i < len; i++) {
  23475. if (levels[i].maxBitrate >= minAutoBitrate) {
  23476. return i;
  23477. }
  23478. }
  23479. return 0;
  23480. }
  23481. /**
  23482. * max level selectable in auto mode according to autoLevelCapping
  23483. */
  23484. }, {
  23485. key: "maxAutoLevel",
  23486. get: function get() {
  23487. var levels = this.levels,
  23488. autoLevelCapping = this.autoLevelCapping,
  23489. maxHdcpLevel = this.maxHdcpLevel;
  23490. var maxAutoLevel;
  23491. if (autoLevelCapping === -1 && levels != null && levels.length) {
  23492. maxAutoLevel = levels.length - 1;
  23493. } else {
  23494. maxAutoLevel = autoLevelCapping;
  23495. }
  23496. if (maxHdcpLevel) {
  23497. for (var i = maxAutoLevel; i--;) {
  23498. var hdcpLevel = levels[i].attrs['HDCP-LEVEL'];
  23499. if (hdcpLevel && hdcpLevel <= maxHdcpLevel) {
  23500. return i;
  23501. }
  23502. }
  23503. }
  23504. return maxAutoLevel;
  23505. }
  23506. }, {
  23507. key: "firstAutoLevel",
  23508. get: function get() {
  23509. return this.abrController.firstAutoLevel;
  23510. }
  23511. /**
  23512. * next automatically selected quality level
  23513. */
  23514. }, {
  23515. key: "nextAutoLevel",
  23516. get: function get() {
  23517. return this.abrController.nextAutoLevel;
  23518. }
  23519. /**
  23520. * this setter is used to force next auto level.
  23521. * this is useful to force a switch down in auto mode:
  23522. * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
  23523. * forced value is valid for one fragment. upon successful frag loading at forced level,
  23524. * this value will be resetted to -1 by ABR controller.
  23525. */,
  23526. set: function set(nextLevel) {
  23527. this.abrController.nextAutoLevel = nextLevel;
  23528. }
  23529. /**
  23530. * get the datetime value relative to media.currentTime for the active level Program Date Time if present
  23531. */
  23532. }, {
  23533. key: "playingDate",
  23534. get: function get() {
  23535. return this.streamController.currentProgramDateTime;
  23536. }
  23537. }, {
  23538. key: "mainForwardBufferInfo",
  23539. get: function get() {
  23540. return this.streamController.getMainFwdBufferInfo();
  23541. }
  23542. }, {
  23543. key: "maxBufferLength",
  23544. get: function get() {
  23545. return this.streamController.maxBufferLength;
  23546. }
  23547. }, {
  23548. key: "allAudioTracks",
  23549. get: function get() {
  23550. var audioTrackController = this.audioTrackController;
  23551. return audioTrackController ? audioTrackController.allAudioTracks : [];
  23552. }
  23553. /**
  23554. * Get the list of selectable audio tracks
  23555. */
  23556. }, {
  23557. key: "audioTracks",
  23558. get: function get() {
  23559. var audioTrackController = this.audioTrackController;
  23560. return audioTrackController ? audioTrackController.audioTracks : [];
  23561. }
  23562. /**
  23563. * index of the selected audio track (index in audio track lists)
  23564. */
  23565. }, {
  23566. key: "audioTrack",
  23567. get: function get() {
  23568. var audioTrackController = this.audioTrackController;
  23569. return audioTrackController ? audioTrackController.audioTrack : -1;
  23570. }
  23571. /**
  23572. * selects an audio track, based on its index in audio track lists
  23573. */,
  23574. set: function set(audioTrackId) {
  23575. var audioTrackController = this.audioTrackController;
  23576. if (audioTrackController) {
  23577. audioTrackController.audioTrack = audioTrackId;
  23578. }
  23579. }
  23580. /**
  23581. * get the complete list of subtitle tracks across all media groups
  23582. */
  23583. }, {
  23584. key: "allSubtitleTracks",
  23585. get: function get() {
  23586. var subtitleTrackController = this.subtitleTrackController;
  23587. return subtitleTrackController ? subtitleTrackController.allSubtitleTracks : [];
  23588. }
  23589. /**
  23590. * get alternate subtitle tracks list from playlist
  23591. */
  23592. }, {
  23593. key: "subtitleTracks",
  23594. get: function get() {
  23595. var subtitleTrackController = this.subtitleTrackController;
  23596. return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
  23597. }
  23598. /**
  23599. * index of the selected subtitle track (index in subtitle track lists)
  23600. */
  23601. }, {
  23602. key: "subtitleTrack",
  23603. get: function get() {
  23604. var subtitleTrackController = this.subtitleTrackController;
  23605. return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
  23606. },
  23607. set:
  23608. /**
  23609. * select an subtitle track, based on its index in subtitle track lists
  23610. */
  23611. function set(subtitleTrackId) {
  23612. var subtitleTrackController = this.subtitleTrackController;
  23613. if (subtitleTrackController) {
  23614. subtitleTrackController.subtitleTrack = subtitleTrackId;
  23615. }
  23616. }
  23617. /**
  23618. * Whether subtitle display is enabled or not
  23619. */
  23620. }, {
  23621. key: "media",
  23622. get: function get() {
  23623. return this._media;
  23624. }
  23625. }, {
  23626. key: "subtitleDisplay",
  23627. get: function get() {
  23628. var subtitleTrackController = this.subtitleTrackController;
  23629. return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
  23630. }
  23631. /**
  23632. * Enable/disable subtitle display rendering
  23633. */,
  23634. set: function set(value) {
  23635. var subtitleTrackController = this.subtitleTrackController;
  23636. if (subtitleTrackController) {
  23637. subtitleTrackController.subtitleDisplay = value;
  23638. }
  23639. }
  23640. /**
  23641. * get mode for Low-Latency HLS loading
  23642. */
  23643. }, {
  23644. key: "lowLatencyMode",
  23645. get: function get() {
  23646. return this.config.lowLatencyMode;
  23647. }
  23648. /**
  23649. * Enable/disable Low-Latency HLS part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK.
  23650. */,
  23651. set: function set(mode) {
  23652. this.config.lowLatencyMode = mode;
  23653. }
  23654. /**
  23655. * Position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```hls.config.liveSyncDuration```)
  23656. * @returns null prior to loading live Playlist
  23657. */
  23658. }, {
  23659. key: "liveSyncPosition",
  23660. get: function get() {
  23661. return this.latencyController.liveSyncPosition;
  23662. }
  23663. /**
  23664. * Estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced)
  23665. * @returns 0 before first playlist is loaded
  23666. */
  23667. }, {
  23668. key: "latency",
  23669. get: function get() {
  23670. return this.latencyController.latency;
  23671. }
  23672. /**
  23673. * maximum distance from the edge before the player seeks forward to ```hls.liveSyncPosition```
  23674. * configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration```
  23675. * @returns 0 before first playlist is loaded
  23676. */
  23677. }, {
  23678. key: "maxLatency",
  23679. get: function get() {
  23680. return this.latencyController.maxLatency;
  23681. }
  23682. /**
  23683. * target distance from the edge as calculated by the latency controller
  23684. */
  23685. }, {
  23686. key: "targetLatency",
  23687. get: function get() {
  23688. return this.latencyController.targetLatency;
  23689. },
  23690. set: function set(latency) {
  23691. this.latencyController.targetLatency = latency;
  23692. }
  23693. /**
  23694. * the rate at which the edge of the current live playlist is advancing or 1 if there is none
  23695. */
  23696. }, {
  23697. key: "drift",
  23698. get: function get() {
  23699. return this.latencyController.drift;
  23700. }
  23701. /**
  23702. * set to true when startLoad is called before MANIFEST_PARSED event
  23703. */
  23704. }, {
  23705. key: "forceStartLoad",
  23706. get: function get() {
  23707. return this.streamController.forceStartLoad;
  23708. }
  23709. /**
  23710. * ContentSteering pathways getter
  23711. */
  23712. }, {
  23713. key: "pathways",
  23714. get: function get() {
  23715. return this.levelController.pathways;
  23716. }
  23717. /**
  23718. * ContentSteering pathwayPriority getter/setter
  23719. */
  23720. }, {
  23721. key: "pathwayPriority",
  23722. get: function get() {
  23723. return this.levelController.pathwayPriority;
  23724. },
  23725. set: function set(pathwayPriority) {
  23726. this.levelController.pathwayPriority = pathwayPriority;
  23727. }
  23728. /**
  23729. * returns true when all SourceBuffers are buffered to the end
  23730. */
  23731. }, {
  23732. key: "bufferedToEnd",
  23733. get: function get() {
  23734. var _this$bufferControlle;
  23735. return !!((_this$bufferControlle = this.bufferController) != null && _this$bufferControlle.bufferedToEnd);
  23736. }
  23737. /**
  23738. * returns Interstitials Program Manager
  23739. */
  23740. }, {
  23741. key: "interstitialsManager",
  23742. get: function get() {
  23743. var _this$interstitialsCo;
  23744. return ((_this$interstitialsCo = this.interstitialsController) == null ? void 0 : _this$interstitialsCo.interstitialsManager) || null;
  23745. }
  23746. }], [{
  23747. key: "version",
  23748. get:
  23749. /**
  23750. * Get the video-dev/hls.js package version.
  23751. */
  23752. function get() {
  23753. return version;
  23754. }
  23755. }, {
  23756. key: "Events",
  23757. get: function get() {
  23758. return Events;
  23759. }
  23760. }, {
  23761. key: "MetadataSchema",
  23762. get: function get() {
  23763. return MetadataSchema;
  23764. }
  23765. }, {
  23766. key: "ErrorTypes",
  23767. get: function get() {
  23768. return ErrorTypes;
  23769. }
  23770. }, {
  23771. key: "ErrorDetails",
  23772. get: function get() {
  23773. return ErrorDetails;
  23774. }
  23775. /**
  23776. * Get the default configuration applied to new instances.
  23777. */
  23778. }, {
  23779. key: "DefaultConfig",
  23780. get: function get() {
  23781. if (!Hls.defaultConfig) {
  23782. return hlsDefaultConfig;
  23783. }
  23784. return Hls.defaultConfig;
  23785. }
  23786. /**
  23787. * Replace the default configuration applied to new instances.
  23788. */,
  23789. set: function set(defaultConfig) {
  23790. Hls.defaultConfig = defaultConfig;
  23791. }
  23792. }]);
  23793. }();
  23794. Hls.defaultConfig = void 0;
  23795. return Hls;
  23796. }));
  23797. })(false);
  23798. //# sourceMappingURL=hls.light.js.map