hls.light.js 807 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113
  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 ownKeys(e, r) {
  8. var t = Object.keys(e);
  9. if (Object.getOwnPropertySymbols) {
  10. var o = Object.getOwnPropertySymbols(e);
  11. r && (o = o.filter(function (r) {
  12. return Object.getOwnPropertyDescriptor(e, r).enumerable;
  13. })), t.push.apply(t, o);
  14. }
  15. return t;
  16. }
  17. function _objectSpread2(e) {
  18. for (var r = 1; r < arguments.length; r++) {
  19. var t = null != arguments[r] ? arguments[r] : {};
  20. r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
  21. _defineProperty(e, r, t[r]);
  22. }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
  23. Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
  24. });
  25. }
  26. return e;
  27. }
  28. function _toPrimitive(t, r) {
  29. if ("object" != typeof t || !t) return t;
  30. var e = t[Symbol.toPrimitive];
  31. if (void 0 !== e) {
  32. var i = e.call(t, r || "default");
  33. if ("object" != typeof i) return i;
  34. throw new TypeError("@@toPrimitive must return a primitive value.");
  35. }
  36. return ("string" === r ? String : Number)(t);
  37. }
  38. function _toPropertyKey(t) {
  39. var i = _toPrimitive(t, "string");
  40. return "symbol" == typeof i ? i : String(i);
  41. }
  42. function _defineProperties(target, props) {
  43. for (var i = 0; i < props.length; i++) {
  44. var descriptor = props[i];
  45. descriptor.enumerable = descriptor.enumerable || false;
  46. descriptor.configurable = true;
  47. if ("value" in descriptor) descriptor.writable = true;
  48. Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
  49. }
  50. }
  51. function _createClass(Constructor, protoProps, staticProps) {
  52. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  53. if (staticProps) _defineProperties(Constructor, staticProps);
  54. Object.defineProperty(Constructor, "prototype", {
  55. writable: false
  56. });
  57. return Constructor;
  58. }
  59. function _defineProperty(obj, key, value) {
  60. key = _toPropertyKey(key);
  61. if (key in obj) {
  62. Object.defineProperty(obj, key, {
  63. value: value,
  64. enumerable: true,
  65. configurable: true,
  66. writable: true
  67. });
  68. } else {
  69. obj[key] = value;
  70. }
  71. return obj;
  72. }
  73. function _extends() {
  74. _extends = Object.assign ? Object.assign.bind() : function (target) {
  75. for (var i = 1; i < arguments.length; i++) {
  76. var source = arguments[i];
  77. for (var key in source) {
  78. if (Object.prototype.hasOwnProperty.call(source, key)) {
  79. target[key] = source[key];
  80. }
  81. }
  82. }
  83. return target;
  84. };
  85. return _extends.apply(this, arguments);
  86. }
  87. function _inheritsLoose(subClass, superClass) {
  88. subClass.prototype = Object.create(superClass.prototype);
  89. subClass.prototype.constructor = subClass;
  90. _setPrototypeOf(subClass, superClass);
  91. }
  92. function _getPrototypeOf(o) {
  93. _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
  94. return o.__proto__ || Object.getPrototypeOf(o);
  95. };
  96. return _getPrototypeOf(o);
  97. }
  98. function _setPrototypeOf(o, p) {
  99. _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
  100. o.__proto__ = p;
  101. return o;
  102. };
  103. return _setPrototypeOf(o, p);
  104. }
  105. function _isNativeReflectConstruct() {
  106. if (typeof Reflect === "undefined" || !Reflect.construct) return false;
  107. if (Reflect.construct.sham) return false;
  108. if (typeof Proxy === "function") return true;
  109. try {
  110. Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
  111. return true;
  112. } catch (e) {
  113. return false;
  114. }
  115. }
  116. function _construct(Parent, args, Class) {
  117. if (_isNativeReflectConstruct()) {
  118. _construct = Reflect.construct.bind();
  119. } else {
  120. _construct = function _construct(Parent, args, Class) {
  121. var a = [null];
  122. a.push.apply(a, args);
  123. var Constructor = Function.bind.apply(Parent, a);
  124. var instance = new Constructor();
  125. if (Class) _setPrototypeOf(instance, Class.prototype);
  126. return instance;
  127. };
  128. }
  129. return _construct.apply(null, arguments);
  130. }
  131. function _isNativeFunction(fn) {
  132. try {
  133. return Function.toString.call(fn).indexOf("[native code]") !== -1;
  134. } catch (e) {
  135. return typeof fn === "function";
  136. }
  137. }
  138. function _wrapNativeSuper(Class) {
  139. var _cache = typeof Map === "function" ? new Map() : undefined;
  140. _wrapNativeSuper = function _wrapNativeSuper(Class) {
  141. if (Class === null || !_isNativeFunction(Class)) return Class;
  142. if (typeof Class !== "function") {
  143. throw new TypeError("Super expression must either be null or a function");
  144. }
  145. if (typeof _cache !== "undefined") {
  146. if (_cache.has(Class)) return _cache.get(Class);
  147. _cache.set(Class, Wrapper);
  148. }
  149. function Wrapper() {
  150. return _construct(Class, arguments, _getPrototypeOf(this).constructor);
  151. }
  152. Wrapper.prototype = Object.create(Class.prototype, {
  153. constructor: {
  154. value: Wrapper,
  155. enumerable: false,
  156. writable: true,
  157. configurable: true
  158. }
  159. });
  160. return _setPrototypeOf(Wrapper, Class);
  161. };
  162. return _wrapNativeSuper(Class);
  163. }
  164. function _assertThisInitialized(self) {
  165. if (self === void 0) {
  166. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  167. }
  168. return self;
  169. }
  170. function getDefaultExportFromCjs (x) {
  171. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  172. }
  173. var urlToolkit = {exports: {}};
  174. (function (module, exports) {
  175. // see https://tools.ietf.org/html/rfc1808
  176. (function (root) {
  177. var URL_REGEX =
  178. /^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/;
  179. var FIRST_SEGMENT_REGEX = /^(?=([^\/?#]*))\1([^]*)$/;
  180. var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
  181. var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
  182. var URLToolkit = {
  183. // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
  184. // E.g
  185. // With opts.alwaysNormalize = false (default, spec compliant)
  186. // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
  187. // With opts.alwaysNormalize = true (not spec compliant)
  188. // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
  189. buildAbsoluteURL: function (baseURL, relativeURL, opts) {
  190. opts = opts || {};
  191. // remove any remaining space and CRLF
  192. baseURL = baseURL.trim();
  193. relativeURL = relativeURL.trim();
  194. if (!relativeURL) {
  195. // 2a) If the embedded URL is entirely empty, it inherits the
  196. // entire base URL (i.e., is set equal to the base URL)
  197. // and we are done.
  198. if (!opts.alwaysNormalize) {
  199. return baseURL;
  200. }
  201. var basePartsForNormalise = URLToolkit.parseURL(baseURL);
  202. if (!basePartsForNormalise) {
  203. throw new Error('Error trying to parse base URL.');
  204. }
  205. basePartsForNormalise.path = URLToolkit.normalizePath(
  206. basePartsForNormalise.path
  207. );
  208. return URLToolkit.buildURLFromParts(basePartsForNormalise);
  209. }
  210. var relativeParts = URLToolkit.parseURL(relativeURL);
  211. if (!relativeParts) {
  212. throw new Error('Error trying to parse relative URL.');
  213. }
  214. if (relativeParts.scheme) {
  215. // 2b) If the embedded URL starts with a scheme name, it is
  216. // interpreted as an absolute URL and we are done.
  217. if (!opts.alwaysNormalize) {
  218. return relativeURL;
  219. }
  220. relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
  221. return URLToolkit.buildURLFromParts(relativeParts);
  222. }
  223. var baseParts = URLToolkit.parseURL(baseURL);
  224. if (!baseParts) {
  225. throw new Error('Error trying to parse base URL.');
  226. }
  227. if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
  228. // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
  229. // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
  230. var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
  231. baseParts.netLoc = pathParts[1];
  232. baseParts.path = pathParts[2];
  233. }
  234. if (baseParts.netLoc && !baseParts.path) {
  235. baseParts.path = '/';
  236. }
  237. var builtParts = {
  238. // 2c) Otherwise, the embedded URL inherits the scheme of
  239. // the base URL.
  240. scheme: baseParts.scheme,
  241. netLoc: relativeParts.netLoc,
  242. path: null,
  243. params: relativeParts.params,
  244. query: relativeParts.query,
  245. fragment: relativeParts.fragment,
  246. };
  247. if (!relativeParts.netLoc) {
  248. // 3) If the embedded URL's <net_loc> is non-empty, we skip to
  249. // Step 7. Otherwise, the embedded URL inherits the <net_loc>
  250. // (if any) of the base URL.
  251. builtParts.netLoc = baseParts.netLoc;
  252. // 4) If the embedded URL path is preceded by a slash "/", the
  253. // path is not relative and we skip to Step 7.
  254. if (relativeParts.path[0] !== '/') {
  255. if (!relativeParts.path) {
  256. // 5) If the embedded URL path is empty (and not preceded by a
  257. // slash), then the embedded URL inherits the base URL path
  258. builtParts.path = baseParts.path;
  259. // 5a) if the embedded URL's <params> is non-empty, we skip to
  260. // step 7; otherwise, it inherits the <params> of the base
  261. // URL (if any) and
  262. if (!relativeParts.params) {
  263. builtParts.params = baseParts.params;
  264. // 5b) if the embedded URL's <query> is non-empty, we skip to
  265. // step 7; otherwise, it inherits the <query> of the base
  266. // URL (if any) and we skip to step 7.
  267. if (!relativeParts.query) {
  268. builtParts.query = baseParts.query;
  269. }
  270. }
  271. } else {
  272. // 6) The last segment of the base URL's path (anything
  273. // following the rightmost slash "/", or the entire path if no
  274. // slash is present) is removed and the embedded URL's path is
  275. // appended in its place.
  276. var baseURLPath = baseParts.path;
  277. var newPath =
  278. baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) +
  279. relativeParts.path;
  280. builtParts.path = URLToolkit.normalizePath(newPath);
  281. }
  282. }
  283. }
  284. if (builtParts.path === null) {
  285. builtParts.path = opts.alwaysNormalize
  286. ? URLToolkit.normalizePath(relativeParts.path)
  287. : relativeParts.path;
  288. }
  289. return URLToolkit.buildURLFromParts(builtParts);
  290. },
  291. parseURL: function (url) {
  292. var parts = URL_REGEX.exec(url);
  293. if (!parts) {
  294. return null;
  295. }
  296. return {
  297. scheme: parts[1] || '',
  298. netLoc: parts[2] || '',
  299. path: parts[3] || '',
  300. params: parts[4] || '',
  301. query: parts[5] || '',
  302. fragment: parts[6] || '',
  303. };
  304. },
  305. normalizePath: function (path) {
  306. // The following operations are
  307. // then applied, in order, to the new path:
  308. // 6a) All occurrences of "./", where "." is a complete path
  309. // segment, are removed.
  310. // 6b) If the path ends with "." as a complete path segment,
  311. // that "." is removed.
  312. path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');
  313. // 6c) All occurrences of "<segment>/../", where <segment> is a
  314. // complete path segment not equal to "..", are removed.
  315. // Removal of these path segments is performed iteratively,
  316. // removing the leftmost matching pattern on each iteration,
  317. // until no matching pattern remains.
  318. // 6d) If the path ends with "<segment>/..", where <segment> is a
  319. // complete path segment not equal to "..", that
  320. // "<segment>/.." is removed.
  321. while (
  322. path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length
  323. ) {}
  324. return path.split('').reverse().join('');
  325. },
  326. buildURLFromParts: function (parts) {
  327. return (
  328. parts.scheme +
  329. parts.netLoc +
  330. parts.path +
  331. parts.params +
  332. parts.query +
  333. parts.fragment
  334. );
  335. },
  336. };
  337. module.exports = URLToolkit;
  338. })();
  339. } (urlToolkit));
  340. var urlToolkitExports = urlToolkit.exports;
  341. // https://caniuse.com/mdn-javascript_builtins_number_isfinite
  342. var isFiniteNumber = Number.isFinite || function (value) {
  343. return typeof value === 'number' && isFinite(value);
  344. };
  345. // https://caniuse.com/mdn-javascript_builtins_number_issafeinteger
  346. var isSafeInteger = Number.isSafeInteger || function (value) {
  347. return typeof value === 'number' && Math.abs(value) <= MAX_SAFE_INTEGER;
  348. };
  349. var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  350. var Events = /*#__PURE__*/function (Events) {
  351. Events["MEDIA_ATTACHING"] = "hlsMediaAttaching";
  352. Events["MEDIA_ATTACHED"] = "hlsMediaAttached";
  353. Events["MEDIA_DETACHING"] = "hlsMediaDetaching";
  354. Events["MEDIA_DETACHED"] = "hlsMediaDetached";
  355. Events["BUFFER_RESET"] = "hlsBufferReset";
  356. Events["BUFFER_CODECS"] = "hlsBufferCodecs";
  357. Events["BUFFER_CREATED"] = "hlsBufferCreated";
  358. Events["BUFFER_APPENDING"] = "hlsBufferAppending";
  359. Events["BUFFER_APPENDED"] = "hlsBufferAppended";
  360. Events["BUFFER_EOS"] = "hlsBufferEos";
  361. Events["BUFFER_FLUSHING"] = "hlsBufferFlushing";
  362. Events["BUFFER_FLUSHED"] = "hlsBufferFlushed";
  363. Events["MANIFEST_LOADING"] = "hlsManifestLoading";
  364. Events["MANIFEST_LOADED"] = "hlsManifestLoaded";
  365. Events["MANIFEST_PARSED"] = "hlsManifestParsed";
  366. Events["LEVEL_SWITCHING"] = "hlsLevelSwitching";
  367. Events["LEVEL_SWITCHED"] = "hlsLevelSwitched";
  368. Events["LEVEL_LOADING"] = "hlsLevelLoading";
  369. Events["LEVEL_LOADED"] = "hlsLevelLoaded";
  370. Events["LEVEL_UPDATED"] = "hlsLevelUpdated";
  371. Events["LEVEL_PTS_UPDATED"] = "hlsLevelPtsUpdated";
  372. Events["LEVELS_UPDATED"] = "hlsLevelsUpdated";
  373. Events["AUDIO_TRACKS_UPDATED"] = "hlsAudioTracksUpdated";
  374. Events["AUDIO_TRACK_SWITCHING"] = "hlsAudioTrackSwitching";
  375. Events["AUDIO_TRACK_SWITCHED"] = "hlsAudioTrackSwitched";
  376. Events["AUDIO_TRACK_LOADING"] = "hlsAudioTrackLoading";
  377. Events["AUDIO_TRACK_LOADED"] = "hlsAudioTrackLoaded";
  378. Events["SUBTITLE_TRACKS_UPDATED"] = "hlsSubtitleTracksUpdated";
  379. Events["SUBTITLE_TRACKS_CLEARED"] = "hlsSubtitleTracksCleared";
  380. Events["SUBTITLE_TRACK_SWITCH"] = "hlsSubtitleTrackSwitch";
  381. Events["SUBTITLE_TRACK_LOADING"] = "hlsSubtitleTrackLoading";
  382. Events["SUBTITLE_TRACK_LOADED"] = "hlsSubtitleTrackLoaded";
  383. Events["SUBTITLE_FRAG_PROCESSED"] = "hlsSubtitleFragProcessed";
  384. Events["CUES_PARSED"] = "hlsCuesParsed";
  385. Events["NON_NATIVE_TEXT_TRACKS_FOUND"] = "hlsNonNativeTextTracksFound";
  386. Events["INIT_PTS_FOUND"] = "hlsInitPtsFound";
  387. Events["FRAG_LOADING"] = "hlsFragLoading";
  388. Events["FRAG_LOAD_EMERGENCY_ABORTED"] = "hlsFragLoadEmergencyAborted";
  389. Events["FRAG_LOADED"] = "hlsFragLoaded";
  390. Events["FRAG_DECRYPTED"] = "hlsFragDecrypted";
  391. Events["FRAG_PARSING_INIT_SEGMENT"] = "hlsFragParsingInitSegment";
  392. Events["FRAG_PARSING_USERDATA"] = "hlsFragParsingUserdata";
  393. Events["FRAG_PARSING_METADATA"] = "hlsFragParsingMetadata";
  394. Events["FRAG_PARSED"] = "hlsFragParsed";
  395. Events["FRAG_BUFFERED"] = "hlsFragBuffered";
  396. Events["FRAG_CHANGED"] = "hlsFragChanged";
  397. Events["FPS_DROP"] = "hlsFpsDrop";
  398. Events["FPS_DROP_LEVEL_CAPPING"] = "hlsFpsDropLevelCapping";
  399. Events["MAX_AUTO_LEVEL_UPDATED"] = "hlsMaxAutoLevelUpdated";
  400. Events["ERROR"] = "hlsError";
  401. Events["DESTROYING"] = "hlsDestroying";
  402. Events["KEY_LOADING"] = "hlsKeyLoading";
  403. Events["KEY_LOADED"] = "hlsKeyLoaded";
  404. Events["LIVE_BACK_BUFFER_REACHED"] = "hlsLiveBackBufferReached";
  405. Events["BACK_BUFFER_REACHED"] = "hlsBackBufferReached";
  406. Events["STEERING_MANIFEST_LOADED"] = "hlsSteeringManifestLoaded";
  407. return Events;
  408. }({});
  409. /**
  410. * Defines each Event type and payload by Event name. Used in {@link hls.js#HlsEventEmitter} to strongly type the event listener API.
  411. */
  412. var ErrorTypes = /*#__PURE__*/function (ErrorTypes) {
  413. ErrorTypes["NETWORK_ERROR"] = "networkError";
  414. ErrorTypes["MEDIA_ERROR"] = "mediaError";
  415. ErrorTypes["KEY_SYSTEM_ERROR"] = "keySystemError";
  416. ErrorTypes["MUX_ERROR"] = "muxError";
  417. ErrorTypes["OTHER_ERROR"] = "otherError";
  418. return ErrorTypes;
  419. }({});
  420. var ErrorDetails = /*#__PURE__*/function (ErrorDetails) {
  421. ErrorDetails["KEY_SYSTEM_NO_KEYS"] = "keySystemNoKeys";
  422. ErrorDetails["KEY_SYSTEM_NO_ACCESS"] = "keySystemNoAccess";
  423. ErrorDetails["KEY_SYSTEM_NO_SESSION"] = "keySystemNoSession";
  424. ErrorDetails["KEY_SYSTEM_NO_CONFIGURED_LICENSE"] = "keySystemNoConfiguredLicense";
  425. ErrorDetails["KEY_SYSTEM_LICENSE_REQUEST_FAILED"] = "keySystemLicenseRequestFailed";
  426. ErrorDetails["KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED"] = "keySystemServerCertificateRequestFailed";
  427. ErrorDetails["KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED"] = "keySystemServerCertificateUpdateFailed";
  428. ErrorDetails["KEY_SYSTEM_SESSION_UPDATE_FAILED"] = "keySystemSessionUpdateFailed";
  429. ErrorDetails["KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED"] = "keySystemStatusOutputRestricted";
  430. ErrorDetails["KEY_SYSTEM_STATUS_INTERNAL_ERROR"] = "keySystemStatusInternalError";
  431. ErrorDetails["MANIFEST_LOAD_ERROR"] = "manifestLoadError";
  432. ErrorDetails["MANIFEST_LOAD_TIMEOUT"] = "manifestLoadTimeOut";
  433. ErrorDetails["MANIFEST_PARSING_ERROR"] = "manifestParsingError";
  434. ErrorDetails["MANIFEST_INCOMPATIBLE_CODECS_ERROR"] = "manifestIncompatibleCodecsError";
  435. ErrorDetails["LEVEL_EMPTY_ERROR"] = "levelEmptyError";
  436. ErrorDetails["LEVEL_LOAD_ERROR"] = "levelLoadError";
  437. ErrorDetails["LEVEL_LOAD_TIMEOUT"] = "levelLoadTimeOut";
  438. ErrorDetails["LEVEL_PARSING_ERROR"] = "levelParsingError";
  439. ErrorDetails["LEVEL_SWITCH_ERROR"] = "levelSwitchError";
  440. ErrorDetails["AUDIO_TRACK_LOAD_ERROR"] = "audioTrackLoadError";
  441. ErrorDetails["AUDIO_TRACK_LOAD_TIMEOUT"] = "audioTrackLoadTimeOut";
  442. ErrorDetails["SUBTITLE_LOAD_ERROR"] = "subtitleTrackLoadError";
  443. ErrorDetails["SUBTITLE_TRACK_LOAD_TIMEOUT"] = "subtitleTrackLoadTimeOut";
  444. ErrorDetails["FRAG_LOAD_ERROR"] = "fragLoadError";
  445. ErrorDetails["FRAG_LOAD_TIMEOUT"] = "fragLoadTimeOut";
  446. ErrorDetails["FRAG_DECRYPT_ERROR"] = "fragDecryptError";
  447. ErrorDetails["FRAG_PARSING_ERROR"] = "fragParsingError";
  448. ErrorDetails["FRAG_GAP"] = "fragGap";
  449. ErrorDetails["REMUX_ALLOC_ERROR"] = "remuxAllocError";
  450. ErrorDetails["KEY_LOAD_ERROR"] = "keyLoadError";
  451. ErrorDetails["KEY_LOAD_TIMEOUT"] = "keyLoadTimeOut";
  452. ErrorDetails["BUFFER_ADD_CODEC_ERROR"] = "bufferAddCodecError";
  453. ErrorDetails["BUFFER_INCOMPATIBLE_CODECS_ERROR"] = "bufferIncompatibleCodecsError";
  454. ErrorDetails["BUFFER_APPEND_ERROR"] = "bufferAppendError";
  455. ErrorDetails["BUFFER_APPENDING_ERROR"] = "bufferAppendingError";
  456. ErrorDetails["BUFFER_STALLED_ERROR"] = "bufferStalledError";
  457. ErrorDetails["BUFFER_FULL_ERROR"] = "bufferFullError";
  458. ErrorDetails["BUFFER_SEEK_OVER_HOLE"] = "bufferSeekOverHole";
  459. ErrorDetails["BUFFER_NUDGE_ON_STALL"] = "bufferNudgeOnStall";
  460. ErrorDetails["INTERNAL_EXCEPTION"] = "internalException";
  461. ErrorDetails["INTERNAL_ABORTED"] = "aborted";
  462. ErrorDetails["UNKNOWN"] = "unknown";
  463. return ErrorDetails;
  464. }({});
  465. var noop = function noop() {};
  466. var fakeLogger = {
  467. trace: noop,
  468. debug: noop,
  469. log: noop,
  470. warn: noop,
  471. info: noop,
  472. error: noop
  473. };
  474. var exportedLogger = fakeLogger;
  475. // let lastCallTime;
  476. // function formatMsgWithTimeInfo(type, msg) {
  477. // const now = Date.now();
  478. // const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';
  479. // lastCallTime = now;
  480. // msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';
  481. // return msg;
  482. // }
  483. function consolePrintFn(type) {
  484. var func = self.console[type];
  485. if (func) {
  486. return func.bind(self.console, "[" + type + "] >");
  487. }
  488. return noop;
  489. }
  490. function exportLoggerFunctions(debugConfig) {
  491. for (var _len = arguments.length, functions = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  492. functions[_key - 1] = arguments[_key];
  493. }
  494. functions.forEach(function (type) {
  495. exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);
  496. });
  497. }
  498. function enableLogs(debugConfig, id) {
  499. // check that console is available
  500. if (typeof console === 'object' && debugConfig === true || typeof debugConfig === 'object') {
  501. exportLoggerFunctions(debugConfig,
  502. // Remove out from list here to hard-disable a log-level
  503. // 'trace',
  504. 'debug', 'log', 'info', 'warn', 'error');
  505. // Some browsers don't allow to use bind on console object anyway
  506. // fallback to default if needed
  507. try {
  508. exportedLogger.log("Debug logs enabled for \"" + id + "\" in hls.js version " + "1.5.15");
  509. } catch (e) {
  510. exportedLogger = fakeLogger;
  511. }
  512. } else {
  513. exportedLogger = fakeLogger;
  514. }
  515. }
  516. var logger = exportedLogger;
  517. var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/;
  518. var ATTR_LIST_REGEX = /(.+?)=(".*?"|.*?)(?:,|$)/g;
  519. // adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
  520. var AttrList = /*#__PURE__*/function () {
  521. function AttrList(attrs) {
  522. if (typeof attrs === 'string') {
  523. attrs = AttrList.parseAttrList(attrs);
  524. }
  525. _extends(this, attrs);
  526. }
  527. var _proto = AttrList.prototype;
  528. _proto.decimalInteger = function decimalInteger(attrName) {
  529. var intValue = parseInt(this[attrName], 10);
  530. if (intValue > Number.MAX_SAFE_INTEGER) {
  531. return Infinity;
  532. }
  533. return intValue;
  534. };
  535. _proto.hexadecimalInteger = function hexadecimalInteger(attrName) {
  536. if (this[attrName]) {
  537. var stringValue = (this[attrName] || '0x').slice(2);
  538. stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;
  539. var value = new Uint8Array(stringValue.length / 2);
  540. for (var i = 0; i < stringValue.length / 2; i++) {
  541. value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
  542. }
  543. return value;
  544. } else {
  545. return null;
  546. }
  547. };
  548. _proto.hexadecimalIntegerAsNumber = function hexadecimalIntegerAsNumber(attrName) {
  549. var intValue = parseInt(this[attrName], 16);
  550. if (intValue > Number.MAX_SAFE_INTEGER) {
  551. return Infinity;
  552. }
  553. return intValue;
  554. };
  555. _proto.decimalFloatingPoint = function decimalFloatingPoint(attrName) {
  556. return parseFloat(this[attrName]);
  557. };
  558. _proto.optionalFloat = function optionalFloat(attrName, defaultValue) {
  559. var value = this[attrName];
  560. return value ? parseFloat(value) : defaultValue;
  561. };
  562. _proto.enumeratedString = function enumeratedString(attrName) {
  563. return this[attrName];
  564. };
  565. _proto.bool = function bool(attrName) {
  566. return this[attrName] === 'YES';
  567. };
  568. _proto.decimalResolution = function decimalResolution(attrName) {
  569. var res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
  570. if (res === null) {
  571. return undefined;
  572. }
  573. return {
  574. width: parseInt(res[1], 10),
  575. height: parseInt(res[2], 10)
  576. };
  577. };
  578. AttrList.parseAttrList = function parseAttrList(input) {
  579. var match;
  580. var attrs = {};
  581. var quote = '"';
  582. ATTR_LIST_REGEX.lastIndex = 0;
  583. while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
  584. var value = match[2];
  585. if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) {
  586. value = value.slice(1, -1);
  587. }
  588. var name = match[1].trim();
  589. attrs[name] = value;
  590. }
  591. return attrs;
  592. };
  593. _createClass(AttrList, [{
  594. key: "clientAttrs",
  595. get: function get() {
  596. return Object.keys(this).filter(function (attr) {
  597. return attr.substring(0, 2) === 'X-';
  598. });
  599. }
  600. }]);
  601. return AttrList;
  602. }();
  603. // Avoid exporting const enum so that these values can be inlined
  604. function isDateRangeCueAttribute(attrName) {
  605. return attrName !== "ID" && attrName !== "CLASS" && attrName !== "START-DATE" && attrName !== "DURATION" && attrName !== "END-DATE" && attrName !== "END-ON-NEXT";
  606. }
  607. function isSCTE35Attribute(attrName) {
  608. return attrName === "SCTE35-OUT" || attrName === "SCTE35-IN";
  609. }
  610. var DateRange = /*#__PURE__*/function () {
  611. function DateRange(dateRangeAttr, dateRangeWithSameId) {
  612. this.attr = void 0;
  613. this._startDate = void 0;
  614. this._endDate = void 0;
  615. this._badValueForSameId = void 0;
  616. if (dateRangeWithSameId) {
  617. var previousAttr = dateRangeWithSameId.attr;
  618. for (var key in previousAttr) {
  619. if (Object.prototype.hasOwnProperty.call(dateRangeAttr, key) && dateRangeAttr[key] !== previousAttr[key]) {
  620. logger.warn("DATERANGE tag attribute: \"" + key + "\" does not match for tags with ID: \"" + dateRangeAttr.ID + "\"");
  621. this._badValueForSameId = key;
  622. break;
  623. }
  624. }
  625. // Merge DateRange tags with the same ID
  626. dateRangeAttr = _extends(new AttrList({}), previousAttr, dateRangeAttr);
  627. }
  628. this.attr = dateRangeAttr;
  629. this._startDate = new Date(dateRangeAttr["START-DATE"]);
  630. if ("END-DATE" in this.attr) {
  631. var endDate = new Date(this.attr["END-DATE"]);
  632. if (isFiniteNumber(endDate.getTime())) {
  633. this._endDate = endDate;
  634. }
  635. }
  636. }
  637. _createClass(DateRange, [{
  638. key: "id",
  639. get: function get() {
  640. return this.attr.ID;
  641. }
  642. }, {
  643. key: "class",
  644. get: function get() {
  645. return this.attr.CLASS;
  646. }
  647. }, {
  648. key: "startDate",
  649. get: function get() {
  650. return this._startDate;
  651. }
  652. }, {
  653. key: "endDate",
  654. get: function get() {
  655. if (this._endDate) {
  656. return this._endDate;
  657. }
  658. var duration = this.duration;
  659. if (duration !== null) {
  660. return new Date(this._startDate.getTime() + duration * 1000);
  661. }
  662. return null;
  663. }
  664. }, {
  665. key: "duration",
  666. get: function get() {
  667. if ("DURATION" in this.attr) {
  668. var duration = this.attr.decimalFloatingPoint("DURATION");
  669. if (isFiniteNumber(duration)) {
  670. return duration;
  671. }
  672. } else if (this._endDate) {
  673. return (this._endDate.getTime() - this._startDate.getTime()) / 1000;
  674. }
  675. return null;
  676. }
  677. }, {
  678. key: "plannedDuration",
  679. get: function get() {
  680. if ("PLANNED-DURATION" in this.attr) {
  681. return this.attr.decimalFloatingPoint("PLANNED-DURATION");
  682. }
  683. return null;
  684. }
  685. }, {
  686. key: "endOnNext",
  687. get: function get() {
  688. return this.attr.bool("END-ON-NEXT");
  689. }
  690. }, {
  691. key: "isValid",
  692. get: function get() {
  693. return !!this.id && !this._badValueForSameId && isFiniteNumber(this.startDate.getTime()) && (this.duration === null || this.duration >= 0) && (!this.endOnNext || !!this.class);
  694. }
  695. }]);
  696. return DateRange;
  697. }();
  698. var LoadStats = function LoadStats() {
  699. this.aborted = false;
  700. this.loaded = 0;
  701. this.retry = 0;
  702. this.total = 0;
  703. this.chunkCount = 0;
  704. this.bwEstimate = 0;
  705. this.loading = {
  706. start: 0,
  707. first: 0,
  708. end: 0
  709. };
  710. this.parsing = {
  711. start: 0,
  712. end: 0
  713. };
  714. this.buffering = {
  715. start: 0,
  716. first: 0,
  717. end: 0
  718. };
  719. };
  720. var ElementaryStreamTypes = {
  721. AUDIO: "audio",
  722. VIDEO: "video",
  723. AUDIOVIDEO: "audiovideo"
  724. };
  725. var BaseSegment = /*#__PURE__*/function () {
  726. function BaseSegment(baseurl) {
  727. var _this$elementaryStrea;
  728. this._byteRange = null;
  729. this._url = null;
  730. // baseurl is the URL to the playlist
  731. this.baseurl = void 0;
  732. // relurl is the portion of the URL that comes from inside the playlist.
  733. this.relurl = void 0;
  734. // Holds the types of data this fragment supports
  735. this.elementaryStreams = (_this$elementaryStrea = {}, _this$elementaryStrea[ElementaryStreamTypes.AUDIO] = null, _this$elementaryStrea[ElementaryStreamTypes.VIDEO] = null, _this$elementaryStrea[ElementaryStreamTypes.AUDIOVIDEO] = null, _this$elementaryStrea);
  736. this.baseurl = baseurl;
  737. }
  738. // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array
  739. var _proto = BaseSegment.prototype;
  740. _proto.setByteRange = function setByteRange(value, previous) {
  741. var params = value.split('@', 2);
  742. var start;
  743. if (params.length === 1) {
  744. start = (previous == null ? void 0 : previous.byteRangeEndOffset) || 0;
  745. } else {
  746. start = parseInt(params[1]);
  747. }
  748. this._byteRange = [start, parseInt(params[0]) + start];
  749. };
  750. _createClass(BaseSegment, [{
  751. key: "byteRange",
  752. get: function get() {
  753. if (!this._byteRange) {
  754. return [];
  755. }
  756. return this._byteRange;
  757. }
  758. }, {
  759. key: "byteRangeStartOffset",
  760. get: function get() {
  761. return this.byteRange[0];
  762. }
  763. }, {
  764. key: "byteRangeEndOffset",
  765. get: function get() {
  766. return this.byteRange[1];
  767. }
  768. }, {
  769. key: "url",
  770. get: function get() {
  771. if (!this._url && this.baseurl && this.relurl) {
  772. this._url = urlToolkitExports.buildAbsoluteURL(this.baseurl, this.relurl, {
  773. alwaysNormalize: true
  774. });
  775. }
  776. return this._url || '';
  777. },
  778. set: function set(value) {
  779. this._url = value;
  780. }
  781. }]);
  782. return BaseSegment;
  783. }();
  784. /**
  785. * Object representing parsed data from an HLS Segment. Found in {@link hls.js#LevelDetails.fragments}.
  786. */
  787. var Fragment = /*#__PURE__*/function (_BaseSegment) {
  788. _inheritsLoose(Fragment, _BaseSegment);
  789. function Fragment(type, baseurl) {
  790. var _this;
  791. _this = _BaseSegment.call(this, baseurl) || this;
  792. _this._decryptdata = null;
  793. _this.rawProgramDateTime = null;
  794. _this.programDateTime = null;
  795. _this.tagList = [];
  796. // EXTINF has to be present for a m3u8 to be considered valid
  797. _this.duration = 0;
  798. // sn notates the sequence number for a segment, and if set to a string can be 'initSegment'
  799. _this.sn = 0;
  800. // levelkeys are the EXT-X-KEY tags that apply to this segment for decryption
  801. // core difference from the private field _decryptdata is the lack of the initialized IV
  802. // _decryptdata will set the IV for this segment based on the segment number in the fragment
  803. _this.levelkeys = void 0;
  804. // A string representing the fragment type
  805. _this.type = void 0;
  806. // A reference to the loader. Set while the fragment is loading, and removed afterwards. Used to abort fragment loading
  807. _this.loader = null;
  808. // A reference to the key loader. Set while the key is loading, and removed afterwards. Used to abort key loading
  809. _this.keyLoader = null;
  810. // The level/track index to which the fragment belongs
  811. _this.level = -1;
  812. // The continuity counter of the fragment
  813. _this.cc = 0;
  814. // The starting Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.
  815. _this.startPTS = void 0;
  816. // The ending Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.
  817. _this.endPTS = void 0;
  818. // The starting Decode Time Stamp (DTS) of the fragment. Set after transmux complete.
  819. _this.startDTS = void 0;
  820. // The ending Decode Time Stamp (DTS) of the fragment. Set after transmux complete.
  821. _this.endDTS = void 0;
  822. // The start time of the fragment, as listed in the manifest. Updated after transmux complete.
  823. _this.start = 0;
  824. // Set by `updateFragPTSDTS` in level-helper
  825. _this.deltaPTS = void 0;
  826. // The maximum starting Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.
  827. _this.maxStartPTS = void 0;
  828. // The minimum ending Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.
  829. _this.minEndPTS = void 0;
  830. // Load/parse timing information
  831. _this.stats = new LoadStats();
  832. // Init Segment bytes (unset for media segments)
  833. _this.data = void 0;
  834. // A flag indicating whether the segment was downloaded in order to test bitrate, and was not buffered
  835. _this.bitrateTest = false;
  836. // #EXTINF segment title
  837. _this.title = null;
  838. // The Media Initialization Section for this segment
  839. _this.initSegment = null;
  840. // Fragment is the last fragment in the media playlist
  841. _this.endList = void 0;
  842. // Fragment is marked by an EXT-X-GAP tag indicating that it does not contain media data and should not be loaded
  843. _this.gap = void 0;
  844. // Deprecated
  845. _this.urlId = 0;
  846. _this.type = type;
  847. return _this;
  848. }
  849. var _proto2 = Fragment.prototype;
  850. _proto2.setKeyFormat = function setKeyFormat(keyFormat) {
  851. if (this.levelkeys) {
  852. var _key = this.levelkeys[keyFormat];
  853. if (_key && !this._decryptdata) {
  854. this._decryptdata = _key.getDecryptData(this.sn);
  855. }
  856. }
  857. };
  858. _proto2.abortRequests = function abortRequests() {
  859. var _this$loader, _this$keyLoader;
  860. (_this$loader = this.loader) == null ? void 0 : _this$loader.abort();
  861. (_this$keyLoader = this.keyLoader) == null ? void 0 : _this$keyLoader.abort();
  862. };
  863. _proto2.setElementaryStreamInfo = function setElementaryStreamInfo(type, startPTS, endPTS, startDTS, endDTS, partial) {
  864. if (partial === void 0) {
  865. partial = false;
  866. }
  867. var elementaryStreams = this.elementaryStreams;
  868. var info = elementaryStreams[type];
  869. if (!info) {
  870. elementaryStreams[type] = {
  871. startPTS: startPTS,
  872. endPTS: endPTS,
  873. startDTS: startDTS,
  874. endDTS: endDTS,
  875. partial: partial
  876. };
  877. return;
  878. }
  879. info.startPTS = Math.min(info.startPTS, startPTS);
  880. info.endPTS = Math.max(info.endPTS, endPTS);
  881. info.startDTS = Math.min(info.startDTS, startDTS);
  882. info.endDTS = Math.max(info.endDTS, endDTS);
  883. };
  884. _proto2.clearElementaryStreamInfo = function clearElementaryStreamInfo() {
  885. var elementaryStreams = this.elementaryStreams;
  886. elementaryStreams[ElementaryStreamTypes.AUDIO] = null;
  887. elementaryStreams[ElementaryStreamTypes.VIDEO] = null;
  888. elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO] = null;
  889. };
  890. _createClass(Fragment, [{
  891. key: "decryptdata",
  892. get: function get() {
  893. var levelkeys = this.levelkeys;
  894. if (!levelkeys && !this._decryptdata) {
  895. return null;
  896. }
  897. if (!this._decryptdata && this.levelkeys && !this.levelkeys.NONE) {
  898. var _key2 = this.levelkeys.identity;
  899. if (_key2) {
  900. this._decryptdata = _key2.getDecryptData(this.sn);
  901. } else {
  902. var keyFormats = Object.keys(this.levelkeys);
  903. if (keyFormats.length === 1) {
  904. return this._decryptdata = this.levelkeys[keyFormats[0]].getDecryptData(this.sn);
  905. }
  906. }
  907. }
  908. return this._decryptdata;
  909. }
  910. }, {
  911. key: "end",
  912. get: function get() {
  913. return this.start + this.duration;
  914. }
  915. }, {
  916. key: "endProgramDateTime",
  917. get: function get() {
  918. if (this.programDateTime === null) {
  919. return null;
  920. }
  921. if (!isFiniteNumber(this.programDateTime)) {
  922. return null;
  923. }
  924. var duration = !isFiniteNumber(this.duration) ? 0 : this.duration;
  925. return this.programDateTime + duration * 1000;
  926. }
  927. }, {
  928. key: "encrypted",
  929. get: function get() {
  930. var _this$_decryptdata;
  931. // At the m3u8-parser level we need to add support for manifest signalled keyformats
  932. // when we want the fragment to start reporting that it is encrypted.
  933. // Currently, keyFormat will only be set for identity keys
  934. if ((_this$_decryptdata = this._decryptdata) != null && _this$_decryptdata.encrypted) {
  935. return true;
  936. } else if (this.levelkeys) {
  937. var keyFormats = Object.keys(this.levelkeys);
  938. var len = keyFormats.length;
  939. if (len > 1 || len === 1 && this.levelkeys[keyFormats[0]].encrypted) {
  940. return true;
  941. }
  942. }
  943. return false;
  944. }
  945. }]);
  946. return Fragment;
  947. }(BaseSegment);
  948. /**
  949. * Object representing parsed data from an HLS Partial Segment. Found in {@link hls.js#LevelDetails.partList}.
  950. */
  951. var Part = /*#__PURE__*/function (_BaseSegment2) {
  952. _inheritsLoose(Part, _BaseSegment2);
  953. function Part(partAttrs, frag, baseurl, index, previous) {
  954. var _this2;
  955. _this2 = _BaseSegment2.call(this, baseurl) || this;
  956. _this2.fragOffset = 0;
  957. _this2.duration = 0;
  958. _this2.gap = false;
  959. _this2.independent = false;
  960. _this2.relurl = void 0;
  961. _this2.fragment = void 0;
  962. _this2.index = void 0;
  963. _this2.stats = new LoadStats();
  964. _this2.duration = partAttrs.decimalFloatingPoint('DURATION');
  965. _this2.gap = partAttrs.bool('GAP');
  966. _this2.independent = partAttrs.bool('INDEPENDENT');
  967. _this2.relurl = partAttrs.enumeratedString('URI');
  968. _this2.fragment = frag;
  969. _this2.index = index;
  970. var byteRange = partAttrs.enumeratedString('BYTERANGE');
  971. if (byteRange) {
  972. _this2.setByteRange(byteRange, previous);
  973. }
  974. if (previous) {
  975. _this2.fragOffset = previous.fragOffset + previous.duration;
  976. }
  977. return _this2;
  978. }
  979. _createClass(Part, [{
  980. key: "start",
  981. get: function get() {
  982. return this.fragment.start + this.fragOffset;
  983. }
  984. }, {
  985. key: "end",
  986. get: function get() {
  987. return this.start + this.duration;
  988. }
  989. }, {
  990. key: "loaded",
  991. get: function get() {
  992. var elementaryStreams = this.elementaryStreams;
  993. return !!(elementaryStreams.audio || elementaryStreams.video || elementaryStreams.audiovideo);
  994. }
  995. }]);
  996. return Part;
  997. }(BaseSegment);
  998. var DEFAULT_TARGET_DURATION = 10;
  999. /**
  1000. * Object representing parsed data from an HLS Media Playlist. Found in {@link hls.js#Level.details}.
  1001. */
  1002. var LevelDetails = /*#__PURE__*/function () {
  1003. function LevelDetails(baseUrl) {
  1004. this.PTSKnown = false;
  1005. this.alignedSliding = false;
  1006. this.averagetargetduration = void 0;
  1007. this.endCC = 0;
  1008. this.endSN = 0;
  1009. this.fragments = void 0;
  1010. this.fragmentHint = void 0;
  1011. this.partList = null;
  1012. this.dateRanges = void 0;
  1013. this.live = true;
  1014. this.ageHeader = 0;
  1015. this.advancedDateTime = void 0;
  1016. this.updated = true;
  1017. this.advanced = true;
  1018. this.availabilityDelay = void 0;
  1019. // Manifest reload synchronization
  1020. this.misses = 0;
  1021. this.startCC = 0;
  1022. this.startSN = 0;
  1023. this.startTimeOffset = null;
  1024. this.targetduration = 0;
  1025. this.totalduration = 0;
  1026. this.type = null;
  1027. this.url = void 0;
  1028. this.m3u8 = '';
  1029. this.version = null;
  1030. this.canBlockReload = false;
  1031. this.canSkipUntil = 0;
  1032. this.canSkipDateRanges = false;
  1033. this.skippedSegments = 0;
  1034. this.recentlyRemovedDateranges = void 0;
  1035. this.partHoldBack = 0;
  1036. this.holdBack = 0;
  1037. this.partTarget = 0;
  1038. this.preloadHint = void 0;
  1039. this.renditionReports = void 0;
  1040. this.tuneInGoal = 0;
  1041. this.deltaUpdateFailed = void 0;
  1042. this.driftStartTime = 0;
  1043. this.driftEndTime = 0;
  1044. this.driftStart = 0;
  1045. this.driftEnd = 0;
  1046. this.encryptedFragments = void 0;
  1047. this.playlistParsingError = null;
  1048. this.variableList = null;
  1049. this.hasVariableRefs = false;
  1050. this.fragments = [];
  1051. this.encryptedFragments = [];
  1052. this.dateRanges = {};
  1053. this.url = baseUrl;
  1054. }
  1055. var _proto = LevelDetails.prototype;
  1056. _proto.reloaded = function reloaded(previous) {
  1057. if (!previous) {
  1058. this.advanced = true;
  1059. this.updated = true;
  1060. return;
  1061. }
  1062. var partSnDiff = this.lastPartSn - previous.lastPartSn;
  1063. var partIndexDiff = this.lastPartIndex - previous.lastPartIndex;
  1064. this.updated = this.endSN !== previous.endSN || !!partIndexDiff || !!partSnDiff || !this.live;
  1065. this.advanced = this.endSN > previous.endSN || partSnDiff > 0 || partSnDiff === 0 && partIndexDiff > 0;
  1066. if (this.updated || this.advanced) {
  1067. this.misses = Math.floor(previous.misses * 0.6);
  1068. } else {
  1069. this.misses = previous.misses + 1;
  1070. }
  1071. this.availabilityDelay = previous.availabilityDelay;
  1072. };
  1073. _createClass(LevelDetails, [{
  1074. key: "hasProgramDateTime",
  1075. get: function get() {
  1076. if (this.fragments.length) {
  1077. return isFiniteNumber(this.fragments[this.fragments.length - 1].programDateTime);
  1078. }
  1079. return false;
  1080. }
  1081. }, {
  1082. key: "levelTargetDuration",
  1083. get: function get() {
  1084. return this.averagetargetduration || this.targetduration || DEFAULT_TARGET_DURATION;
  1085. }
  1086. }, {
  1087. key: "drift",
  1088. get: function get() {
  1089. var runTime = this.driftEndTime - this.driftStartTime;
  1090. if (runTime > 0) {
  1091. var runDuration = this.driftEnd - this.driftStart;
  1092. return runDuration * 1000 / runTime;
  1093. }
  1094. return 1;
  1095. }
  1096. }, {
  1097. key: "edge",
  1098. get: function get() {
  1099. return this.partEnd || this.fragmentEnd;
  1100. }
  1101. }, {
  1102. key: "partEnd",
  1103. get: function get() {
  1104. var _this$partList;
  1105. if ((_this$partList = this.partList) != null && _this$partList.length) {
  1106. return this.partList[this.partList.length - 1].end;
  1107. }
  1108. return this.fragmentEnd;
  1109. }
  1110. }, {
  1111. key: "fragmentEnd",
  1112. get: function get() {
  1113. var _this$fragments;
  1114. if ((_this$fragments = this.fragments) != null && _this$fragments.length) {
  1115. return this.fragments[this.fragments.length - 1].end;
  1116. }
  1117. return 0;
  1118. }
  1119. }, {
  1120. key: "age",
  1121. get: function get() {
  1122. if (this.advancedDateTime) {
  1123. return Math.max(Date.now() - this.advancedDateTime, 0) / 1000;
  1124. }
  1125. return 0;
  1126. }
  1127. }, {
  1128. key: "lastPartIndex",
  1129. get: function get() {
  1130. var _this$partList2;
  1131. if ((_this$partList2 = this.partList) != null && _this$partList2.length) {
  1132. return this.partList[this.partList.length - 1].index;
  1133. }
  1134. return -1;
  1135. }
  1136. }, {
  1137. key: "lastPartSn",
  1138. get: function get() {
  1139. var _this$partList3;
  1140. if ((_this$partList3 = this.partList) != null && _this$partList3.length) {
  1141. return this.partList[this.partList.length - 1].fragment.sn;
  1142. }
  1143. return this.endSN;
  1144. }
  1145. }]);
  1146. return LevelDetails;
  1147. }();
  1148. // This file is inserted as a shim for modules which we do not want to include into the distro.
  1149. // This replacement is done in the "alias" plugin of the rollup config.
  1150. var empty = undefined;
  1151. var Cues = /*@__PURE__*/getDefaultExportFromCjs(empty);
  1152. function sliceUint8(array, start, end) {
  1153. // @ts-expect-error This polyfills IE11 usage of Uint8Array slice.
  1154. // It always exists in the TypeScript definition so fails, but it fails at runtime on IE11.
  1155. return Uint8Array.prototype.slice ? array.slice(start, end) : new Uint8Array(Array.prototype.slice.call(array, start, end));
  1156. }
  1157. // breaking up those two types in order to clarify what is happening in the decoding path.
  1158. /**
  1159. * Returns true if an ID3 header can be found at offset in data
  1160. * @param data - The data to search
  1161. * @param offset - The offset at which to start searching
  1162. */
  1163. var isHeader$2 = function isHeader(data, offset) {
  1164. /*
  1165. * http://id3.org/id3v2.3.0
  1166. * [0] = 'I'
  1167. * [1] = 'D'
  1168. * [2] = '3'
  1169. * [3,4] = {Version}
  1170. * [5] = {Flags}
  1171. * [6-9] = {ID3 Size}
  1172. *
  1173. * An ID3v2 tag can be detected with the following pattern:
  1174. * $49 44 33 yy yy xx zz zz zz zz
  1175. * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80
  1176. */
  1177. if (offset + 10 <= data.length) {
  1178. // look for 'ID3' identifier
  1179. if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) {
  1180. // check version is within range
  1181. if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {
  1182. // check size is within range
  1183. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  1184. return true;
  1185. }
  1186. }
  1187. }
  1188. }
  1189. return false;
  1190. };
  1191. /**
  1192. * Returns true if an ID3 footer can be found at offset in data
  1193. * @param data - The data to search
  1194. * @param offset - The offset at which to start searching
  1195. */
  1196. var isFooter = function isFooter(data, offset) {
  1197. /*
  1198. * The footer is a copy of the header, but with a different identifier
  1199. */
  1200. if (offset + 10 <= data.length) {
  1201. // look for '3DI' identifier
  1202. if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) {
  1203. // check version is within range
  1204. if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {
  1205. // check size is within range
  1206. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  1207. return true;
  1208. }
  1209. }
  1210. }
  1211. }
  1212. return false;
  1213. };
  1214. /**
  1215. * Returns any adjacent ID3 tags found in data starting at offset, as one block of data
  1216. * @param data - The data to search in
  1217. * @param offset - The offset at which to start searching
  1218. * @returns the block of data containing any ID3 tags found
  1219. * or *undefined* if no header is found at the starting offset
  1220. */
  1221. var getID3Data = function getID3Data(data, offset) {
  1222. var front = offset;
  1223. var length = 0;
  1224. while (isHeader$2(data, offset)) {
  1225. // ID3 header is 10 bytes
  1226. length += 10;
  1227. var size = readSize(data, offset + 6);
  1228. length += size;
  1229. if (isFooter(data, offset + 10)) {
  1230. // ID3 footer is 10 bytes
  1231. length += 10;
  1232. }
  1233. offset += length;
  1234. }
  1235. if (length > 0) {
  1236. return data.subarray(front, front + length);
  1237. }
  1238. return undefined;
  1239. };
  1240. var readSize = function readSize(data, offset) {
  1241. var size = 0;
  1242. size = (data[offset] & 0x7f) << 21;
  1243. size |= (data[offset + 1] & 0x7f) << 14;
  1244. size |= (data[offset + 2] & 0x7f) << 7;
  1245. size |= data[offset + 3] & 0x7f;
  1246. return size;
  1247. };
  1248. var canParse$2 = function canParse(data, offset) {
  1249. return isHeader$2(data, offset) && readSize(data, offset + 6) + 10 <= data.length - offset;
  1250. };
  1251. /**
  1252. * Searches for the Elementary Stream timestamp found in the ID3 data chunk
  1253. * @param data - Block of data containing one or more ID3 tags
  1254. */
  1255. var getTimeStamp = function getTimeStamp(data) {
  1256. var frames = getID3Frames(data);
  1257. for (var i = 0; i < frames.length; i++) {
  1258. var frame = frames[i];
  1259. if (isTimeStampFrame(frame)) {
  1260. return readTimeStamp(frame);
  1261. }
  1262. }
  1263. return undefined;
  1264. };
  1265. /**
  1266. * Returns true if the ID3 frame is an Elementary Stream timestamp frame
  1267. */
  1268. var isTimeStampFrame = function isTimeStampFrame(frame) {
  1269. return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp';
  1270. };
  1271. var getFrameData = function getFrameData(data) {
  1272. /*
  1273. Frame ID $xx xx xx xx (four characters)
  1274. Size $xx xx xx xx
  1275. Flags $xx xx
  1276. */
  1277. var type = String.fromCharCode(data[0], data[1], data[2], data[3]);
  1278. var size = readSize(data, 4);
  1279. // skip frame id, size, and flags
  1280. var offset = 10;
  1281. return {
  1282. type: type,
  1283. size: size,
  1284. data: data.subarray(offset, offset + size)
  1285. };
  1286. };
  1287. /**
  1288. * Returns an array of ID3 frames found in all the ID3 tags in the id3Data
  1289. * @param id3Data - The ID3 data containing one or more ID3 tags
  1290. */
  1291. var getID3Frames = function getID3Frames(id3Data) {
  1292. var offset = 0;
  1293. var frames = [];
  1294. while (isHeader$2(id3Data, offset)) {
  1295. var size = readSize(id3Data, offset + 6);
  1296. // skip past ID3 header
  1297. offset += 10;
  1298. var end = offset + size;
  1299. // loop through frames in the ID3 tag
  1300. while (offset + 8 < end) {
  1301. var frameData = getFrameData(id3Data.subarray(offset));
  1302. var frame = decodeFrame(frameData);
  1303. if (frame) {
  1304. frames.push(frame);
  1305. }
  1306. // skip frame header and frame data
  1307. offset += frameData.size + 10;
  1308. }
  1309. if (isFooter(id3Data, offset)) {
  1310. offset += 10;
  1311. }
  1312. }
  1313. return frames;
  1314. };
  1315. var decodeFrame = function decodeFrame(frame) {
  1316. if (frame.type === 'PRIV') {
  1317. return decodePrivFrame(frame);
  1318. } else if (frame.type[0] === 'W') {
  1319. return decodeURLFrame(frame);
  1320. }
  1321. return decodeTextFrame(frame);
  1322. };
  1323. var decodePrivFrame = function decodePrivFrame(frame) {
  1324. /*
  1325. Format: <text string>\0<binary data>
  1326. */
  1327. if (frame.size < 2) {
  1328. return undefined;
  1329. }
  1330. var owner = utf8ArrayToStr(frame.data, true);
  1331. var privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
  1332. return {
  1333. key: frame.type,
  1334. info: owner,
  1335. data: privateData.buffer
  1336. };
  1337. };
  1338. var decodeTextFrame = function decodeTextFrame(frame) {
  1339. if (frame.size < 2) {
  1340. return undefined;
  1341. }
  1342. if (frame.type === 'TXXX') {
  1343. /*
  1344. Format:
  1345. [0] = {Text Encoding}
  1346. [1-?] = {Description}\0{Value}
  1347. */
  1348. var index = 1;
  1349. var description = utf8ArrayToStr(frame.data.subarray(index), true);
  1350. index += description.length + 1;
  1351. var value = utf8ArrayToStr(frame.data.subarray(index));
  1352. return {
  1353. key: frame.type,
  1354. info: description,
  1355. data: value
  1356. };
  1357. }
  1358. /*
  1359. Format:
  1360. [0] = {Text Encoding}
  1361. [1-?] = {Value}
  1362. */
  1363. var text = utf8ArrayToStr(frame.data.subarray(1));
  1364. return {
  1365. key: frame.type,
  1366. data: text
  1367. };
  1368. };
  1369. var decodeURLFrame = function decodeURLFrame(frame) {
  1370. if (frame.type === 'WXXX') {
  1371. /*
  1372. Format:
  1373. [0] = {Text Encoding}
  1374. [1-?] = {Description}\0{URL}
  1375. */
  1376. if (frame.size < 2) {
  1377. return undefined;
  1378. }
  1379. var index = 1;
  1380. var description = utf8ArrayToStr(frame.data.subarray(index), true);
  1381. index += description.length + 1;
  1382. var value = utf8ArrayToStr(frame.data.subarray(index));
  1383. return {
  1384. key: frame.type,
  1385. info: description,
  1386. data: value
  1387. };
  1388. }
  1389. /*
  1390. Format:
  1391. [0-?] = {URL}
  1392. */
  1393. var url = utf8ArrayToStr(frame.data);
  1394. return {
  1395. key: frame.type,
  1396. data: url
  1397. };
  1398. };
  1399. var readTimeStamp = function readTimeStamp(timeStampFrame) {
  1400. if (timeStampFrame.data.byteLength === 8) {
  1401. var data = new Uint8Array(timeStampFrame.data);
  1402. // timestamp is 33 bit expressed as a big-endian eight-octet number,
  1403. // with the upper 31 bits set to zero.
  1404. var pts33Bit = data[3] & 0x1;
  1405. var timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];
  1406. timestamp /= 45;
  1407. if (pts33Bit) {
  1408. timestamp += 47721858.84;
  1409. } // 2^32 / 90
  1410. return Math.round(timestamp);
  1411. }
  1412. return undefined;
  1413. };
  1414. // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197
  1415. // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
  1416. /* utf.js - UTF-8 <=> UTF-16 convertion
  1417. *
  1418. * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
  1419. * Version: 1.0
  1420. * LastModified: Dec 25 1999
  1421. * This library is free. You can redistribute it and/or modify it.
  1422. */
  1423. var utf8ArrayToStr = function utf8ArrayToStr(array, exitOnNull) {
  1424. if (exitOnNull === void 0) {
  1425. exitOnNull = false;
  1426. }
  1427. var decoder = getTextDecoder();
  1428. if (decoder) {
  1429. var decoded = decoder.decode(array);
  1430. if (exitOnNull) {
  1431. // grab up to the first null
  1432. var idx = decoded.indexOf('\0');
  1433. return idx !== -1 ? decoded.substring(0, idx) : decoded;
  1434. }
  1435. // remove any null characters
  1436. return decoded.replace(/\0/g, '');
  1437. }
  1438. var len = array.length;
  1439. var c;
  1440. var char2;
  1441. var char3;
  1442. var out = '';
  1443. var i = 0;
  1444. while (i < len) {
  1445. c = array[i++];
  1446. if (c === 0x00 && exitOnNull) {
  1447. return out;
  1448. } else if (c === 0x00 || c === 0x03) {
  1449. // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it
  1450. continue;
  1451. }
  1452. switch (c >> 4) {
  1453. case 0:
  1454. case 1:
  1455. case 2:
  1456. case 3:
  1457. case 4:
  1458. case 5:
  1459. case 6:
  1460. case 7:
  1461. // 0xxxxxxx
  1462. out += String.fromCharCode(c);
  1463. break;
  1464. case 12:
  1465. case 13:
  1466. // 110x xxxx 10xx xxxx
  1467. char2 = array[i++];
  1468. out += String.fromCharCode((c & 0x1f) << 6 | char2 & 0x3f);
  1469. break;
  1470. case 14:
  1471. // 1110 xxxx 10xx xxxx 10xx xxxx
  1472. char2 = array[i++];
  1473. char3 = array[i++];
  1474. out += String.fromCharCode((c & 0x0f) << 12 | (char2 & 0x3f) << 6 | (char3 & 0x3f) << 0);
  1475. break;
  1476. }
  1477. }
  1478. return out;
  1479. };
  1480. var decoder;
  1481. function getTextDecoder() {
  1482. // On Play Station 4, TextDecoder is defined but partially implemented.
  1483. // Manual decoding option is preferable
  1484. if (navigator.userAgent.includes('PlayStation 4')) {
  1485. return;
  1486. }
  1487. if (!decoder && typeof self.TextDecoder !== 'undefined') {
  1488. decoder = new self.TextDecoder('utf-8');
  1489. }
  1490. return decoder;
  1491. }
  1492. /**
  1493. * hex dump helper class
  1494. */
  1495. var Hex = {
  1496. hexDump: function hexDump(array) {
  1497. var str = '';
  1498. for (var i = 0; i < array.length; i++) {
  1499. var h = array[i].toString(16);
  1500. if (h.length < 2) {
  1501. h = '0' + h;
  1502. }
  1503. str += h;
  1504. }
  1505. return str;
  1506. }
  1507. };
  1508. var UINT32_MAX$1 = Math.pow(2, 32) - 1;
  1509. var push = [].push;
  1510. // We are using fixed track IDs for driving the MP4 remuxer
  1511. // instead of following the TS PIDs.
  1512. // There is no reason not to do this and some browsers/SourceBuffer-demuxers
  1513. // may not like if there are TrackID "switches"
  1514. // See https://github.com/video-dev/hls.js/issues/1331
  1515. // Here we are mapping our internal track types to constant MP4 track IDs
  1516. // With MSE currently one can only have one track of each, and we are muxing
  1517. // whatever video/audio rendition in them.
  1518. var RemuxerTrackIdConfig = {
  1519. video: 1,
  1520. audio: 2,
  1521. id3: 3,
  1522. text: 4
  1523. };
  1524. function bin2str(data) {
  1525. return String.fromCharCode.apply(null, data);
  1526. }
  1527. function readUint16(buffer, offset) {
  1528. var val = buffer[offset] << 8 | buffer[offset + 1];
  1529. return val < 0 ? 65536 + val : val;
  1530. }
  1531. function readUint32(buffer, offset) {
  1532. var val = readSint32(buffer, offset);
  1533. return val < 0 ? 4294967296 + val : val;
  1534. }
  1535. function readUint64(buffer, offset) {
  1536. var result = readUint32(buffer, offset);
  1537. result *= Math.pow(2, 32);
  1538. result += readUint32(buffer, offset + 4);
  1539. return result;
  1540. }
  1541. function readSint32(buffer, offset) {
  1542. return buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];
  1543. }
  1544. function writeUint32(buffer, offset, value) {
  1545. buffer[offset] = value >> 24;
  1546. buffer[offset + 1] = value >> 16 & 0xff;
  1547. buffer[offset + 2] = value >> 8 & 0xff;
  1548. buffer[offset + 3] = value & 0xff;
  1549. }
  1550. // Find "moof" box
  1551. function hasMoofData(data) {
  1552. var end = data.byteLength;
  1553. for (var i = 0; i < end;) {
  1554. var size = readUint32(data, i);
  1555. if (size > 8 && data[i + 4] === 0x6d && data[i + 5] === 0x6f && data[i + 6] === 0x6f && data[i + 7] === 0x66) {
  1556. return true;
  1557. }
  1558. i = size > 1 ? i + size : end;
  1559. }
  1560. return false;
  1561. }
  1562. // Find the data for a box specified by its path
  1563. function findBox(data, path) {
  1564. var results = [];
  1565. if (!path.length) {
  1566. // short-circuit the search for empty paths
  1567. return results;
  1568. }
  1569. var end = data.byteLength;
  1570. for (var i = 0; i < end;) {
  1571. var size = readUint32(data, i);
  1572. var type = bin2str(data.subarray(i + 4, i + 8));
  1573. var endbox = size > 1 ? i + size : end;
  1574. if (type === path[0]) {
  1575. if (path.length === 1) {
  1576. // this is the end of the path and we've found the box we were
  1577. // looking for
  1578. results.push(data.subarray(i + 8, endbox));
  1579. } else {
  1580. // recursively search for the next box along the path
  1581. var subresults = findBox(data.subarray(i + 8, endbox), path.slice(1));
  1582. if (subresults.length) {
  1583. push.apply(results, subresults);
  1584. }
  1585. }
  1586. }
  1587. i = endbox;
  1588. }
  1589. // we've finished searching all of data
  1590. return results;
  1591. }
  1592. function parseSegmentIndex(sidx) {
  1593. var references = [];
  1594. var version = sidx[0];
  1595. // set initial offset, we skip the reference ID (not needed)
  1596. var index = 8;
  1597. var timescale = readUint32(sidx, index);
  1598. index += 4;
  1599. var earliestPresentationTime = 0;
  1600. var firstOffset = 0;
  1601. if (version === 0) {
  1602. earliestPresentationTime = readUint32(sidx, index);
  1603. firstOffset = readUint32(sidx, index + 4);
  1604. index += 8;
  1605. } else {
  1606. earliestPresentationTime = readUint64(sidx, index);
  1607. firstOffset = readUint64(sidx, index + 8);
  1608. index += 16;
  1609. }
  1610. // skip reserved
  1611. index += 2;
  1612. var startByte = sidx.length + firstOffset;
  1613. var referencesCount = readUint16(sidx, index);
  1614. index += 2;
  1615. for (var i = 0; i < referencesCount; i++) {
  1616. var referenceIndex = index;
  1617. var referenceInfo = readUint32(sidx, referenceIndex);
  1618. referenceIndex += 4;
  1619. var referenceSize = referenceInfo & 0x7fffffff;
  1620. var referenceType = (referenceInfo & 0x80000000) >>> 31;
  1621. if (referenceType === 1) {
  1622. logger.warn('SIDX has hierarchical references (not supported)');
  1623. return null;
  1624. }
  1625. var subsegmentDuration = readUint32(sidx, referenceIndex);
  1626. referenceIndex += 4;
  1627. references.push({
  1628. referenceSize: referenceSize,
  1629. subsegmentDuration: subsegmentDuration,
  1630. // unscaled
  1631. info: {
  1632. duration: subsegmentDuration / timescale,
  1633. start: startByte,
  1634. end: startByte + referenceSize - 1
  1635. }
  1636. });
  1637. startByte += referenceSize;
  1638. // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits
  1639. // for |sapDelta|.
  1640. referenceIndex += 4;
  1641. // skip to next ref
  1642. index = referenceIndex;
  1643. }
  1644. return {
  1645. earliestPresentationTime: earliestPresentationTime,
  1646. timescale: timescale,
  1647. version: version,
  1648. referencesCount: referencesCount,
  1649. references: references
  1650. };
  1651. }
  1652. /**
  1653. * Parses an MP4 initialization segment and extracts stream type and
  1654. * timescale values for any declared tracks. Timescale values indicate the
  1655. * number of clock ticks per second to assume for time-based values
  1656. * elsewhere in the MP4.
  1657. *
  1658. * To determine the start time of an MP4, you need two pieces of
  1659. * information: the timescale unit and the earliest base media decode
  1660. * time. Multiple timescales can be specified within an MP4 but the
  1661. * base media decode time is always expressed in the timescale from
  1662. * the media header box for the track:
  1663. * ```
  1664. * moov > trak > mdia > mdhd.timescale
  1665. * moov > trak > mdia > hdlr
  1666. * ```
  1667. * @param initSegment the bytes of the init segment
  1668. * @returns a hash of track type to timescale values or null if
  1669. * the init segment is malformed.
  1670. */
  1671. function parseInitSegment(initSegment) {
  1672. var result = [];
  1673. var traks = findBox(initSegment, ['moov', 'trak']);
  1674. for (var i = 0; i < traks.length; i++) {
  1675. var trak = traks[i];
  1676. var tkhd = findBox(trak, ['tkhd'])[0];
  1677. if (tkhd) {
  1678. var version = tkhd[0];
  1679. var trackId = readUint32(tkhd, version === 0 ? 12 : 20);
  1680. var mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  1681. if (mdhd) {
  1682. version = mdhd[0];
  1683. var timescale = readUint32(mdhd, version === 0 ? 12 : 20);
  1684. var hdlr = findBox(trak, ['mdia', 'hdlr'])[0];
  1685. if (hdlr) {
  1686. var hdlrType = bin2str(hdlr.subarray(8, 12));
  1687. var type = {
  1688. soun: ElementaryStreamTypes.AUDIO,
  1689. vide: ElementaryStreamTypes.VIDEO
  1690. }[hdlrType];
  1691. if (type) {
  1692. // Parse codec details
  1693. var stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  1694. var stsdData = parseStsd(stsd);
  1695. result[trackId] = {
  1696. timescale: timescale,
  1697. type: type
  1698. };
  1699. result[type] = _objectSpread2({
  1700. timescale: timescale,
  1701. id: trackId
  1702. }, stsdData);
  1703. }
  1704. }
  1705. }
  1706. }
  1707. }
  1708. var trex = findBox(initSegment, ['moov', 'mvex', 'trex']);
  1709. trex.forEach(function (trex) {
  1710. var trackId = readUint32(trex, 4);
  1711. var track = result[trackId];
  1712. if (track) {
  1713. track.default = {
  1714. duration: readUint32(trex, 12),
  1715. flags: readUint32(trex, 20)
  1716. };
  1717. }
  1718. });
  1719. return result;
  1720. }
  1721. function parseStsd(stsd) {
  1722. var sampleEntries = stsd.subarray(8);
  1723. var sampleEntriesEnd = sampleEntries.subarray(8 + 78);
  1724. var fourCC = bin2str(sampleEntries.subarray(4, 8));
  1725. var codec = fourCC;
  1726. var encrypted = fourCC === 'enca' || fourCC === 'encv';
  1727. if (encrypted) {
  1728. var encBox = findBox(sampleEntries, [fourCC])[0];
  1729. var encBoxChildren = encBox.subarray(fourCC === 'enca' ? 28 : 78);
  1730. var sinfs = findBox(encBoxChildren, ['sinf']);
  1731. sinfs.forEach(function (sinf) {
  1732. var schm = findBox(sinf, ['schm'])[0];
  1733. if (schm) {
  1734. var scheme = bin2str(schm.subarray(4, 8));
  1735. if (scheme === 'cbcs' || scheme === 'cenc') {
  1736. var frma = findBox(sinf, ['frma'])[0];
  1737. if (frma) {
  1738. // for encrypted content codec fourCC will be in frma
  1739. codec = bin2str(frma);
  1740. }
  1741. }
  1742. }
  1743. });
  1744. }
  1745. switch (codec) {
  1746. case 'avc1':
  1747. case 'avc2':
  1748. case 'avc3':
  1749. case 'avc4':
  1750. {
  1751. // extract profile + compatibility + level out of avcC box
  1752. var avcCBox = findBox(sampleEntriesEnd, ['avcC'])[0];
  1753. codec += '.' + toHex(avcCBox[1]) + toHex(avcCBox[2]) + toHex(avcCBox[3]);
  1754. break;
  1755. }
  1756. case 'mp4a':
  1757. {
  1758. var codecBox = findBox(sampleEntries, [fourCC])[0];
  1759. var esdsBox = findBox(codecBox.subarray(28), ['esds'])[0];
  1760. if (esdsBox && esdsBox.length > 12) {
  1761. var i = 4;
  1762. // ES Descriptor tag
  1763. if (esdsBox[i++] !== 0x03) {
  1764. break;
  1765. }
  1766. i = skipBERInteger(esdsBox, i);
  1767. i += 2; // skip es_id;
  1768. var flags = esdsBox[i++];
  1769. if (flags & 0x80) {
  1770. i += 2; // skip dependency es_id
  1771. }
  1772. if (flags & 0x40) {
  1773. i += esdsBox[i++]; // skip URL
  1774. }
  1775. // Decoder config descriptor
  1776. if (esdsBox[i++] !== 0x04) {
  1777. break;
  1778. }
  1779. i = skipBERInteger(esdsBox, i);
  1780. var objectType = esdsBox[i++];
  1781. if (objectType === 0x40) {
  1782. codec += '.' + toHex(objectType);
  1783. } else {
  1784. break;
  1785. }
  1786. i += 12;
  1787. // Decoder specific info
  1788. if (esdsBox[i++] !== 0x05) {
  1789. break;
  1790. }
  1791. i = skipBERInteger(esdsBox, i);
  1792. var firstByte = esdsBox[i++];
  1793. var audioObjectType = (firstByte & 0xf8) >> 3;
  1794. if (audioObjectType === 31) {
  1795. audioObjectType += 1 + ((firstByte & 0x7) << 3) + ((esdsBox[i] & 0xe0) >> 5);
  1796. }
  1797. codec += '.' + audioObjectType;
  1798. }
  1799. break;
  1800. }
  1801. case 'hvc1':
  1802. case 'hev1':
  1803. {
  1804. var hvcCBox = findBox(sampleEntriesEnd, ['hvcC'])[0];
  1805. var profileByte = hvcCBox[1];
  1806. var profileSpace = ['', 'A', 'B', 'C'][profileByte >> 6];
  1807. var generalProfileIdc = profileByte & 0x1f;
  1808. var profileCompat = readUint32(hvcCBox, 2);
  1809. var tierFlag = (profileByte & 0x20) >> 5 ? 'H' : 'L';
  1810. var levelIDC = hvcCBox[12];
  1811. var constraintIndicator = hvcCBox.subarray(6, 12);
  1812. codec += '.' + profileSpace + generalProfileIdc;
  1813. codec += '.' + profileCompat.toString(16).toUpperCase();
  1814. codec += '.' + tierFlag + levelIDC;
  1815. var constraintString = '';
  1816. for (var _i = constraintIndicator.length; _i--;) {
  1817. var _byte = constraintIndicator[_i];
  1818. if (_byte || constraintString) {
  1819. var encodedByte = _byte.toString(16).toUpperCase();
  1820. constraintString = '.' + encodedByte + constraintString;
  1821. }
  1822. }
  1823. codec += constraintString;
  1824. break;
  1825. }
  1826. case 'dvh1':
  1827. case 'dvhe':
  1828. {
  1829. var dvcCBox = findBox(sampleEntriesEnd, ['dvcC'])[0];
  1830. var profile = dvcCBox[2] >> 1 & 0x7f;
  1831. var level = dvcCBox[2] << 5 & 0x20 | dvcCBox[3] >> 3 & 0x1f;
  1832. codec += '.' + addLeadingZero(profile) + '.' + addLeadingZero(level);
  1833. break;
  1834. }
  1835. case 'vp09':
  1836. {
  1837. var vpcCBox = findBox(sampleEntriesEnd, ['vpcC'])[0];
  1838. var _profile = vpcCBox[4];
  1839. var _level = vpcCBox[5];
  1840. var bitDepth = vpcCBox[6] >> 4 & 0x0f;
  1841. codec += '.' + addLeadingZero(_profile) + '.' + addLeadingZero(_level) + '.' + addLeadingZero(bitDepth);
  1842. break;
  1843. }
  1844. case 'av01':
  1845. {
  1846. var av1CBox = findBox(sampleEntriesEnd, ['av1C'])[0];
  1847. var _profile2 = av1CBox[1] >>> 5;
  1848. var _level2 = av1CBox[1] & 0x1f;
  1849. var _tierFlag = av1CBox[2] >>> 7 ? 'H' : 'M';
  1850. var highBitDepth = (av1CBox[2] & 0x40) >> 6;
  1851. var twelveBit = (av1CBox[2] & 0x20) >> 5;
  1852. var _bitDepth = _profile2 === 2 && highBitDepth ? twelveBit ? 12 : 10 : highBitDepth ? 10 : 8;
  1853. var monochrome = (av1CBox[2] & 0x10) >> 4;
  1854. var chromaSubsamplingX = (av1CBox[2] & 0x08) >> 3;
  1855. var chromaSubsamplingY = (av1CBox[2] & 0x04) >> 2;
  1856. var chromaSamplePosition = av1CBox[2] & 0x03;
  1857. // TODO: parse color_description_present_flag
  1858. // default it to BT.709/limited range for now
  1859. // more info https://aomediacodec.github.io/av1-isobmff/#av1codecconfigurationbox-syntax
  1860. var colorPrimaries = 1;
  1861. var transferCharacteristics = 1;
  1862. var matrixCoefficients = 1;
  1863. var videoFullRangeFlag = 0;
  1864. codec += '.' + _profile2 + '.' + addLeadingZero(_level2) + _tierFlag + '.' + addLeadingZero(_bitDepth) + '.' + monochrome + '.' + chromaSubsamplingX + chromaSubsamplingY + chromaSamplePosition + '.' + addLeadingZero(colorPrimaries) + '.' + addLeadingZero(transferCharacteristics) + '.' + addLeadingZero(matrixCoefficients) + '.' + videoFullRangeFlag;
  1865. break;
  1866. }
  1867. }
  1868. return {
  1869. codec: codec,
  1870. encrypted: encrypted
  1871. };
  1872. }
  1873. function skipBERInteger(bytes, i) {
  1874. var limit = i + 5;
  1875. while (bytes[i++] & 0x80 && i < limit) {}
  1876. return i;
  1877. }
  1878. function toHex(x) {
  1879. return ('0' + x.toString(16).toUpperCase()).slice(-2);
  1880. }
  1881. function addLeadingZero(num) {
  1882. return (num < 10 ? '0' : '') + num;
  1883. }
  1884. function patchEncyptionData(initSegment, decryptdata) {
  1885. if (!initSegment || !decryptdata) {
  1886. return initSegment;
  1887. }
  1888. var keyId = decryptdata.keyId;
  1889. if (keyId && decryptdata.isCommonEncryption) {
  1890. var traks = findBox(initSegment, ['moov', 'trak']);
  1891. traks.forEach(function (trak) {
  1892. var stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  1893. // skip the sample entry count
  1894. var sampleEntries = stsd.subarray(8);
  1895. var encBoxes = findBox(sampleEntries, ['enca']);
  1896. var isAudio = encBoxes.length > 0;
  1897. if (!isAudio) {
  1898. encBoxes = findBox(sampleEntries, ['encv']);
  1899. }
  1900. encBoxes.forEach(function (enc) {
  1901. var encBoxChildren = isAudio ? enc.subarray(28) : enc.subarray(78);
  1902. var sinfBoxes = findBox(encBoxChildren, ['sinf']);
  1903. sinfBoxes.forEach(function (sinf) {
  1904. var tenc = parseSinf(sinf);
  1905. if (tenc) {
  1906. // Look for default key id (keyID offset is always 8 within the tenc box):
  1907. var tencKeyId = tenc.subarray(8, 24);
  1908. if (!tencKeyId.some(function (b) {
  1909. return b !== 0;
  1910. })) {
  1911. logger.log("[eme] Patching keyId in 'enc" + (isAudio ? 'a' : 'v') + ">sinf>>tenc' box: " + Hex.hexDump(tencKeyId) + " -> " + Hex.hexDump(keyId));
  1912. tenc.set(keyId, 8);
  1913. }
  1914. }
  1915. });
  1916. });
  1917. });
  1918. }
  1919. return initSegment;
  1920. }
  1921. function parseSinf(sinf) {
  1922. var schm = findBox(sinf, ['schm'])[0];
  1923. if (schm) {
  1924. var scheme = bin2str(schm.subarray(4, 8));
  1925. if (scheme === 'cbcs' || scheme === 'cenc') {
  1926. return findBox(sinf, ['schi', 'tenc'])[0];
  1927. }
  1928. }
  1929. return null;
  1930. }
  1931. /**
  1932. * Determine the base media decode start time, in seconds, for an MP4
  1933. * fragment. If multiple fragments are specified, the earliest time is
  1934. * returned.
  1935. *
  1936. * The base media decode time can be parsed from track fragment
  1937. * metadata:
  1938. * ```
  1939. * moof > traf > tfdt.baseMediaDecodeTime
  1940. * ```
  1941. * It requires the timescale value from the mdhd to interpret.
  1942. *
  1943. * @param initData - a hash of track type to timescale values
  1944. * @param fmp4 - the bytes of the mp4 fragment
  1945. * @returns the earliest base media decode start time for the
  1946. * fragment, in seconds
  1947. */
  1948. function getStartDTS(initData, fmp4) {
  1949. // we need info from two children of each track fragment box
  1950. return findBox(fmp4, ['moof', 'traf']).reduce(function (result, traf) {
  1951. var tfdt = findBox(traf, ['tfdt'])[0];
  1952. var version = tfdt[0];
  1953. var start = findBox(traf, ['tfhd']).reduce(function (result, tfhd) {
  1954. // get the track id from the tfhd
  1955. var id = readUint32(tfhd, 4);
  1956. var track = initData[id];
  1957. if (track) {
  1958. var baseTime = readUint32(tfdt, 4);
  1959. if (version === 1) {
  1960. // If value is too large, assume signed 64-bit. Negative track fragment decode times are invalid, but they exist in the wild.
  1961. // This prevents large values from being used for initPTS, which can cause playlist sync issues.
  1962. // https://github.com/video-dev/hls.js/issues/5303
  1963. if (baseTime === UINT32_MAX$1) {
  1964. logger.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time");
  1965. return result;
  1966. }
  1967. baseTime *= UINT32_MAX$1 + 1;
  1968. baseTime += readUint32(tfdt, 8);
  1969. }
  1970. // assume a 90kHz clock if no timescale was specified
  1971. var scale = track.timescale || 90e3;
  1972. // convert base time to seconds
  1973. var startTime = baseTime / scale;
  1974. if (isFiniteNumber(startTime) && (result === null || startTime < result)) {
  1975. return startTime;
  1976. }
  1977. }
  1978. return result;
  1979. }, null);
  1980. if (start !== null && isFiniteNumber(start) && (result === null || start < result)) {
  1981. return start;
  1982. }
  1983. return result;
  1984. }, null);
  1985. }
  1986. /*
  1987. For Reference:
  1988. aligned(8) class TrackFragmentHeaderBox
  1989. extends FullBox(‘tfhd’, 0, tf_flags){
  1990. unsigned int(32) track_ID;
  1991. // all the following are optional fields
  1992. unsigned int(64) base_data_offset;
  1993. unsigned int(32) sample_description_index;
  1994. unsigned int(32) default_sample_duration;
  1995. unsigned int(32) default_sample_size;
  1996. unsigned int(32) default_sample_flags
  1997. }
  1998. */
  1999. function getDuration(data, initData) {
  2000. var rawDuration = 0;
  2001. var videoDuration = 0;
  2002. var audioDuration = 0;
  2003. var trafs = findBox(data, ['moof', 'traf']);
  2004. for (var i = 0; i < trafs.length; i++) {
  2005. var traf = trafs[i];
  2006. // There is only one tfhd & trun per traf
  2007. // This is true for CMAF style content, and we should perhaps check the ftyp
  2008. // and only look for a single trun then, but for ISOBMFF we should check
  2009. // for multiple track runs.
  2010. var tfhd = findBox(traf, ['tfhd'])[0];
  2011. // get the track id from the tfhd
  2012. var id = readUint32(tfhd, 4);
  2013. var track = initData[id];
  2014. if (!track) {
  2015. continue;
  2016. }
  2017. var trackDefault = track.default;
  2018. var tfhdFlags = readUint32(tfhd, 0) | (trackDefault == null ? void 0 : trackDefault.flags);
  2019. var sampleDuration = trackDefault == null ? void 0 : trackDefault.duration;
  2020. if (tfhdFlags & 0x000008) {
  2021. // 0x000008 indicates the presence of the default_sample_duration field
  2022. if (tfhdFlags & 0x000002) {
  2023. // 0x000002 indicates the presence of the sample_description_index field, which precedes default_sample_duration
  2024. // If present, the default_sample_duration exists at byte offset 12
  2025. sampleDuration = readUint32(tfhd, 12);
  2026. } else {
  2027. // Otherwise, the duration is at byte offset 8
  2028. sampleDuration = readUint32(tfhd, 8);
  2029. }
  2030. }
  2031. // assume a 90kHz clock if no timescale was specified
  2032. var timescale = track.timescale || 90e3;
  2033. var truns = findBox(traf, ['trun']);
  2034. for (var j = 0; j < truns.length; j++) {
  2035. rawDuration = computeRawDurationFromSamples(truns[j]);
  2036. if (!rawDuration && sampleDuration) {
  2037. var sampleCount = readUint32(truns[j], 4);
  2038. rawDuration = sampleDuration * sampleCount;
  2039. }
  2040. if (track.type === ElementaryStreamTypes.VIDEO) {
  2041. videoDuration += rawDuration / timescale;
  2042. } else if (track.type === ElementaryStreamTypes.AUDIO) {
  2043. audioDuration += rawDuration / timescale;
  2044. }
  2045. }
  2046. }
  2047. if (videoDuration === 0 && audioDuration === 0) {
  2048. // If duration samples are not available in the traf use sidx subsegment_duration
  2049. var sidxMinStart = Infinity;
  2050. var sidxMaxEnd = 0;
  2051. var sidxDuration = 0;
  2052. var sidxs = findBox(data, ['sidx']);
  2053. for (var _i2 = 0; _i2 < sidxs.length; _i2++) {
  2054. var sidx = parseSegmentIndex(sidxs[_i2]);
  2055. if (sidx != null && sidx.references) {
  2056. sidxMinStart = Math.min(sidxMinStart, sidx.earliestPresentationTime / sidx.timescale);
  2057. var subSegmentDuration = sidx.references.reduce(function (dur, ref) {
  2058. return dur + ref.info.duration || 0;
  2059. }, 0);
  2060. sidxMaxEnd = Math.max(sidxMaxEnd, subSegmentDuration + sidx.earliestPresentationTime / sidx.timescale);
  2061. sidxDuration = sidxMaxEnd - sidxMinStart;
  2062. }
  2063. }
  2064. if (sidxDuration && isFiniteNumber(sidxDuration)) {
  2065. return sidxDuration;
  2066. }
  2067. }
  2068. if (videoDuration) {
  2069. return videoDuration;
  2070. }
  2071. return audioDuration;
  2072. }
  2073. /*
  2074. For Reference:
  2075. aligned(8) class TrackRunBox
  2076. extends FullBox(‘trun’, version, tr_flags) {
  2077. unsigned int(32) sample_count;
  2078. // the following are optional fields
  2079. signed int(32) data_offset;
  2080. unsigned int(32) first_sample_flags;
  2081. // all fields in the following array are optional
  2082. {
  2083. unsigned int(32) sample_duration;
  2084. unsigned int(32) sample_size;
  2085. unsigned int(32) sample_flags
  2086. if (version == 0)
  2087. { unsigned int(32)
  2088. else
  2089. { signed int(32)
  2090. }[ sample_count ]
  2091. }
  2092. */
  2093. function computeRawDurationFromSamples(trun) {
  2094. var flags = readUint32(trun, 0);
  2095. // Flags are at offset 0, non-optional sample_count is at offset 4. Therefore we start 8 bytes in.
  2096. // Each field is an int32, which is 4 bytes
  2097. var offset = 8;
  2098. // data-offset-present flag
  2099. if (flags & 0x000001) {
  2100. offset += 4;
  2101. }
  2102. // first-sample-flags-present flag
  2103. if (flags & 0x000004) {
  2104. offset += 4;
  2105. }
  2106. var duration = 0;
  2107. var sampleCount = readUint32(trun, 4);
  2108. for (var i = 0; i < sampleCount; i++) {
  2109. // sample-duration-present flag
  2110. if (flags & 0x000100) {
  2111. var sampleDuration = readUint32(trun, offset);
  2112. duration += sampleDuration;
  2113. offset += 4;
  2114. }
  2115. // sample-size-present flag
  2116. if (flags & 0x000200) {
  2117. offset += 4;
  2118. }
  2119. // sample-flags-present flag
  2120. if (flags & 0x000400) {
  2121. offset += 4;
  2122. }
  2123. // sample-composition-time-offsets-present flag
  2124. if (flags & 0x000800) {
  2125. offset += 4;
  2126. }
  2127. }
  2128. return duration;
  2129. }
  2130. function offsetStartDTS(initData, fmp4, timeOffset) {
  2131. findBox(fmp4, ['moof', 'traf']).forEach(function (traf) {
  2132. findBox(traf, ['tfhd']).forEach(function (tfhd) {
  2133. // get the track id from the tfhd
  2134. var id = readUint32(tfhd, 4);
  2135. var track = initData[id];
  2136. if (!track) {
  2137. return;
  2138. }
  2139. // assume a 90kHz clock if no timescale was specified
  2140. var timescale = track.timescale || 90e3;
  2141. // get the base media decode time from the tfdt
  2142. findBox(traf, ['tfdt']).forEach(function (tfdt) {
  2143. var version = tfdt[0];
  2144. var offset = timeOffset * timescale;
  2145. if (offset) {
  2146. var baseMediaDecodeTime = readUint32(tfdt, 4);
  2147. if (version === 0) {
  2148. baseMediaDecodeTime -= offset;
  2149. baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);
  2150. writeUint32(tfdt, 4, baseMediaDecodeTime);
  2151. } else {
  2152. baseMediaDecodeTime *= Math.pow(2, 32);
  2153. baseMediaDecodeTime += readUint32(tfdt, 8);
  2154. baseMediaDecodeTime -= offset;
  2155. baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);
  2156. var upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX$1 + 1));
  2157. var lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX$1 + 1));
  2158. writeUint32(tfdt, 4, upper);
  2159. writeUint32(tfdt, 8, lower);
  2160. }
  2161. }
  2162. });
  2163. });
  2164. });
  2165. }
  2166. // TODO: Check if the last moof+mdat pair is part of the valid range
  2167. function segmentValidRange(data) {
  2168. var segmentedRange = {
  2169. valid: null,
  2170. remainder: null
  2171. };
  2172. var moofs = findBox(data, ['moof']);
  2173. if (moofs.length < 2) {
  2174. segmentedRange.remainder = data;
  2175. return segmentedRange;
  2176. }
  2177. var last = moofs[moofs.length - 1];
  2178. // Offset by 8 bytes; findBox offsets the start by as much
  2179. segmentedRange.valid = sliceUint8(data, 0, last.byteOffset - 8);
  2180. segmentedRange.remainder = sliceUint8(data, last.byteOffset - 8);
  2181. return segmentedRange;
  2182. }
  2183. function appendUint8Array(data1, data2) {
  2184. var temp = new Uint8Array(data1.length + data2.length);
  2185. temp.set(data1);
  2186. temp.set(data2, data1.length);
  2187. return temp;
  2188. }
  2189. function parseSamples(timeOffset, track) {
  2190. var seiSamples = [];
  2191. var videoData = track.samples;
  2192. var timescale = track.timescale;
  2193. var trackId = track.id;
  2194. var isHEVCFlavor = false;
  2195. var moofs = findBox(videoData, ['moof']);
  2196. moofs.map(function (moof) {
  2197. var moofOffset = moof.byteOffset - 8;
  2198. var trafs = findBox(moof, ['traf']);
  2199. trafs.map(function (traf) {
  2200. // get the base media decode time from the tfdt
  2201. var baseTime = findBox(traf, ['tfdt']).map(function (tfdt) {
  2202. var version = tfdt[0];
  2203. var result = readUint32(tfdt, 4);
  2204. if (version === 1) {
  2205. result *= Math.pow(2, 32);
  2206. result += readUint32(tfdt, 8);
  2207. }
  2208. return result / timescale;
  2209. })[0];
  2210. if (baseTime !== undefined) {
  2211. timeOffset = baseTime;
  2212. }
  2213. return findBox(traf, ['tfhd']).map(function (tfhd) {
  2214. var id = readUint32(tfhd, 4);
  2215. var tfhdFlags = readUint32(tfhd, 0) & 0xffffff;
  2216. var baseDataOffsetPresent = (tfhdFlags & 0x000001) !== 0;
  2217. var sampleDescriptionIndexPresent = (tfhdFlags & 0x000002) !== 0;
  2218. var defaultSampleDurationPresent = (tfhdFlags & 0x000008) !== 0;
  2219. var defaultSampleDuration = 0;
  2220. var defaultSampleSizePresent = (tfhdFlags & 0x000010) !== 0;
  2221. var defaultSampleSize = 0;
  2222. var defaultSampleFlagsPresent = (tfhdFlags & 0x000020) !== 0;
  2223. var tfhdOffset = 8;
  2224. if (id === trackId) {
  2225. if (baseDataOffsetPresent) {
  2226. tfhdOffset += 8;
  2227. }
  2228. if (sampleDescriptionIndexPresent) {
  2229. tfhdOffset += 4;
  2230. }
  2231. if (defaultSampleDurationPresent) {
  2232. defaultSampleDuration = readUint32(tfhd, tfhdOffset);
  2233. tfhdOffset += 4;
  2234. }
  2235. if (defaultSampleSizePresent) {
  2236. defaultSampleSize = readUint32(tfhd, tfhdOffset);
  2237. tfhdOffset += 4;
  2238. }
  2239. if (defaultSampleFlagsPresent) {
  2240. tfhdOffset += 4;
  2241. }
  2242. if (track.type === 'video') {
  2243. isHEVCFlavor = isHEVC(track.codec);
  2244. }
  2245. findBox(traf, ['trun']).map(function (trun) {
  2246. var version = trun[0];
  2247. var flags = readUint32(trun, 0) & 0xffffff;
  2248. var dataOffsetPresent = (flags & 0x000001) !== 0;
  2249. var dataOffset = 0;
  2250. var firstSampleFlagsPresent = (flags & 0x000004) !== 0;
  2251. var sampleDurationPresent = (flags & 0x000100) !== 0;
  2252. var sampleDuration = 0;
  2253. var sampleSizePresent = (flags & 0x000200) !== 0;
  2254. var sampleSize = 0;
  2255. var sampleFlagsPresent = (flags & 0x000400) !== 0;
  2256. var sampleCompositionOffsetsPresent = (flags & 0x000800) !== 0;
  2257. var compositionOffset = 0;
  2258. var sampleCount = readUint32(trun, 4);
  2259. var trunOffset = 8; // past version, flags, and sample count
  2260. if (dataOffsetPresent) {
  2261. dataOffset = readUint32(trun, trunOffset);
  2262. trunOffset += 4;
  2263. }
  2264. if (firstSampleFlagsPresent) {
  2265. trunOffset += 4;
  2266. }
  2267. var sampleOffset = dataOffset + moofOffset;
  2268. for (var ix = 0; ix < sampleCount; ix++) {
  2269. if (sampleDurationPresent) {
  2270. sampleDuration = readUint32(trun, trunOffset);
  2271. trunOffset += 4;
  2272. } else {
  2273. sampleDuration = defaultSampleDuration;
  2274. }
  2275. if (sampleSizePresent) {
  2276. sampleSize = readUint32(trun, trunOffset);
  2277. trunOffset += 4;
  2278. } else {
  2279. sampleSize = defaultSampleSize;
  2280. }
  2281. if (sampleFlagsPresent) {
  2282. trunOffset += 4;
  2283. }
  2284. if (sampleCompositionOffsetsPresent) {
  2285. if (version === 0) {
  2286. compositionOffset = readUint32(trun, trunOffset);
  2287. } else {
  2288. compositionOffset = readSint32(trun, trunOffset);
  2289. }
  2290. trunOffset += 4;
  2291. }
  2292. if (track.type === ElementaryStreamTypes.VIDEO) {
  2293. var naluTotalSize = 0;
  2294. while (naluTotalSize < sampleSize) {
  2295. var naluSize = readUint32(videoData, sampleOffset);
  2296. sampleOffset += 4;
  2297. if (isSEIMessage(isHEVCFlavor, videoData[sampleOffset])) {
  2298. var data = videoData.subarray(sampleOffset, sampleOffset + naluSize);
  2299. parseSEIMessageFromNALu(data, isHEVCFlavor ? 2 : 1, timeOffset + compositionOffset / timescale, seiSamples);
  2300. }
  2301. sampleOffset += naluSize;
  2302. naluTotalSize += naluSize + 4;
  2303. }
  2304. }
  2305. timeOffset += sampleDuration / timescale;
  2306. }
  2307. });
  2308. }
  2309. });
  2310. });
  2311. });
  2312. return seiSamples;
  2313. }
  2314. function isHEVC(codec) {
  2315. if (!codec) {
  2316. return false;
  2317. }
  2318. var delimit = codec.indexOf('.');
  2319. var baseCodec = delimit < 0 ? codec : codec.substring(0, delimit);
  2320. return baseCodec === 'hvc1' || baseCodec === 'hev1' ||
  2321. // Dolby Vision
  2322. baseCodec === 'dvh1' || baseCodec === 'dvhe';
  2323. }
  2324. function isSEIMessage(isHEVCFlavor, naluHeader) {
  2325. if (isHEVCFlavor) {
  2326. var naluType = naluHeader >> 1 & 0x3f;
  2327. return naluType === 39 || naluType === 40;
  2328. } else {
  2329. var _naluType = naluHeader & 0x1f;
  2330. return _naluType === 6;
  2331. }
  2332. }
  2333. function parseSEIMessageFromNALu(unescapedData, headerSize, pts, samples) {
  2334. var data = discardEPB(unescapedData);
  2335. var seiPtr = 0;
  2336. // skip nal header
  2337. seiPtr += headerSize;
  2338. var payloadType = 0;
  2339. var payloadSize = 0;
  2340. var b = 0;
  2341. while (seiPtr < data.length) {
  2342. payloadType = 0;
  2343. do {
  2344. if (seiPtr >= data.length) {
  2345. break;
  2346. }
  2347. b = data[seiPtr++];
  2348. payloadType += b;
  2349. } while (b === 0xff);
  2350. // Parse payload size.
  2351. payloadSize = 0;
  2352. do {
  2353. if (seiPtr >= data.length) {
  2354. break;
  2355. }
  2356. b = data[seiPtr++];
  2357. payloadSize += b;
  2358. } while (b === 0xff);
  2359. var leftOver = data.length - seiPtr;
  2360. // Create a variable to process the payload
  2361. var payPtr = seiPtr;
  2362. // Increment the seiPtr to the end of the payload
  2363. if (payloadSize < leftOver) {
  2364. seiPtr += payloadSize;
  2365. } else if (payloadSize > leftOver) {
  2366. // Some type of corruption has happened?
  2367. logger.error("Malformed SEI payload. " + payloadSize + " is too small, only " + leftOver + " bytes left to parse.");
  2368. // We might be able to parse some data, but let's be safe and ignore it.
  2369. break;
  2370. }
  2371. if (payloadType === 4) {
  2372. var countryCode = data[payPtr++];
  2373. if (countryCode === 181) {
  2374. var providerCode = readUint16(data, payPtr);
  2375. payPtr += 2;
  2376. if (providerCode === 49) {
  2377. var userStructure = readUint32(data, payPtr);
  2378. payPtr += 4;
  2379. if (userStructure === 0x47413934) {
  2380. var userDataType = data[payPtr++];
  2381. // Raw CEA-608 bytes wrapped in CEA-708 packet
  2382. if (userDataType === 3) {
  2383. var firstByte = data[payPtr++];
  2384. var totalCCs = 0x1f & firstByte;
  2385. var enabled = 0x40 & firstByte;
  2386. var totalBytes = enabled ? 2 + totalCCs * 3 : 0;
  2387. var byteArray = new Uint8Array(totalBytes);
  2388. if (enabled) {
  2389. byteArray[0] = firstByte;
  2390. for (var i = 1; i < totalBytes; i++) {
  2391. byteArray[i] = data[payPtr++];
  2392. }
  2393. }
  2394. samples.push({
  2395. type: userDataType,
  2396. payloadType: payloadType,
  2397. pts: pts,
  2398. bytes: byteArray
  2399. });
  2400. }
  2401. }
  2402. }
  2403. }
  2404. } else if (payloadType === 5) {
  2405. if (payloadSize > 16) {
  2406. var uuidStrArray = [];
  2407. for (var _i3 = 0; _i3 < 16; _i3++) {
  2408. var _b = data[payPtr++].toString(16);
  2409. uuidStrArray.push(_b.length == 1 ? '0' + _b : _b);
  2410. if (_i3 === 3 || _i3 === 5 || _i3 === 7 || _i3 === 9) {
  2411. uuidStrArray.push('-');
  2412. }
  2413. }
  2414. var length = payloadSize - 16;
  2415. var userDataBytes = new Uint8Array(length);
  2416. for (var _i4 = 0; _i4 < length; _i4++) {
  2417. userDataBytes[_i4] = data[payPtr++];
  2418. }
  2419. samples.push({
  2420. payloadType: payloadType,
  2421. pts: pts,
  2422. uuid: uuidStrArray.join(''),
  2423. userData: utf8ArrayToStr(userDataBytes),
  2424. userDataBytes: userDataBytes
  2425. });
  2426. }
  2427. }
  2428. }
  2429. }
  2430. /**
  2431. * remove Emulation Prevention bytes from a RBSP
  2432. */
  2433. function discardEPB(data) {
  2434. var length = data.byteLength;
  2435. var EPBPositions = [];
  2436. var i = 1;
  2437. // Find all `Emulation Prevention Bytes`
  2438. while (i < length - 2) {
  2439. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  2440. EPBPositions.push(i + 2);
  2441. i += 2;
  2442. } else {
  2443. i++;
  2444. }
  2445. }
  2446. // If no Emulation Prevention Bytes were found just return the original
  2447. // array
  2448. if (EPBPositions.length === 0) {
  2449. return data;
  2450. }
  2451. // Create a new array to hold the NAL unit data
  2452. var newLength = length - EPBPositions.length;
  2453. var newData = new Uint8Array(newLength);
  2454. var sourceIndex = 0;
  2455. for (i = 0; i < newLength; sourceIndex++, i++) {
  2456. if (sourceIndex === EPBPositions[0]) {
  2457. // Skip this byte
  2458. sourceIndex++;
  2459. // Remove this position index
  2460. EPBPositions.shift();
  2461. }
  2462. newData[i] = data[sourceIndex];
  2463. }
  2464. return newData;
  2465. }
  2466. function parseEmsg(data) {
  2467. var version = data[0];
  2468. var schemeIdUri = '';
  2469. var value = '';
  2470. var timeScale = 0;
  2471. var presentationTimeDelta = 0;
  2472. var presentationTime = 0;
  2473. var eventDuration = 0;
  2474. var id = 0;
  2475. var offset = 0;
  2476. if (version === 0) {
  2477. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2478. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2479. offset += 1;
  2480. }
  2481. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2482. offset += 1;
  2483. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2484. value += bin2str(data.subarray(offset, offset + 1));
  2485. offset += 1;
  2486. }
  2487. value += bin2str(data.subarray(offset, offset + 1));
  2488. offset += 1;
  2489. timeScale = readUint32(data, 12);
  2490. presentationTimeDelta = readUint32(data, 16);
  2491. eventDuration = readUint32(data, 20);
  2492. id = readUint32(data, 24);
  2493. offset = 28;
  2494. } else if (version === 1) {
  2495. offset += 4;
  2496. timeScale = readUint32(data, offset);
  2497. offset += 4;
  2498. var leftPresentationTime = readUint32(data, offset);
  2499. offset += 4;
  2500. var rightPresentationTime = readUint32(data, offset);
  2501. offset += 4;
  2502. presentationTime = Math.pow(2, 32) * leftPresentationTime + rightPresentationTime;
  2503. if (!isSafeInteger(presentationTime)) {
  2504. presentationTime = Number.MAX_SAFE_INTEGER;
  2505. logger.warn('Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box');
  2506. }
  2507. eventDuration = readUint32(data, offset);
  2508. offset += 4;
  2509. id = readUint32(data, offset);
  2510. offset += 4;
  2511. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2512. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2513. offset += 1;
  2514. }
  2515. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2516. offset += 1;
  2517. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2518. value += bin2str(data.subarray(offset, offset + 1));
  2519. offset += 1;
  2520. }
  2521. value += bin2str(data.subarray(offset, offset + 1));
  2522. offset += 1;
  2523. }
  2524. var payload = data.subarray(offset, data.byteLength);
  2525. return {
  2526. schemeIdUri: schemeIdUri,
  2527. value: value,
  2528. timeScale: timeScale,
  2529. presentationTime: presentationTime,
  2530. presentationTimeDelta: presentationTimeDelta,
  2531. eventDuration: eventDuration,
  2532. id: id,
  2533. payload: payload
  2534. };
  2535. }
  2536. var LevelKey = /*#__PURE__*/function () {
  2537. LevelKey.clearKeyUriToKeyIdMap = function clearKeyUriToKeyIdMap() {
  2538. };
  2539. function LevelKey(method, uri, format, formatversions, iv) {
  2540. if (formatversions === void 0) {
  2541. formatversions = [1];
  2542. }
  2543. if (iv === void 0) {
  2544. iv = null;
  2545. }
  2546. this.uri = void 0;
  2547. this.method = void 0;
  2548. this.keyFormat = void 0;
  2549. this.keyFormatVersions = void 0;
  2550. this.encrypted = void 0;
  2551. this.isCommonEncryption = void 0;
  2552. this.iv = null;
  2553. this.key = null;
  2554. this.keyId = null;
  2555. this.pssh = null;
  2556. this.method = method;
  2557. this.uri = uri;
  2558. this.keyFormat = format;
  2559. this.keyFormatVersions = formatversions;
  2560. this.iv = iv;
  2561. this.encrypted = method ? method !== 'NONE' : false;
  2562. this.isCommonEncryption = this.encrypted && method !== 'AES-128';
  2563. }
  2564. var _proto = LevelKey.prototype;
  2565. _proto.isSupported = function isSupported() {
  2566. // If it's Segment encryption or No encryption, just select that key system
  2567. if (this.method) {
  2568. if (this.method === 'AES-128' || this.method === 'NONE') {
  2569. return true;
  2570. }
  2571. if (this.keyFormat === 'identity') {
  2572. // Maintain support for clear SAMPLE-AES with MPEG-3 TS
  2573. return this.method === 'SAMPLE-AES';
  2574. }
  2575. }
  2576. return false;
  2577. };
  2578. _proto.getDecryptData = function getDecryptData(sn) {
  2579. if (!this.encrypted || !this.uri) {
  2580. return null;
  2581. }
  2582. if (this.method === 'AES-128' && this.uri && !this.iv) {
  2583. if (typeof sn !== 'number') {
  2584. // We are fetching decryption data for a initialization segment
  2585. // If the segment was encrypted with AES-128
  2586. // It must have an IV defined. We cannot substitute the Segment Number in.
  2587. if (this.method === 'AES-128' && !this.iv) {
  2588. logger.warn("missing IV for initialization segment with method=\"" + this.method + "\" - compliance issue");
  2589. }
  2590. // Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation.
  2591. sn = 0;
  2592. }
  2593. var iv = createInitializationVector(sn);
  2594. var decryptdata = new LevelKey(this.method, this.uri, 'identity', this.keyFormatVersions, iv);
  2595. return decryptdata;
  2596. }
  2597. {
  2598. return this;
  2599. }
  2600. };
  2601. return LevelKey;
  2602. }();
  2603. function createInitializationVector(segmentNumber) {
  2604. var uint8View = new Uint8Array(16);
  2605. for (var i = 12; i < 16; i++) {
  2606. uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff;
  2607. }
  2608. return uint8View;
  2609. }
  2610. /**
  2611. * MediaSource helper
  2612. */
  2613. function getMediaSource(preferManagedMediaSource) {
  2614. if (preferManagedMediaSource === void 0) {
  2615. preferManagedMediaSource = true;
  2616. }
  2617. if (typeof self === 'undefined') return undefined;
  2618. var mms = (preferManagedMediaSource || !self.MediaSource) && self.ManagedMediaSource;
  2619. return mms || self.MediaSource || self.WebKitMediaSource;
  2620. }
  2621. function isManagedMediaSource(source) {
  2622. return typeof self !== 'undefined' && source === self.ManagedMediaSource;
  2623. }
  2624. // from http://mp4ra.org/codecs.html
  2625. // values indicate codec selection preference (lower is higher priority)
  2626. var sampleEntryCodesISO = {
  2627. audio: {
  2628. a3ds: 1,
  2629. 'ac-3': 0.95,
  2630. 'ac-4': 1,
  2631. alac: 0.9,
  2632. alaw: 1,
  2633. dra1: 1,
  2634. 'dts+': 1,
  2635. 'dts-': 1,
  2636. dtsc: 1,
  2637. dtse: 1,
  2638. dtsh: 1,
  2639. 'ec-3': 0.9,
  2640. enca: 1,
  2641. fLaC: 0.9,
  2642. // MP4-RA listed codec entry for FLAC
  2643. flac: 0.9,
  2644. // legacy browser codec name for FLAC
  2645. FLAC: 0.9,
  2646. // some manifests may list "FLAC" with Apple's tools
  2647. g719: 1,
  2648. g726: 1,
  2649. m4ae: 1,
  2650. mha1: 1,
  2651. mha2: 1,
  2652. mhm1: 1,
  2653. mhm2: 1,
  2654. mlpa: 1,
  2655. mp4a: 1,
  2656. 'raw ': 1,
  2657. Opus: 1,
  2658. opus: 1,
  2659. // browsers expect this to be lowercase despite MP4RA says 'Opus'
  2660. samr: 1,
  2661. sawb: 1,
  2662. sawp: 1,
  2663. sevc: 1,
  2664. sqcp: 1,
  2665. ssmv: 1,
  2666. twos: 1,
  2667. ulaw: 1
  2668. },
  2669. video: {
  2670. avc1: 1,
  2671. avc2: 1,
  2672. avc3: 1,
  2673. avc4: 1,
  2674. avcp: 1,
  2675. av01: 0.8,
  2676. drac: 1,
  2677. dva1: 1,
  2678. dvav: 1,
  2679. dvh1: 0.7,
  2680. dvhe: 0.7,
  2681. encv: 1,
  2682. hev1: 0.75,
  2683. hvc1: 0.75,
  2684. mjp2: 1,
  2685. mp4v: 1,
  2686. mvc1: 1,
  2687. mvc2: 1,
  2688. mvc3: 1,
  2689. mvc4: 1,
  2690. resv: 1,
  2691. rv60: 1,
  2692. s263: 1,
  2693. svc1: 1,
  2694. svc2: 1,
  2695. 'vc-1': 1,
  2696. vp08: 1,
  2697. vp09: 0.9
  2698. },
  2699. text: {
  2700. stpp: 1,
  2701. wvtt: 1
  2702. }
  2703. };
  2704. function isCodecType(codec, type) {
  2705. var typeCodes = sampleEntryCodesISO[type];
  2706. return !!typeCodes && !!typeCodes[codec.slice(0, 4)];
  2707. }
  2708. function areCodecsMediaSourceSupported(codecs, type, preferManagedMediaSource) {
  2709. if (preferManagedMediaSource === void 0) {
  2710. preferManagedMediaSource = true;
  2711. }
  2712. return !codecs.split(',').some(function (codec) {
  2713. return !isCodecMediaSourceSupported(codec, type, preferManagedMediaSource);
  2714. });
  2715. }
  2716. function isCodecMediaSourceSupported(codec, type, preferManagedMediaSource) {
  2717. var _MediaSource$isTypeSu;
  2718. if (preferManagedMediaSource === void 0) {
  2719. preferManagedMediaSource = true;
  2720. }
  2721. var MediaSource = getMediaSource(preferManagedMediaSource);
  2722. return (_MediaSource$isTypeSu = MediaSource == null ? void 0 : MediaSource.isTypeSupported(mimeTypeForCodec(codec, type))) != null ? _MediaSource$isTypeSu : false;
  2723. }
  2724. function mimeTypeForCodec(codec, type) {
  2725. return type + "/mp4;codecs=\"" + codec + "\"";
  2726. }
  2727. function videoCodecPreferenceValue(videoCodec) {
  2728. if (videoCodec) {
  2729. var fourCC = videoCodec.substring(0, 4);
  2730. return sampleEntryCodesISO.video[fourCC];
  2731. }
  2732. return 2;
  2733. }
  2734. function codecsSetSelectionPreferenceValue(codecSet) {
  2735. return codecSet.split(',').reduce(function (num, fourCC) {
  2736. var preferenceValue = sampleEntryCodesISO.video[fourCC];
  2737. if (preferenceValue) {
  2738. return (preferenceValue * 2 + num) / (num ? 3 : 2);
  2739. }
  2740. return (sampleEntryCodesISO.audio[fourCC] + num) / (num ? 2 : 1);
  2741. }, 0);
  2742. }
  2743. var CODEC_COMPATIBLE_NAMES = {};
  2744. function getCodecCompatibleNameLower(lowerCaseCodec, preferManagedMediaSource) {
  2745. if (preferManagedMediaSource === void 0) {
  2746. preferManagedMediaSource = true;
  2747. }
  2748. if (CODEC_COMPATIBLE_NAMES[lowerCaseCodec]) {
  2749. return CODEC_COMPATIBLE_NAMES[lowerCaseCodec];
  2750. }
  2751. // Idealy fLaC and Opus would be first (spec-compliant) but
  2752. // some browsers will report that fLaC is supported then fail.
  2753. // see: https://bugs.chromium.org/p/chromium/issues/detail?id=1422728
  2754. var codecsToCheck = {
  2755. flac: ['flac', 'fLaC', 'FLAC'],
  2756. opus: ['opus', 'Opus']
  2757. }[lowerCaseCodec];
  2758. for (var i = 0; i < codecsToCheck.length; i++) {
  2759. if (isCodecMediaSourceSupported(codecsToCheck[i], 'audio', preferManagedMediaSource)) {
  2760. CODEC_COMPATIBLE_NAMES[lowerCaseCodec] = codecsToCheck[i];
  2761. return codecsToCheck[i];
  2762. }
  2763. }
  2764. return lowerCaseCodec;
  2765. }
  2766. var AUDIO_CODEC_REGEXP = /flac|opus/i;
  2767. function getCodecCompatibleName(codec, preferManagedMediaSource) {
  2768. if (preferManagedMediaSource === void 0) {
  2769. preferManagedMediaSource = true;
  2770. }
  2771. return codec.replace(AUDIO_CODEC_REGEXP, function (m) {
  2772. return getCodecCompatibleNameLower(m.toLowerCase(), preferManagedMediaSource);
  2773. });
  2774. }
  2775. function pickMostCompleteCodecName(parsedCodec, levelCodec) {
  2776. // Parsing of mp4a codecs strings in mp4-tools from media is incomplete as of d8c6c7a
  2777. // so use level codec is parsed codec is unavailable or incomplete
  2778. if (parsedCodec && parsedCodec !== 'mp4a') {
  2779. return parsedCodec;
  2780. }
  2781. return levelCodec ? levelCodec.split(',')[0] : levelCodec;
  2782. }
  2783. function convertAVC1ToAVCOTI(codec) {
  2784. // Convert avc1 codec string from RFC-4281 to RFC-6381 for MediaSource.isTypeSupported
  2785. // Examples: avc1.66.30 to avc1.42001e and avc1.77.30,avc1.66.30 to avc1.4d001e,avc1.42001e.
  2786. var codecs = codec.split(',');
  2787. for (var i = 0; i < codecs.length; i++) {
  2788. var avcdata = codecs[i].split('.');
  2789. if (avcdata.length > 2) {
  2790. var result = avcdata.shift() + '.';
  2791. result += parseInt(avcdata.shift()).toString(16);
  2792. result += ('000' + parseInt(avcdata.shift()).toString(16)).slice(-4);
  2793. codecs[i] = result;
  2794. }
  2795. }
  2796. return codecs.join(',');
  2797. }
  2798. 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;
  2799. var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
  2800. var IS_MEDIA_PLAYLIST = /^#EXT(?:INF|-X-TARGETDURATION):/m; // Handle empty Media Playlist (first EXTINF not signaled, but TARGETDURATION present)
  2801. var LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,
  2802. // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
  2803. /(?!#) *(\S[^\r\n]*)/.source,
  2804. // segment URI, group 3 => the URI (note newline is not eaten)
  2805. /#EXT-X-BYTERANGE:*(.+)/.source,
  2806. // next segment's byterange, group 4 => range spec (x@y)
  2807. /#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,
  2808. // next segment's program date/time group 5 => the datetime spec
  2809. /#.*/.source // All other non-segment oriented tags will match with all groups empty
  2810. ].join('|'), 'g');
  2811. var LEVEL_PLAYLIST_REGEX_SLOW = new RegExp([/#(EXTM3U)/.source, /#EXT-X-(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('|'));
  2812. var M3U8Parser = /*#__PURE__*/function () {
  2813. function M3U8Parser() {}
  2814. M3U8Parser.findGroup = function findGroup(groups, mediaGroupId) {
  2815. for (var i = 0; i < groups.length; i++) {
  2816. var group = groups[i];
  2817. if (group.id === mediaGroupId) {
  2818. return group;
  2819. }
  2820. }
  2821. };
  2822. M3U8Parser.resolve = function resolve(url, baseUrl) {
  2823. return urlToolkitExports.buildAbsoluteURL(baseUrl, url, {
  2824. alwaysNormalize: true
  2825. });
  2826. };
  2827. M3U8Parser.isMediaPlaylist = function isMediaPlaylist(str) {
  2828. return IS_MEDIA_PLAYLIST.test(str);
  2829. };
  2830. M3U8Parser.parseMasterPlaylist = function parseMasterPlaylist(string, baseurl) {
  2831. var hasVariableRefs = false;
  2832. var parsed = {
  2833. contentSteering: null,
  2834. levels: [],
  2835. playlistParsingError: null,
  2836. sessionData: null,
  2837. sessionKeys: null,
  2838. startTimeOffset: null,
  2839. variableList: null,
  2840. hasVariableRefs: hasVariableRefs
  2841. };
  2842. var levelsWithKnownCodecs = [];
  2843. MASTER_PLAYLIST_REGEX.lastIndex = 0;
  2844. var result;
  2845. while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
  2846. if (result[1]) {
  2847. var _level$unknownCodecs;
  2848. // '#EXT-X-STREAM-INF' is found, parse level tag in group 1
  2849. var attrs = new AttrList(result[1]);
  2850. var uri = result[2];
  2851. var level = {
  2852. attrs: attrs,
  2853. bitrate: attrs.decimalInteger('BANDWIDTH') || attrs.decimalInteger('AVERAGE-BANDWIDTH'),
  2854. name: attrs.NAME,
  2855. url: M3U8Parser.resolve(uri, baseurl)
  2856. };
  2857. var resolution = attrs.decimalResolution('RESOLUTION');
  2858. if (resolution) {
  2859. level.width = resolution.width;
  2860. level.height = resolution.height;
  2861. }
  2862. setCodecs(attrs.CODECS, level);
  2863. if (!((_level$unknownCodecs = level.unknownCodecs) != null && _level$unknownCodecs.length)) {
  2864. levelsWithKnownCodecs.push(level);
  2865. }
  2866. parsed.levels.push(level);
  2867. } else if (result[3]) {
  2868. var tag = result[3];
  2869. var attributes = result[4];
  2870. switch (tag) {
  2871. case 'SESSION-DATA':
  2872. {
  2873. // #EXT-X-SESSION-DATA
  2874. var sessionAttrs = new AttrList(attributes);
  2875. var dataId = sessionAttrs['DATA-ID'];
  2876. if (dataId) {
  2877. if (parsed.sessionData === null) {
  2878. parsed.sessionData = {};
  2879. }
  2880. parsed.sessionData[dataId] = sessionAttrs;
  2881. }
  2882. break;
  2883. }
  2884. case 'SESSION-KEY':
  2885. {
  2886. // #EXT-X-SESSION-KEY
  2887. var sessionKey = parseKey(attributes, baseurl);
  2888. if (sessionKey.encrypted && sessionKey.isSupported()) {
  2889. if (parsed.sessionKeys === null) {
  2890. parsed.sessionKeys = [];
  2891. }
  2892. parsed.sessionKeys.push(sessionKey);
  2893. } else {
  2894. logger.warn("[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: \"" + attributes + "\"");
  2895. }
  2896. break;
  2897. }
  2898. case 'DEFINE':
  2899. {
  2900. break;
  2901. }
  2902. case 'CONTENT-STEERING':
  2903. {
  2904. // #EXT-X-CONTENT-STEERING
  2905. var contentSteeringAttributes = new AttrList(attributes);
  2906. parsed.contentSteering = {
  2907. uri: M3U8Parser.resolve(contentSteeringAttributes['SERVER-URI'], baseurl),
  2908. pathwayId: contentSteeringAttributes['PATHWAY-ID'] || '.'
  2909. };
  2910. break;
  2911. }
  2912. case 'START':
  2913. {
  2914. // #EXT-X-START
  2915. parsed.startTimeOffset = parseStartTimeOffset(attributes);
  2916. break;
  2917. }
  2918. }
  2919. }
  2920. }
  2921. // Filter out levels with unknown codecs if it does not remove all levels
  2922. var stripUnknownCodecLevels = levelsWithKnownCodecs.length > 0 && levelsWithKnownCodecs.length < parsed.levels.length;
  2923. parsed.levels = stripUnknownCodecLevels ? levelsWithKnownCodecs : parsed.levels;
  2924. if (parsed.levels.length === 0) {
  2925. parsed.playlistParsingError = new Error('no levels found in manifest');
  2926. }
  2927. return parsed;
  2928. };
  2929. M3U8Parser.parseMasterPlaylistMedia = function parseMasterPlaylistMedia(string, baseurl, parsed) {
  2930. var result;
  2931. var results = {};
  2932. var levels = parsed.levels;
  2933. var groupsByType = {
  2934. AUDIO: levels.map(function (level) {
  2935. return {
  2936. id: level.attrs.AUDIO,
  2937. audioCodec: level.audioCodec
  2938. };
  2939. }),
  2940. SUBTITLES: levels.map(function (level) {
  2941. return {
  2942. id: level.attrs.SUBTITLES,
  2943. textCodec: level.textCodec
  2944. };
  2945. }),
  2946. 'CLOSED-CAPTIONS': []
  2947. };
  2948. var id = 0;
  2949. MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
  2950. while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
  2951. var attrs = new AttrList(result[1]);
  2952. var type = attrs.TYPE;
  2953. if (type) {
  2954. var groups = groupsByType[type];
  2955. var medias = results[type] || [];
  2956. results[type] = medias;
  2957. var lang = attrs.LANGUAGE;
  2958. var assocLang = attrs['ASSOC-LANGUAGE'];
  2959. var channels = attrs.CHANNELS;
  2960. var characteristics = attrs.CHARACTERISTICS;
  2961. var instreamId = attrs['INSTREAM-ID'];
  2962. var media = {
  2963. attrs: attrs,
  2964. bitrate: 0,
  2965. id: id++,
  2966. groupId: attrs['GROUP-ID'] || '',
  2967. name: attrs.NAME || lang || '',
  2968. type: type,
  2969. default: attrs.bool('DEFAULT'),
  2970. autoselect: attrs.bool('AUTOSELECT'),
  2971. forced: attrs.bool('FORCED'),
  2972. lang: lang,
  2973. url: attrs.URI ? M3U8Parser.resolve(attrs.URI, baseurl) : ''
  2974. };
  2975. if (assocLang) {
  2976. media.assocLang = assocLang;
  2977. }
  2978. if (channels) {
  2979. media.channels = channels;
  2980. }
  2981. if (characteristics) {
  2982. media.characteristics = characteristics;
  2983. }
  2984. if (instreamId) {
  2985. media.instreamId = instreamId;
  2986. }
  2987. if (groups != null && groups.length) {
  2988. // If there are audio or text groups signalled in the manifest, let's look for a matching codec string for this track
  2989. // If we don't find the track signalled, lets use the first audio groups codec we have
  2990. // Acting as a best guess
  2991. var groupCodec = M3U8Parser.findGroup(groups, media.groupId) || groups[0];
  2992. assignCodec(media, groupCodec, 'audioCodec');
  2993. assignCodec(media, groupCodec, 'textCodec');
  2994. }
  2995. medias.push(media);
  2996. }
  2997. }
  2998. return results;
  2999. };
  3000. M3U8Parser.parseLevelPlaylist = function parseLevelPlaylist(string, baseurl, id, type, levelUrlId, multivariantVariableList) {
  3001. var level = new LevelDetails(baseurl);
  3002. var fragments = level.fragments;
  3003. // The most recent init segment seen (applies to all subsequent segments)
  3004. var currentInitSegment = null;
  3005. var currentSN = 0;
  3006. var currentPart = 0;
  3007. var totalduration = 0;
  3008. var discontinuityCounter = 0;
  3009. var prevFrag = null;
  3010. var frag = new Fragment(type, baseurl);
  3011. var result;
  3012. var i;
  3013. var levelkeys;
  3014. var firstPdtIndex = -1;
  3015. var createNextFrag = false;
  3016. var nextByteRange = null;
  3017. LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
  3018. level.m3u8 = string;
  3019. level.hasVariableRefs = false;
  3020. while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
  3021. if (createNextFrag) {
  3022. createNextFrag = false;
  3023. frag = new Fragment(type, baseurl);
  3024. // setup the next fragment for part loading
  3025. frag.start = totalduration;
  3026. frag.sn = currentSN;
  3027. frag.cc = discontinuityCounter;
  3028. frag.level = id;
  3029. if (currentInitSegment) {
  3030. frag.initSegment = currentInitSegment;
  3031. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  3032. currentInitSegment.rawProgramDateTime = null;
  3033. if (nextByteRange) {
  3034. frag.setByteRange(nextByteRange);
  3035. nextByteRange = null;
  3036. }
  3037. }
  3038. }
  3039. var duration = result[1];
  3040. if (duration) {
  3041. // INF
  3042. frag.duration = parseFloat(duration);
  3043. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  3044. var title = (' ' + result[2]).slice(1);
  3045. frag.title = title || null;
  3046. frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);
  3047. } else if (result[3]) {
  3048. // url
  3049. if (isFiniteNumber(frag.duration)) {
  3050. frag.start = totalduration;
  3051. if (levelkeys) {
  3052. setFragLevelKeys(frag, levelkeys, level);
  3053. }
  3054. frag.sn = currentSN;
  3055. frag.level = id;
  3056. frag.cc = discontinuityCounter;
  3057. fragments.push(frag);
  3058. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  3059. var uri = (' ' + result[3]).slice(1);
  3060. frag.relurl = uri;
  3061. assignProgramDateTime(frag, prevFrag);
  3062. prevFrag = frag;
  3063. totalduration += frag.duration;
  3064. currentSN++;
  3065. currentPart = 0;
  3066. createNextFrag = true;
  3067. }
  3068. } else if (result[4]) {
  3069. // X-BYTERANGE
  3070. var data = (' ' + result[4]).slice(1);
  3071. if (prevFrag) {
  3072. frag.setByteRange(data, prevFrag);
  3073. } else {
  3074. frag.setByteRange(data);
  3075. }
  3076. } else if (result[5]) {
  3077. // PROGRAM-DATE-TIME
  3078. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  3079. frag.rawProgramDateTime = (' ' + result[5]).slice(1);
  3080. frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);
  3081. if (firstPdtIndex === -1) {
  3082. firstPdtIndex = fragments.length;
  3083. }
  3084. } else {
  3085. result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
  3086. if (!result) {
  3087. logger.warn('No matches on slow regex match for level playlist!');
  3088. continue;
  3089. }
  3090. for (i = 1; i < result.length; i++) {
  3091. if (typeof result[i] !== 'undefined') {
  3092. break;
  3093. }
  3094. }
  3095. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  3096. var tag = (' ' + result[i]).slice(1);
  3097. var value1 = (' ' + result[i + 1]).slice(1);
  3098. var value2 = result[i + 2] ? (' ' + result[i + 2]).slice(1) : '';
  3099. switch (tag) {
  3100. case 'PLAYLIST-TYPE':
  3101. level.type = value1.toUpperCase();
  3102. break;
  3103. case 'MEDIA-SEQUENCE':
  3104. currentSN = level.startSN = parseInt(value1);
  3105. break;
  3106. case 'SKIP':
  3107. {
  3108. var skipAttrs = new AttrList(value1);
  3109. var skippedSegments = skipAttrs.decimalInteger('SKIPPED-SEGMENTS');
  3110. if (isFiniteNumber(skippedSegments)) {
  3111. level.skippedSegments = skippedSegments;
  3112. // This will result in fragments[] containing undefined values, which we will fill in with `mergeDetails`
  3113. for (var _i = skippedSegments; _i--;) {
  3114. fragments.unshift(null);
  3115. }
  3116. currentSN += skippedSegments;
  3117. }
  3118. var recentlyRemovedDateranges = skipAttrs.enumeratedString('RECENTLY-REMOVED-DATERANGES');
  3119. if (recentlyRemovedDateranges) {
  3120. level.recentlyRemovedDateranges = recentlyRemovedDateranges.split('\t');
  3121. }
  3122. break;
  3123. }
  3124. case 'TARGETDURATION':
  3125. level.targetduration = Math.max(parseInt(value1), 1);
  3126. break;
  3127. case 'VERSION':
  3128. level.version = parseInt(value1);
  3129. break;
  3130. case 'INDEPENDENT-SEGMENTS':
  3131. case 'EXTM3U':
  3132. break;
  3133. case 'ENDLIST':
  3134. level.live = false;
  3135. break;
  3136. case '#':
  3137. if (value1 || value2) {
  3138. frag.tagList.push(value2 ? [value1, value2] : [value1]);
  3139. }
  3140. break;
  3141. case 'DISCONTINUITY':
  3142. discontinuityCounter++;
  3143. frag.tagList.push(['DIS']);
  3144. break;
  3145. case 'GAP':
  3146. frag.gap = true;
  3147. frag.tagList.push([tag]);
  3148. break;
  3149. case 'BITRATE':
  3150. frag.tagList.push([tag, value1]);
  3151. break;
  3152. case 'DATERANGE':
  3153. {
  3154. var dateRangeAttr = new AttrList(value1);
  3155. var dateRange = new DateRange(dateRangeAttr, level.dateRanges[dateRangeAttr.ID]);
  3156. if (dateRange.isValid || level.skippedSegments) {
  3157. level.dateRanges[dateRange.id] = dateRange;
  3158. } else {
  3159. logger.warn("Ignoring invalid DATERANGE tag: \"" + value1 + "\"");
  3160. }
  3161. // Add to fragment tag list for backwards compatibility (< v1.2.0)
  3162. frag.tagList.push(['EXT-X-DATERANGE', value1]);
  3163. break;
  3164. }
  3165. case 'DEFINE':
  3166. {
  3167. break;
  3168. }
  3169. case 'DISCONTINUITY-SEQUENCE':
  3170. discontinuityCounter = parseInt(value1);
  3171. break;
  3172. case 'KEY':
  3173. {
  3174. var levelKey = parseKey(value1, baseurl);
  3175. if (levelKey.isSupported()) {
  3176. if (levelKey.method === 'NONE') {
  3177. levelkeys = undefined;
  3178. break;
  3179. }
  3180. if (!levelkeys) {
  3181. levelkeys = {};
  3182. }
  3183. if (levelkeys[levelKey.keyFormat]) {
  3184. levelkeys = _extends({}, levelkeys);
  3185. }
  3186. levelkeys[levelKey.keyFormat] = levelKey;
  3187. } else {
  3188. logger.warn("[Keys] Ignoring invalid EXT-X-KEY tag: \"" + value1 + "\"");
  3189. }
  3190. break;
  3191. }
  3192. case 'START':
  3193. level.startTimeOffset = parseStartTimeOffset(value1);
  3194. break;
  3195. case 'MAP':
  3196. {
  3197. var mapAttrs = new AttrList(value1);
  3198. if (frag.duration) {
  3199. // Initial segment tag is after segment duration tag.
  3200. // #EXTINF: 6.0
  3201. // #EXT-X-MAP:URI="init.mp4
  3202. var init = new Fragment(type, baseurl);
  3203. setInitSegment(init, mapAttrs, id, levelkeys);
  3204. currentInitSegment = init;
  3205. frag.initSegment = currentInitSegment;
  3206. if (currentInitSegment.rawProgramDateTime && !frag.rawProgramDateTime) {
  3207. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  3208. }
  3209. } else {
  3210. // Initial segment tag is before segment duration tag
  3211. // Handle case where EXT-X-MAP is declared after EXT-X-BYTERANGE
  3212. var end = frag.byteRangeEndOffset;
  3213. if (end) {
  3214. var start = frag.byteRangeStartOffset;
  3215. nextByteRange = end - start + "@" + start;
  3216. } else {
  3217. nextByteRange = null;
  3218. }
  3219. setInitSegment(frag, mapAttrs, id, levelkeys);
  3220. currentInitSegment = frag;
  3221. createNextFrag = true;
  3222. }
  3223. break;
  3224. }
  3225. case 'SERVER-CONTROL':
  3226. {
  3227. var serverControlAttrs = new AttrList(value1);
  3228. level.canBlockReload = serverControlAttrs.bool('CAN-BLOCK-RELOAD');
  3229. level.canSkipUntil = serverControlAttrs.optionalFloat('CAN-SKIP-UNTIL', 0);
  3230. level.canSkipDateRanges = level.canSkipUntil > 0 && serverControlAttrs.bool('CAN-SKIP-DATERANGES');
  3231. level.partHoldBack = serverControlAttrs.optionalFloat('PART-HOLD-BACK', 0);
  3232. level.holdBack = serverControlAttrs.optionalFloat('HOLD-BACK', 0);
  3233. break;
  3234. }
  3235. case 'PART-INF':
  3236. {
  3237. var partInfAttrs = new AttrList(value1);
  3238. level.partTarget = partInfAttrs.decimalFloatingPoint('PART-TARGET');
  3239. break;
  3240. }
  3241. case 'PART':
  3242. {
  3243. var partList = level.partList;
  3244. if (!partList) {
  3245. partList = level.partList = [];
  3246. }
  3247. var previousFragmentPart = currentPart > 0 ? partList[partList.length - 1] : undefined;
  3248. var index = currentPart++;
  3249. var partAttrs = new AttrList(value1);
  3250. var part = new Part(partAttrs, frag, baseurl, index, previousFragmentPart);
  3251. partList.push(part);
  3252. frag.duration += part.duration;
  3253. break;
  3254. }
  3255. case 'PRELOAD-HINT':
  3256. {
  3257. var preloadHintAttrs = new AttrList(value1);
  3258. level.preloadHint = preloadHintAttrs;
  3259. break;
  3260. }
  3261. case 'RENDITION-REPORT':
  3262. {
  3263. var renditionReportAttrs = new AttrList(value1);
  3264. level.renditionReports = level.renditionReports || [];
  3265. level.renditionReports.push(renditionReportAttrs);
  3266. break;
  3267. }
  3268. default:
  3269. logger.warn("line parsed but not handled: " + result);
  3270. break;
  3271. }
  3272. }
  3273. }
  3274. if (prevFrag && !prevFrag.relurl) {
  3275. fragments.pop();
  3276. totalduration -= prevFrag.duration;
  3277. if (level.partList) {
  3278. level.fragmentHint = prevFrag;
  3279. }
  3280. } else if (level.partList) {
  3281. assignProgramDateTime(frag, prevFrag);
  3282. frag.cc = discontinuityCounter;
  3283. level.fragmentHint = frag;
  3284. if (levelkeys) {
  3285. setFragLevelKeys(frag, levelkeys, level);
  3286. }
  3287. }
  3288. var fragmentLength = fragments.length;
  3289. var firstFragment = fragments[0];
  3290. var lastFragment = fragments[fragmentLength - 1];
  3291. totalduration += level.skippedSegments * level.targetduration;
  3292. if (totalduration > 0 && fragmentLength && lastFragment) {
  3293. level.averagetargetduration = totalduration / fragmentLength;
  3294. var lastSn = lastFragment.sn;
  3295. level.endSN = lastSn !== 'initSegment' ? lastSn : 0;
  3296. if (!level.live) {
  3297. lastFragment.endList = true;
  3298. }
  3299. if (firstFragment) {
  3300. level.startCC = firstFragment.cc;
  3301. }
  3302. } else {
  3303. level.endSN = 0;
  3304. level.startCC = 0;
  3305. }
  3306. if (level.fragmentHint) {
  3307. totalduration += level.fragmentHint.duration;
  3308. }
  3309. level.totalduration = totalduration;
  3310. level.endCC = discontinuityCounter;
  3311. /**
  3312. * Backfill any missing PDT values
  3313. * "If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after
  3314. * one or more Media Segment URIs, the client SHOULD extrapolate
  3315. * backward from that tag (using EXTINF durations and/or media
  3316. * timestamps) to associate dates with those segments."
  3317. * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs
  3318. * computed.
  3319. */
  3320. if (firstPdtIndex > 0) {
  3321. backfillProgramDateTimes(fragments, firstPdtIndex);
  3322. }
  3323. return level;
  3324. };
  3325. return M3U8Parser;
  3326. }();
  3327. function parseKey(keyTagAttributes, baseurl, parsed) {
  3328. var _keyAttrs$METHOD, _keyAttrs$KEYFORMAT;
  3329. // https://tools.ietf.org/html/rfc8216#section-4.3.2.4
  3330. var keyAttrs = new AttrList(keyTagAttributes);
  3331. var decryptmethod = (_keyAttrs$METHOD = keyAttrs.METHOD) != null ? _keyAttrs$METHOD : '';
  3332. var decrypturi = keyAttrs.URI;
  3333. var decryptiv = keyAttrs.hexadecimalInteger('IV');
  3334. var decryptkeyformatversions = keyAttrs.KEYFORMATVERSIONS;
  3335. // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of "identity".
  3336. var decryptkeyformat = (_keyAttrs$KEYFORMAT = keyAttrs.KEYFORMAT) != null ? _keyAttrs$KEYFORMAT : 'identity';
  3337. if (decrypturi && keyAttrs.IV && !decryptiv) {
  3338. logger.error("Invalid IV: " + keyAttrs.IV);
  3339. }
  3340. // If decrypturi is a URI with a scheme, then baseurl will be ignored
  3341. // No uri is allowed when METHOD is NONE
  3342. var resolvedUri = decrypturi ? M3U8Parser.resolve(decrypturi, baseurl) : '';
  3343. var keyFormatVersions = (decryptkeyformatversions ? decryptkeyformatversions : '1').split('/').map(Number).filter(Number.isFinite);
  3344. return new LevelKey(decryptmethod, resolvedUri, decryptkeyformat, keyFormatVersions, decryptiv);
  3345. }
  3346. function parseStartTimeOffset(startAttributes) {
  3347. var startAttrs = new AttrList(startAttributes);
  3348. var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');
  3349. if (isFiniteNumber(startTimeOffset)) {
  3350. return startTimeOffset;
  3351. }
  3352. return null;
  3353. }
  3354. function setCodecs(codecsAttributeValue, level) {
  3355. var codecs = (codecsAttributeValue || '').split(/[ ,]+/).filter(function (c) {
  3356. return c;
  3357. });
  3358. ['video', 'audio', 'text'].forEach(function (type) {
  3359. var filtered = codecs.filter(function (codec) {
  3360. return isCodecType(codec, type);
  3361. });
  3362. if (filtered.length) {
  3363. // Comma separated list of all codecs for type
  3364. level[type + "Codec"] = filtered.join(',');
  3365. // Remove known codecs so that only unknownCodecs are left after iterating through each type
  3366. codecs = codecs.filter(function (codec) {
  3367. return filtered.indexOf(codec) === -1;
  3368. });
  3369. }
  3370. });
  3371. level.unknownCodecs = codecs;
  3372. }
  3373. function assignCodec(media, groupItem, codecProperty) {
  3374. var codecValue = groupItem[codecProperty];
  3375. if (codecValue) {
  3376. media[codecProperty] = codecValue;
  3377. }
  3378. }
  3379. function backfillProgramDateTimes(fragments, firstPdtIndex) {
  3380. var fragPrev = fragments[firstPdtIndex];
  3381. for (var i = firstPdtIndex; i--;) {
  3382. var frag = fragments[i];
  3383. // Exit on delta-playlist skipped segments
  3384. if (!frag) {
  3385. return;
  3386. }
  3387. frag.programDateTime = fragPrev.programDateTime - frag.duration * 1000;
  3388. fragPrev = frag;
  3389. }
  3390. }
  3391. function assignProgramDateTime(frag, prevFrag) {
  3392. if (frag.rawProgramDateTime) {
  3393. frag.programDateTime = Date.parse(frag.rawProgramDateTime);
  3394. } else if (prevFrag != null && prevFrag.programDateTime) {
  3395. frag.programDateTime = prevFrag.endProgramDateTime;
  3396. }
  3397. if (!isFiniteNumber(frag.programDateTime)) {
  3398. frag.programDateTime = null;
  3399. frag.rawProgramDateTime = null;
  3400. }
  3401. }
  3402. function setInitSegment(frag, mapAttrs, id, levelkeys) {
  3403. frag.relurl = mapAttrs.URI;
  3404. if (mapAttrs.BYTERANGE) {
  3405. frag.setByteRange(mapAttrs.BYTERANGE);
  3406. }
  3407. frag.level = id;
  3408. frag.sn = 'initSegment';
  3409. if (levelkeys) {
  3410. frag.levelkeys = levelkeys;
  3411. }
  3412. frag.initSegment = null;
  3413. }
  3414. function setFragLevelKeys(frag, levelkeys, level) {
  3415. frag.levelkeys = levelkeys;
  3416. var encryptedFragments = level.encryptedFragments;
  3417. if ((!encryptedFragments.length || encryptedFragments[encryptedFragments.length - 1].levelkeys !== levelkeys) && Object.keys(levelkeys).some(function (format) {
  3418. return levelkeys[format].isCommonEncryption;
  3419. })) {
  3420. encryptedFragments.push(frag);
  3421. }
  3422. }
  3423. var PlaylistContextType = {
  3424. MANIFEST: "manifest",
  3425. LEVEL: "level",
  3426. AUDIO_TRACK: "audioTrack",
  3427. SUBTITLE_TRACK: "subtitleTrack"
  3428. };
  3429. var PlaylistLevelType = {
  3430. MAIN: "main",
  3431. AUDIO: "audio",
  3432. SUBTITLE: "subtitle"
  3433. };
  3434. function mapContextToLevelType(context) {
  3435. var type = context.type;
  3436. switch (type) {
  3437. case PlaylistContextType.AUDIO_TRACK:
  3438. return PlaylistLevelType.AUDIO;
  3439. case PlaylistContextType.SUBTITLE_TRACK:
  3440. return PlaylistLevelType.SUBTITLE;
  3441. default:
  3442. return PlaylistLevelType.MAIN;
  3443. }
  3444. }
  3445. function getResponseUrl(response, context) {
  3446. var url = response.url;
  3447. // responseURL not supported on some browsers (it is used to detect URL redirection)
  3448. // data-uri mode also not supported (but no need to detect redirection)
  3449. if (url === undefined || url.indexOf('data:') === 0) {
  3450. // fallback to initial URL
  3451. url = context.url;
  3452. }
  3453. return url;
  3454. }
  3455. var PlaylistLoader = /*#__PURE__*/function () {
  3456. function PlaylistLoader(hls) {
  3457. this.hls = void 0;
  3458. this.loaders = Object.create(null);
  3459. this.variableList = null;
  3460. this.hls = hls;
  3461. this.registerListeners();
  3462. }
  3463. var _proto = PlaylistLoader.prototype;
  3464. _proto.startLoad = function startLoad(startPosition) {};
  3465. _proto.stopLoad = function stopLoad() {
  3466. this.destroyInternalLoaders();
  3467. };
  3468. _proto.registerListeners = function registerListeners() {
  3469. var hls = this.hls;
  3470. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3471. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  3472. hls.on(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  3473. hls.on(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  3474. };
  3475. _proto.unregisterListeners = function unregisterListeners() {
  3476. var hls = this.hls;
  3477. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3478. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  3479. hls.off(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  3480. hls.off(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  3481. }
  3482. /**
  3483. * Returns defaults or configured loader-type overloads (pLoader and loader config params)
  3484. */;
  3485. _proto.createInternalLoader = function createInternalLoader(context) {
  3486. var config = this.hls.config;
  3487. var PLoader = config.pLoader;
  3488. var Loader = config.loader;
  3489. var InternalLoader = PLoader || Loader;
  3490. var loader = new InternalLoader(config);
  3491. this.loaders[context.type] = loader;
  3492. return loader;
  3493. };
  3494. _proto.getInternalLoader = function getInternalLoader(context) {
  3495. return this.loaders[context.type];
  3496. };
  3497. _proto.resetInternalLoader = function resetInternalLoader(contextType) {
  3498. if (this.loaders[contextType]) {
  3499. delete this.loaders[contextType];
  3500. }
  3501. }
  3502. /**
  3503. * Call `destroy` on all internal loader instances mapped (one per context type)
  3504. */;
  3505. _proto.destroyInternalLoaders = function destroyInternalLoaders() {
  3506. for (var contextType in this.loaders) {
  3507. var loader = this.loaders[contextType];
  3508. if (loader) {
  3509. loader.destroy();
  3510. }
  3511. this.resetInternalLoader(contextType);
  3512. }
  3513. };
  3514. _proto.destroy = function destroy() {
  3515. this.variableList = null;
  3516. this.unregisterListeners();
  3517. this.destroyInternalLoaders();
  3518. };
  3519. _proto.onManifestLoading = function onManifestLoading(event, data) {
  3520. var url = data.url;
  3521. this.variableList = null;
  3522. this.load({
  3523. id: null,
  3524. level: 0,
  3525. responseType: 'text',
  3526. type: PlaylistContextType.MANIFEST,
  3527. url: url,
  3528. deliveryDirectives: null
  3529. });
  3530. };
  3531. _proto.onLevelLoading = function onLevelLoading(event, data) {
  3532. var id = data.id,
  3533. level = data.level,
  3534. pathwayId = data.pathwayId,
  3535. url = data.url,
  3536. deliveryDirectives = data.deliveryDirectives;
  3537. this.load({
  3538. id: id,
  3539. level: level,
  3540. pathwayId: pathwayId,
  3541. responseType: 'text',
  3542. type: PlaylistContextType.LEVEL,
  3543. url: url,
  3544. deliveryDirectives: deliveryDirectives
  3545. });
  3546. };
  3547. _proto.onAudioTrackLoading = function onAudioTrackLoading(event, data) {
  3548. var id = data.id,
  3549. groupId = data.groupId,
  3550. url = data.url,
  3551. deliveryDirectives = data.deliveryDirectives;
  3552. this.load({
  3553. id: id,
  3554. groupId: groupId,
  3555. level: null,
  3556. responseType: 'text',
  3557. type: PlaylistContextType.AUDIO_TRACK,
  3558. url: url,
  3559. deliveryDirectives: deliveryDirectives
  3560. });
  3561. };
  3562. _proto.onSubtitleTrackLoading = function onSubtitleTrackLoading(event, data) {
  3563. var id = data.id,
  3564. groupId = data.groupId,
  3565. url = data.url,
  3566. deliveryDirectives = data.deliveryDirectives;
  3567. this.load({
  3568. id: id,
  3569. groupId: groupId,
  3570. level: null,
  3571. responseType: 'text',
  3572. type: PlaylistContextType.SUBTITLE_TRACK,
  3573. url: url,
  3574. deliveryDirectives: deliveryDirectives
  3575. });
  3576. };
  3577. _proto.load = function load(context) {
  3578. var _context$deliveryDire,
  3579. _this = this;
  3580. var config = this.hls.config;
  3581. // logger.debug(`[playlist-loader]: Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);
  3582. // Check if a loader for this context already exists
  3583. var loader = this.getInternalLoader(context);
  3584. if (loader) {
  3585. var loaderContext = loader.context;
  3586. if (loaderContext && loaderContext.url === context.url && loaderContext.level === context.level) {
  3587. // same URL can't overlap
  3588. logger.trace('[playlist-loader]: playlist request ongoing');
  3589. return;
  3590. }
  3591. logger.log("[playlist-loader]: aborting previous loader for type: " + context.type);
  3592. loader.abort();
  3593. }
  3594. // apply different configs for retries depending on
  3595. // context (manifest, level, audio/subs playlist)
  3596. var loadPolicy;
  3597. if (context.type === PlaylistContextType.MANIFEST) {
  3598. loadPolicy = config.manifestLoadPolicy.default;
  3599. } else {
  3600. loadPolicy = _extends({}, config.playlistLoadPolicy.default, {
  3601. timeoutRetry: null,
  3602. errorRetry: null
  3603. });
  3604. }
  3605. loader = this.createInternalLoader(context);
  3606. // Override level/track timeout for LL-HLS requests
  3607. // (the default of 10000ms is counter productive to blocking playlist reload requests)
  3608. if (isFiniteNumber((_context$deliveryDire = context.deliveryDirectives) == null ? void 0 : _context$deliveryDire.part)) {
  3609. var levelDetails;
  3610. if (context.type === PlaylistContextType.LEVEL && context.level !== null) {
  3611. levelDetails = this.hls.levels[context.level].details;
  3612. } else if (context.type === PlaylistContextType.AUDIO_TRACK && context.id !== null) {
  3613. levelDetails = this.hls.audioTracks[context.id].details;
  3614. } else if (context.type === PlaylistContextType.SUBTITLE_TRACK && context.id !== null) {
  3615. levelDetails = this.hls.subtitleTracks[context.id].details;
  3616. }
  3617. if (levelDetails) {
  3618. var partTarget = levelDetails.partTarget;
  3619. var targetDuration = levelDetails.targetduration;
  3620. if (partTarget && targetDuration) {
  3621. var maxLowLatencyPlaylistRefresh = Math.max(partTarget * 3, targetDuration * 0.8) * 1000;
  3622. loadPolicy = _extends({}, loadPolicy, {
  3623. maxTimeToFirstByteMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs),
  3624. maxLoadTimeMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs)
  3625. });
  3626. }
  3627. }
  3628. }
  3629. var legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  3630. var loaderConfig = {
  3631. loadPolicy: loadPolicy,
  3632. timeout: loadPolicy.maxLoadTimeMs,
  3633. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  3634. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  3635. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  3636. };
  3637. var loaderCallbacks = {
  3638. onSuccess: function onSuccess(response, stats, context, networkDetails) {
  3639. var loader = _this.getInternalLoader(context);
  3640. _this.resetInternalLoader(context.type);
  3641. var string = response.data;
  3642. // Validate if it is an M3U8 at all
  3643. if (string.indexOf('#EXTM3U') !== 0) {
  3644. _this.handleManifestParsingError(response, context, new Error('no EXTM3U delimiter'), networkDetails || null, stats);
  3645. return;
  3646. }
  3647. stats.parsing.start = performance.now();
  3648. if (M3U8Parser.isMediaPlaylist(string)) {
  3649. _this.handleTrackOrLevelPlaylist(response, stats, context, networkDetails || null, loader);
  3650. } else {
  3651. _this.handleMasterPlaylist(response, stats, context, networkDetails);
  3652. }
  3653. },
  3654. onError: function onError(response, context, networkDetails, stats) {
  3655. _this.handleNetworkError(context, networkDetails, false, response, stats);
  3656. },
  3657. onTimeout: function onTimeout(stats, context, networkDetails) {
  3658. _this.handleNetworkError(context, networkDetails, true, undefined, stats);
  3659. }
  3660. };
  3661. // logger.debug(`[playlist-loader]: Calling internal loader delegate for URL: ${context.url}`);
  3662. loader.load(context, loaderConfig, loaderCallbacks);
  3663. };
  3664. _proto.handleMasterPlaylist = function handleMasterPlaylist(response, stats, context, networkDetails) {
  3665. var hls = this.hls;
  3666. var string = response.data;
  3667. var url = getResponseUrl(response, context);
  3668. var parsedResult = M3U8Parser.parseMasterPlaylist(string, url);
  3669. if (parsedResult.playlistParsingError) {
  3670. this.handleManifestParsingError(response, context, parsedResult.playlistParsingError, networkDetails, stats);
  3671. return;
  3672. }
  3673. var contentSteering = parsedResult.contentSteering,
  3674. levels = parsedResult.levels,
  3675. sessionData = parsedResult.sessionData,
  3676. sessionKeys = parsedResult.sessionKeys,
  3677. startTimeOffset = parsedResult.startTimeOffset,
  3678. variableList = parsedResult.variableList;
  3679. this.variableList = variableList;
  3680. var _M3U8Parser$parseMast = M3U8Parser.parseMasterPlaylistMedia(string, url, parsedResult),
  3681. _M3U8Parser$parseMast2 = _M3U8Parser$parseMast.AUDIO,
  3682. audioTracks = _M3U8Parser$parseMast2 === void 0 ? [] : _M3U8Parser$parseMast2,
  3683. subtitles = _M3U8Parser$parseMast.SUBTITLES,
  3684. captions = _M3U8Parser$parseMast['CLOSED-CAPTIONS'];
  3685. if (audioTracks.length) {
  3686. // check if we have found an audio track embedded in main playlist (audio track without URI attribute)
  3687. var embeddedAudioFound = audioTracks.some(function (audioTrack) {
  3688. return !audioTrack.url;
  3689. });
  3690. // if no embedded audio track defined, but audio codec signaled in quality level,
  3691. // we need to signal this main audio track this could happen with playlists with
  3692. // alt audio rendition in which quality levels (main)
  3693. // contains both audio+video. but with mixed audio track not signaled
  3694. if (!embeddedAudioFound && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
  3695. logger.log('[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one');
  3696. audioTracks.unshift({
  3697. type: 'main',
  3698. name: 'main',
  3699. groupId: 'main',
  3700. default: false,
  3701. autoselect: false,
  3702. forced: false,
  3703. id: -1,
  3704. attrs: new AttrList({}),
  3705. bitrate: 0,
  3706. url: ''
  3707. });
  3708. }
  3709. }
  3710. hls.trigger(Events.MANIFEST_LOADED, {
  3711. levels: levels,
  3712. audioTracks: audioTracks,
  3713. subtitles: subtitles,
  3714. captions: captions,
  3715. contentSteering: contentSteering,
  3716. url: url,
  3717. stats: stats,
  3718. networkDetails: networkDetails,
  3719. sessionData: sessionData,
  3720. sessionKeys: sessionKeys,
  3721. startTimeOffset: startTimeOffset,
  3722. variableList: variableList
  3723. });
  3724. };
  3725. _proto.handleTrackOrLevelPlaylist = function handleTrackOrLevelPlaylist(response, stats, context, networkDetails, loader) {
  3726. var hls = this.hls;
  3727. var id = context.id,
  3728. level = context.level,
  3729. type = context.type;
  3730. var url = getResponseUrl(response, context);
  3731. var levelUrlId = 0;
  3732. var levelId = isFiniteNumber(level) ? level : isFiniteNumber(id) ? id : 0;
  3733. var levelType = mapContextToLevelType(context);
  3734. var levelDetails = M3U8Parser.parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId, this.variableList);
  3735. // We have done our first request (Manifest-type) and receive
  3736. // not a master playlist but a chunk-list (track/level)
  3737. // We fire the manifest-loaded event anyway with the parsed level-details
  3738. // by creating a single-level structure for it.
  3739. if (type === PlaylistContextType.MANIFEST) {
  3740. var singleLevel = {
  3741. attrs: new AttrList({}),
  3742. bitrate: 0,
  3743. details: levelDetails,
  3744. name: '',
  3745. url: url
  3746. };
  3747. hls.trigger(Events.MANIFEST_LOADED, {
  3748. levels: [singleLevel],
  3749. audioTracks: [],
  3750. url: url,
  3751. stats: stats,
  3752. networkDetails: networkDetails,
  3753. sessionData: null,
  3754. sessionKeys: null,
  3755. contentSteering: null,
  3756. startTimeOffset: null,
  3757. variableList: null
  3758. });
  3759. }
  3760. // save parsing time
  3761. stats.parsing.end = performance.now();
  3762. // extend the context with the new levelDetails property
  3763. context.levelDetails = levelDetails;
  3764. this.handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader);
  3765. };
  3766. _proto.handleManifestParsingError = function handleManifestParsingError(response, context, error, networkDetails, stats) {
  3767. this.hls.trigger(Events.ERROR, {
  3768. type: ErrorTypes.NETWORK_ERROR,
  3769. details: ErrorDetails.MANIFEST_PARSING_ERROR,
  3770. fatal: context.type === PlaylistContextType.MANIFEST,
  3771. url: response.url,
  3772. err: error,
  3773. error: error,
  3774. reason: error.message,
  3775. response: response,
  3776. context: context,
  3777. networkDetails: networkDetails,
  3778. stats: stats
  3779. });
  3780. };
  3781. _proto.handleNetworkError = function handleNetworkError(context, networkDetails, timeout, response, stats) {
  3782. if (timeout === void 0) {
  3783. timeout = false;
  3784. }
  3785. var message = "A network " + (timeout ? 'timeout' : 'error' + (response ? ' (status ' + response.code + ')' : '')) + " occurred while loading " + context.type;
  3786. if (context.type === PlaylistContextType.LEVEL) {
  3787. message += ": " + context.level + " id: " + context.id;
  3788. } else if (context.type === PlaylistContextType.AUDIO_TRACK || context.type === PlaylistContextType.SUBTITLE_TRACK) {
  3789. message += " id: " + context.id + " group-id: \"" + context.groupId + "\"";
  3790. }
  3791. var error = new Error(message);
  3792. logger.warn("[playlist-loader]: " + message);
  3793. var details = ErrorDetails.UNKNOWN;
  3794. var fatal = false;
  3795. var loader = this.getInternalLoader(context);
  3796. switch (context.type) {
  3797. case PlaylistContextType.MANIFEST:
  3798. details = timeout ? ErrorDetails.MANIFEST_LOAD_TIMEOUT : ErrorDetails.MANIFEST_LOAD_ERROR;
  3799. fatal = true;
  3800. break;
  3801. case PlaylistContextType.LEVEL:
  3802. details = timeout ? ErrorDetails.LEVEL_LOAD_TIMEOUT : ErrorDetails.LEVEL_LOAD_ERROR;
  3803. fatal = false;
  3804. break;
  3805. case PlaylistContextType.AUDIO_TRACK:
  3806. details = timeout ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : ErrorDetails.AUDIO_TRACK_LOAD_ERROR;
  3807. fatal = false;
  3808. break;
  3809. case PlaylistContextType.SUBTITLE_TRACK:
  3810. details = timeout ? ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT : ErrorDetails.SUBTITLE_LOAD_ERROR;
  3811. fatal = false;
  3812. break;
  3813. }
  3814. if (loader) {
  3815. this.resetInternalLoader(context.type);
  3816. }
  3817. var errorData = {
  3818. type: ErrorTypes.NETWORK_ERROR,
  3819. details: details,
  3820. fatal: fatal,
  3821. url: context.url,
  3822. loader: loader,
  3823. context: context,
  3824. error: error,
  3825. networkDetails: networkDetails,
  3826. stats: stats
  3827. };
  3828. if (response) {
  3829. var url = (networkDetails == null ? void 0 : networkDetails.url) || context.url;
  3830. errorData.response = _objectSpread2({
  3831. url: url,
  3832. data: undefined
  3833. }, response);
  3834. }
  3835. this.hls.trigger(Events.ERROR, errorData);
  3836. };
  3837. _proto.handlePlaylistLoaded = function handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader) {
  3838. var hls = this.hls;
  3839. var type = context.type,
  3840. level = context.level,
  3841. id = context.id,
  3842. groupId = context.groupId,
  3843. deliveryDirectives = context.deliveryDirectives;
  3844. var url = getResponseUrl(response, context);
  3845. var parent = mapContextToLevelType(context);
  3846. var levelIndex = typeof context.level === 'number' && parent === PlaylistLevelType.MAIN ? level : undefined;
  3847. if (!levelDetails.fragments.length) {
  3848. var _error = new Error('No Segments found in Playlist');
  3849. hls.trigger(Events.ERROR, {
  3850. type: ErrorTypes.NETWORK_ERROR,
  3851. details: ErrorDetails.LEVEL_EMPTY_ERROR,
  3852. fatal: false,
  3853. url: url,
  3854. error: _error,
  3855. reason: _error.message,
  3856. response: response,
  3857. context: context,
  3858. level: levelIndex,
  3859. parent: parent,
  3860. networkDetails: networkDetails,
  3861. stats: stats
  3862. });
  3863. return;
  3864. }
  3865. if (!levelDetails.targetduration) {
  3866. levelDetails.playlistParsingError = new Error('Missing Target Duration');
  3867. }
  3868. var error = levelDetails.playlistParsingError;
  3869. if (error) {
  3870. hls.trigger(Events.ERROR, {
  3871. type: ErrorTypes.NETWORK_ERROR,
  3872. details: ErrorDetails.LEVEL_PARSING_ERROR,
  3873. fatal: false,
  3874. url: url,
  3875. error: error,
  3876. reason: error.message,
  3877. response: response,
  3878. context: context,
  3879. level: levelIndex,
  3880. parent: parent,
  3881. networkDetails: networkDetails,
  3882. stats: stats
  3883. });
  3884. return;
  3885. }
  3886. if (levelDetails.live && loader) {
  3887. if (loader.getCacheAge) {
  3888. levelDetails.ageHeader = loader.getCacheAge() || 0;
  3889. }
  3890. if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) {
  3891. levelDetails.ageHeader = 0;
  3892. }
  3893. }
  3894. switch (type) {
  3895. case PlaylistContextType.MANIFEST:
  3896. case PlaylistContextType.LEVEL:
  3897. hls.trigger(Events.LEVEL_LOADED, {
  3898. details: levelDetails,
  3899. level: levelIndex || 0,
  3900. id: id || 0,
  3901. stats: stats,
  3902. networkDetails: networkDetails,
  3903. deliveryDirectives: deliveryDirectives
  3904. });
  3905. break;
  3906. case PlaylistContextType.AUDIO_TRACK:
  3907. hls.trigger(Events.AUDIO_TRACK_LOADED, {
  3908. details: levelDetails,
  3909. id: id || 0,
  3910. groupId: groupId || '',
  3911. stats: stats,
  3912. networkDetails: networkDetails,
  3913. deliveryDirectives: deliveryDirectives
  3914. });
  3915. break;
  3916. case PlaylistContextType.SUBTITLE_TRACK:
  3917. hls.trigger(Events.SUBTITLE_TRACK_LOADED, {
  3918. details: levelDetails,
  3919. id: id || 0,
  3920. groupId: groupId || '',
  3921. stats: stats,
  3922. networkDetails: networkDetails,
  3923. deliveryDirectives: deliveryDirectives
  3924. });
  3925. break;
  3926. }
  3927. };
  3928. return PlaylistLoader;
  3929. }();
  3930. function sendAddTrackEvent(track, videoEl) {
  3931. var event;
  3932. try {
  3933. event = new Event('addtrack');
  3934. } catch (err) {
  3935. // for IE11
  3936. event = document.createEvent('Event');
  3937. event.initEvent('addtrack', false, false);
  3938. }
  3939. event.track = track;
  3940. videoEl.dispatchEvent(event);
  3941. }
  3942. function clearCurrentCues(track) {
  3943. // When track.mode is disabled, track.cues will be null.
  3944. // To guarantee the removal of cues, we need to temporarily
  3945. // change the mode to hidden
  3946. var mode = track.mode;
  3947. if (mode === 'disabled') {
  3948. track.mode = 'hidden';
  3949. }
  3950. if (track.cues) {
  3951. for (var i = track.cues.length; i--;) {
  3952. track.removeCue(track.cues[i]);
  3953. }
  3954. }
  3955. if (mode === 'disabled') {
  3956. track.mode = mode;
  3957. }
  3958. }
  3959. function removeCuesInRange(track, start, end, predicate) {
  3960. var mode = track.mode;
  3961. if (mode === 'disabled') {
  3962. track.mode = 'hidden';
  3963. }
  3964. if (track.cues && track.cues.length > 0) {
  3965. var cues = getCuesInRange(track.cues, start, end);
  3966. for (var i = 0; i < cues.length; i++) {
  3967. if (!predicate || predicate(cues[i])) {
  3968. track.removeCue(cues[i]);
  3969. }
  3970. }
  3971. }
  3972. if (mode === 'disabled') {
  3973. track.mode = mode;
  3974. }
  3975. }
  3976. // Find first cue starting after given time.
  3977. // Modified version of binary search O(log(n)).
  3978. function getFirstCueIndexAfterTime(cues, time) {
  3979. // If first cue starts after time, start there
  3980. if (time < cues[0].startTime) {
  3981. return 0;
  3982. }
  3983. // If the last cue ends before time there is no overlap
  3984. var len = cues.length - 1;
  3985. if (time > cues[len].endTime) {
  3986. return -1;
  3987. }
  3988. var left = 0;
  3989. var right = len;
  3990. while (left <= right) {
  3991. var mid = Math.floor((right + left) / 2);
  3992. if (time < cues[mid].startTime) {
  3993. right = mid - 1;
  3994. } else if (time > cues[mid].startTime && left < len) {
  3995. left = mid + 1;
  3996. } else {
  3997. // If it's not lower or higher, it must be equal.
  3998. return mid;
  3999. }
  4000. }
  4001. // At this point, left and right have swapped.
  4002. // No direct match was found, left or right element must be the closest. Check which one has the smallest diff.
  4003. return cues[left].startTime - time < time - cues[right].startTime ? left : right;
  4004. }
  4005. function getCuesInRange(cues, start, end) {
  4006. var cuesFound = [];
  4007. var firstCueInRange = getFirstCueIndexAfterTime(cues, start);
  4008. if (firstCueInRange > -1) {
  4009. for (var i = firstCueInRange, len = cues.length; i < len; i++) {
  4010. var _cue = cues[i];
  4011. if (_cue.startTime >= start && _cue.endTime <= end) {
  4012. cuesFound.push(_cue);
  4013. } else if (_cue.startTime > end) {
  4014. return cuesFound;
  4015. }
  4016. }
  4017. }
  4018. return cuesFound;
  4019. }
  4020. var MetadataSchema = {
  4021. audioId3: "org.id3",
  4022. dateRange: "com.apple.quicktime.HLS",
  4023. emsg: "https://aomedia.org/emsg/ID3"
  4024. };
  4025. var MIN_CUE_DURATION = 0.25;
  4026. function getCueClass() {
  4027. if (typeof self === 'undefined') return undefined;
  4028. return self.VTTCue || self.TextTrackCue;
  4029. }
  4030. function createCueWithDataFields(Cue, startTime, endTime, data, type) {
  4031. var cue = new Cue(startTime, endTime, '');
  4032. try {
  4033. cue.value = data;
  4034. if (type) {
  4035. cue.type = type;
  4036. }
  4037. } catch (e) {
  4038. cue = new Cue(startTime, endTime, JSON.stringify(type ? _objectSpread2({
  4039. type: type
  4040. }, data) : data));
  4041. }
  4042. return cue;
  4043. }
  4044. // VTTCue latest draft allows an infinite duration, fallback
  4045. // to MAX_VALUE if necessary
  4046. var MAX_CUE_ENDTIME = function () {
  4047. var Cue = getCueClass();
  4048. try {
  4049. Cue && new Cue(0, Number.POSITIVE_INFINITY, '');
  4050. } catch (e) {
  4051. return Number.MAX_VALUE;
  4052. }
  4053. return Number.POSITIVE_INFINITY;
  4054. }();
  4055. function dateRangeDateToTimelineSeconds(date, offset) {
  4056. return date.getTime() / 1000 - offset;
  4057. }
  4058. function hexToArrayBuffer(str) {
  4059. return Uint8Array.from(str.replace(/^0x/, '').replace(/([\da-fA-F]{2}) ?/g, '0x$1 ').replace(/ +$/, '').split(' ')).buffer;
  4060. }
  4061. var ID3TrackController = /*#__PURE__*/function () {
  4062. function ID3TrackController(hls) {
  4063. this.hls = void 0;
  4064. this.id3Track = null;
  4065. this.media = null;
  4066. this.dateRangeCuesAppended = {};
  4067. this.hls = hls;
  4068. this._registerListeners();
  4069. }
  4070. var _proto = ID3TrackController.prototype;
  4071. _proto.destroy = function destroy() {
  4072. this._unregisterListeners();
  4073. this.id3Track = null;
  4074. this.media = null;
  4075. this.dateRangeCuesAppended = {};
  4076. // @ts-ignore
  4077. this.hls = null;
  4078. };
  4079. _proto._registerListeners = function _registerListeners() {
  4080. var hls = this.hls;
  4081. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  4082. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  4083. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4084. hls.on(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  4085. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  4086. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  4087. };
  4088. _proto._unregisterListeners = function _unregisterListeners() {
  4089. var hls = this.hls;
  4090. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  4091. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  4092. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4093. hls.off(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  4094. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  4095. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  4096. }
  4097. // Add ID3 metatadata text track.
  4098. ;
  4099. _proto.onMediaAttached = function onMediaAttached(event, data) {
  4100. this.media = data.media;
  4101. };
  4102. _proto.onMediaDetaching = function onMediaDetaching() {
  4103. if (!this.id3Track) {
  4104. return;
  4105. }
  4106. clearCurrentCues(this.id3Track);
  4107. this.id3Track = null;
  4108. this.media = null;
  4109. this.dateRangeCuesAppended = {};
  4110. };
  4111. _proto.onManifestLoading = function onManifestLoading() {
  4112. this.dateRangeCuesAppended = {};
  4113. };
  4114. _proto.createTrack = function createTrack(media) {
  4115. var track = this.getID3Track(media.textTracks);
  4116. track.mode = 'hidden';
  4117. return track;
  4118. };
  4119. _proto.getID3Track = function getID3Track(textTracks) {
  4120. if (!this.media) {
  4121. return;
  4122. }
  4123. for (var i = 0; i < textTracks.length; i++) {
  4124. var textTrack = textTracks[i];
  4125. if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {
  4126. // send 'addtrack' when reusing the textTrack for metadata,
  4127. // same as what we do for captions
  4128. sendAddTrackEvent(textTrack, this.media);
  4129. return textTrack;
  4130. }
  4131. }
  4132. return this.media.addTextTrack('metadata', 'id3');
  4133. };
  4134. _proto.onFragParsingMetadata = function onFragParsingMetadata(event, data) {
  4135. if (!this.media) {
  4136. return;
  4137. }
  4138. var _this$hls$config = this.hls.config,
  4139. enableEmsgMetadataCues = _this$hls$config.enableEmsgMetadataCues,
  4140. enableID3MetadataCues = _this$hls$config.enableID3MetadataCues;
  4141. if (!enableEmsgMetadataCues && !enableID3MetadataCues) {
  4142. return;
  4143. }
  4144. var samples = data.samples;
  4145. // create track dynamically
  4146. if (!this.id3Track) {
  4147. this.id3Track = this.createTrack(this.media);
  4148. }
  4149. var Cue = getCueClass();
  4150. if (!Cue) {
  4151. return;
  4152. }
  4153. for (var i = 0; i < samples.length; i++) {
  4154. var type = samples[i].type;
  4155. if (type === MetadataSchema.emsg && !enableEmsgMetadataCues || !enableID3MetadataCues) {
  4156. continue;
  4157. }
  4158. var frames = getID3Frames(samples[i].data);
  4159. if (frames) {
  4160. var startTime = samples[i].pts;
  4161. var endTime = startTime + samples[i].duration;
  4162. if (endTime > MAX_CUE_ENDTIME) {
  4163. endTime = MAX_CUE_ENDTIME;
  4164. }
  4165. var timeDiff = endTime - startTime;
  4166. if (timeDiff <= 0) {
  4167. endTime = startTime + MIN_CUE_DURATION;
  4168. }
  4169. for (var j = 0; j < frames.length; j++) {
  4170. var frame = frames[j];
  4171. // Safari doesn't put the timestamp frame in the TextTrack
  4172. if (!isTimeStampFrame(frame)) {
  4173. // add a bounds to any unbounded cues
  4174. this.updateId3CueEnds(startTime, type);
  4175. var cue = createCueWithDataFields(Cue, startTime, endTime, frame, type);
  4176. if (cue) {
  4177. this.id3Track.addCue(cue);
  4178. }
  4179. }
  4180. }
  4181. }
  4182. }
  4183. };
  4184. _proto.updateId3CueEnds = function updateId3CueEnds(startTime, type) {
  4185. var _this$id3Track;
  4186. var cues = (_this$id3Track = this.id3Track) == null ? void 0 : _this$id3Track.cues;
  4187. if (cues) {
  4188. for (var i = cues.length; i--;) {
  4189. var cue = cues[i];
  4190. if (cue.type === type && cue.startTime < startTime && cue.endTime === MAX_CUE_ENDTIME) {
  4191. cue.endTime = startTime;
  4192. }
  4193. }
  4194. }
  4195. };
  4196. _proto.onBufferFlushing = function onBufferFlushing(event, _ref) {
  4197. var startOffset = _ref.startOffset,
  4198. endOffset = _ref.endOffset,
  4199. type = _ref.type;
  4200. var id3Track = this.id3Track,
  4201. hls = this.hls;
  4202. if (!hls) {
  4203. return;
  4204. }
  4205. var _hls$config = hls.config,
  4206. enableEmsgMetadataCues = _hls$config.enableEmsgMetadataCues,
  4207. enableID3MetadataCues = _hls$config.enableID3MetadataCues;
  4208. if (id3Track && (enableEmsgMetadataCues || enableID3MetadataCues)) {
  4209. var predicate;
  4210. if (type === 'audio') {
  4211. predicate = function predicate(cue) {
  4212. return cue.type === MetadataSchema.audioId3 && enableID3MetadataCues;
  4213. };
  4214. } else if (type === 'video') {
  4215. predicate = function predicate(cue) {
  4216. return cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  4217. };
  4218. } else {
  4219. predicate = function predicate(cue) {
  4220. return cue.type === MetadataSchema.audioId3 && enableID3MetadataCues || cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  4221. };
  4222. }
  4223. removeCuesInRange(id3Track, startOffset, endOffset, predicate);
  4224. }
  4225. };
  4226. _proto.onLevelUpdated = function onLevelUpdated(event, _ref2) {
  4227. var _this = this;
  4228. var details = _ref2.details;
  4229. if (!this.media || !details.hasProgramDateTime || !this.hls.config.enableDateRangeMetadataCues) {
  4230. return;
  4231. }
  4232. var dateRangeCuesAppended = this.dateRangeCuesAppended,
  4233. id3Track = this.id3Track;
  4234. var dateRanges = details.dateRanges;
  4235. var ids = Object.keys(dateRanges);
  4236. // Remove cues from track not found in details.dateRanges
  4237. if (id3Track) {
  4238. var idsToRemove = Object.keys(dateRangeCuesAppended).filter(function (id) {
  4239. return !ids.includes(id);
  4240. });
  4241. var _loop = function _loop() {
  4242. var id = idsToRemove[i];
  4243. Object.keys(dateRangeCuesAppended[id].cues).forEach(function (key) {
  4244. id3Track.removeCue(dateRangeCuesAppended[id].cues[key]);
  4245. });
  4246. delete dateRangeCuesAppended[id];
  4247. };
  4248. for (var i = idsToRemove.length; i--;) {
  4249. _loop();
  4250. }
  4251. }
  4252. // Exit if the playlist does not have Date Ranges or does not have Program Date Time
  4253. var lastFragment = details.fragments[details.fragments.length - 1];
  4254. if (ids.length === 0 || !isFiniteNumber(lastFragment == null ? void 0 : lastFragment.programDateTime)) {
  4255. return;
  4256. }
  4257. if (!this.id3Track) {
  4258. this.id3Track = this.createTrack(this.media);
  4259. }
  4260. var dateTimeOffset = lastFragment.programDateTime / 1000 - lastFragment.start;
  4261. var Cue = getCueClass();
  4262. var _loop2 = function _loop2() {
  4263. var id = ids[_i];
  4264. var dateRange = dateRanges[id];
  4265. var startTime = dateRangeDateToTimelineSeconds(dateRange.startDate, dateTimeOffset);
  4266. // Process DateRanges to determine end-time (known DURATION, END-DATE, or END-ON-NEXT)
  4267. var appendedDateRangeCues = dateRangeCuesAppended[id];
  4268. var cues = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.cues) || {};
  4269. var durationKnown = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.durationKnown) || false;
  4270. var endTime = MAX_CUE_ENDTIME;
  4271. var endDate = dateRange.endDate;
  4272. if (endDate) {
  4273. endTime = dateRangeDateToTimelineSeconds(endDate, dateTimeOffset);
  4274. durationKnown = true;
  4275. } else if (dateRange.endOnNext && !durationKnown) {
  4276. var nextDateRangeWithSameClass = ids.reduce(function (candidateDateRange, id) {
  4277. if (id !== dateRange.id) {
  4278. var otherDateRange = dateRanges[id];
  4279. if (otherDateRange.class === dateRange.class && otherDateRange.startDate > dateRange.startDate && (!candidateDateRange || dateRange.startDate < candidateDateRange.startDate)) {
  4280. return otherDateRange;
  4281. }
  4282. }
  4283. return candidateDateRange;
  4284. }, null);
  4285. if (nextDateRangeWithSameClass) {
  4286. endTime = dateRangeDateToTimelineSeconds(nextDateRangeWithSameClass.startDate, dateTimeOffset);
  4287. durationKnown = true;
  4288. }
  4289. }
  4290. // Create TextTrack Cues for each MetadataGroup Item (select DateRange attribute)
  4291. // This is to emulate Safari HLS playback handling of DateRange tags
  4292. var attributes = Object.keys(dateRange.attr);
  4293. for (var j = 0; j < attributes.length; j++) {
  4294. var key = attributes[j];
  4295. if (!isDateRangeCueAttribute(key)) {
  4296. continue;
  4297. }
  4298. var cue = cues[key];
  4299. if (cue) {
  4300. if (durationKnown && !appendedDateRangeCues.durationKnown) {
  4301. cue.endTime = endTime;
  4302. }
  4303. } else if (Cue) {
  4304. var data = dateRange.attr[key];
  4305. if (isSCTE35Attribute(key)) {
  4306. data = hexToArrayBuffer(data);
  4307. }
  4308. var _cue = createCueWithDataFields(Cue, startTime, endTime, {
  4309. key: key,
  4310. data: data
  4311. }, MetadataSchema.dateRange);
  4312. if (_cue) {
  4313. _cue.id = id;
  4314. _this.id3Track.addCue(_cue);
  4315. cues[key] = _cue;
  4316. }
  4317. }
  4318. }
  4319. // Keep track of processed DateRanges by ID for updating cues with new DateRange tag attributes
  4320. dateRangeCuesAppended[id] = {
  4321. cues: cues,
  4322. dateRange: dateRange,
  4323. durationKnown: durationKnown
  4324. };
  4325. };
  4326. for (var _i = 0; _i < ids.length; _i++) {
  4327. _loop2();
  4328. }
  4329. };
  4330. return ID3TrackController;
  4331. }();
  4332. var LatencyController = /*#__PURE__*/function () {
  4333. function LatencyController(hls) {
  4334. var _this = this;
  4335. this.hls = void 0;
  4336. this.config = void 0;
  4337. this.media = null;
  4338. this.levelDetails = null;
  4339. this.currentTime = 0;
  4340. this.stallCount = 0;
  4341. this._latency = null;
  4342. this.timeupdateHandler = function () {
  4343. return _this.timeupdate();
  4344. };
  4345. this.hls = hls;
  4346. this.config = hls.config;
  4347. this.registerListeners();
  4348. }
  4349. var _proto = LatencyController.prototype;
  4350. _proto.destroy = function destroy() {
  4351. this.unregisterListeners();
  4352. this.onMediaDetaching();
  4353. this.levelDetails = null;
  4354. // @ts-ignore
  4355. this.hls = this.timeupdateHandler = null;
  4356. };
  4357. _proto.registerListeners = function registerListeners() {
  4358. this.hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  4359. this.hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  4360. this.hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4361. this.hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  4362. this.hls.on(Events.ERROR, this.onError, this);
  4363. };
  4364. _proto.unregisterListeners = function unregisterListeners() {
  4365. this.hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  4366. this.hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  4367. this.hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4368. this.hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  4369. this.hls.off(Events.ERROR, this.onError, this);
  4370. };
  4371. _proto.onMediaAttached = function onMediaAttached(event, data) {
  4372. this.media = data.media;
  4373. this.media.addEventListener('timeupdate', this.timeupdateHandler);
  4374. };
  4375. _proto.onMediaDetaching = function onMediaDetaching() {
  4376. if (this.media) {
  4377. this.media.removeEventListener('timeupdate', this.timeupdateHandler);
  4378. this.media = null;
  4379. }
  4380. };
  4381. _proto.onManifestLoading = function onManifestLoading() {
  4382. this.levelDetails = null;
  4383. this._latency = null;
  4384. this.stallCount = 0;
  4385. };
  4386. _proto.onLevelUpdated = function onLevelUpdated(event, _ref) {
  4387. var details = _ref.details;
  4388. this.levelDetails = details;
  4389. if (details.advanced) {
  4390. this.timeupdate();
  4391. }
  4392. if (!details.live && this.media) {
  4393. this.media.removeEventListener('timeupdate', this.timeupdateHandler);
  4394. }
  4395. };
  4396. _proto.onError = function onError(event, data) {
  4397. var _this$levelDetails;
  4398. if (data.details !== ErrorDetails.BUFFER_STALLED_ERROR) {
  4399. return;
  4400. }
  4401. this.stallCount++;
  4402. if ((_this$levelDetails = this.levelDetails) != null && _this$levelDetails.live) {
  4403. logger.warn('[playback-rate-controller]: Stall detected, adjusting target latency');
  4404. }
  4405. };
  4406. _proto.timeupdate = function timeupdate() {
  4407. var media = this.media,
  4408. levelDetails = this.levelDetails;
  4409. if (!media || !levelDetails) {
  4410. return;
  4411. }
  4412. this.currentTime = media.currentTime;
  4413. var latency = this.computeLatency();
  4414. if (latency === null) {
  4415. return;
  4416. }
  4417. this._latency = latency;
  4418. // Adapt playbackRate to meet target latency in low-latency mode
  4419. var _this$config = this.config,
  4420. lowLatencyMode = _this$config.lowLatencyMode,
  4421. maxLiveSyncPlaybackRate = _this$config.maxLiveSyncPlaybackRate;
  4422. if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1 || !levelDetails.live) {
  4423. return;
  4424. }
  4425. var targetLatency = this.targetLatency;
  4426. if (targetLatency === null) {
  4427. return;
  4428. }
  4429. var distanceFromTarget = latency - targetLatency;
  4430. // Only adjust playbackRate when within one target duration of targetLatency
  4431. // and more than one second from under-buffering.
  4432. // Playback further than one target duration from target can be considered DVR playback.
  4433. var liveMinLatencyDuration = Math.min(this.maxLatency, targetLatency + levelDetails.targetduration);
  4434. var inLiveRange = distanceFromTarget < liveMinLatencyDuration;
  4435. if (inLiveRange && distanceFromTarget > 0.05 && this.forwardBufferLength > 1) {
  4436. var max = Math.min(2, Math.max(1.0, maxLiveSyncPlaybackRate));
  4437. var rate = Math.round(2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled)) * 20) / 20;
  4438. media.playbackRate = Math.min(max, Math.max(1, rate));
  4439. } else if (media.playbackRate !== 1 && media.playbackRate !== 0) {
  4440. media.playbackRate = 1;
  4441. }
  4442. };
  4443. _proto.estimateLiveEdge = function estimateLiveEdge() {
  4444. var levelDetails = this.levelDetails;
  4445. if (levelDetails === null) {
  4446. return null;
  4447. }
  4448. return levelDetails.edge + levelDetails.age;
  4449. };
  4450. _proto.computeLatency = function computeLatency() {
  4451. var liveEdge = this.estimateLiveEdge();
  4452. if (liveEdge === null) {
  4453. return null;
  4454. }
  4455. return liveEdge - this.currentTime;
  4456. };
  4457. _createClass(LatencyController, [{
  4458. key: "latency",
  4459. get: function get() {
  4460. return this._latency || 0;
  4461. }
  4462. }, {
  4463. key: "maxLatency",
  4464. get: function get() {
  4465. var config = this.config,
  4466. levelDetails = this.levelDetails;
  4467. if (config.liveMaxLatencyDuration !== undefined) {
  4468. return config.liveMaxLatencyDuration;
  4469. }
  4470. return levelDetails ? config.liveMaxLatencyDurationCount * levelDetails.targetduration : 0;
  4471. }
  4472. }, {
  4473. key: "targetLatency",
  4474. get: function get() {
  4475. var levelDetails = this.levelDetails;
  4476. if (levelDetails === null) {
  4477. return null;
  4478. }
  4479. var holdBack = levelDetails.holdBack,
  4480. partHoldBack = levelDetails.partHoldBack,
  4481. targetduration = levelDetails.targetduration;
  4482. var _this$config2 = this.config,
  4483. liveSyncDuration = _this$config2.liveSyncDuration,
  4484. liveSyncDurationCount = _this$config2.liveSyncDurationCount,
  4485. lowLatencyMode = _this$config2.lowLatencyMode;
  4486. var userConfig = this.hls.userConfig;
  4487. var targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack;
  4488. if (userConfig.liveSyncDuration || userConfig.liveSyncDurationCount || targetLatency === 0) {
  4489. targetLatency = liveSyncDuration !== undefined ? liveSyncDuration : liveSyncDurationCount * targetduration;
  4490. }
  4491. var maxLiveSyncOnStallIncrease = targetduration;
  4492. var liveSyncOnStallIncrease = 1.0;
  4493. return targetLatency + Math.min(this.stallCount * liveSyncOnStallIncrease, maxLiveSyncOnStallIncrease);
  4494. }
  4495. }, {
  4496. key: "liveSyncPosition",
  4497. get: function get() {
  4498. var liveEdge = this.estimateLiveEdge();
  4499. var targetLatency = this.targetLatency;
  4500. var levelDetails = this.levelDetails;
  4501. if (liveEdge === null || targetLatency === null || levelDetails === null) {
  4502. return null;
  4503. }
  4504. var edge = levelDetails.edge;
  4505. var syncPosition = liveEdge - targetLatency - this.edgeStalled;
  4506. var min = edge - levelDetails.totalduration;
  4507. var max = edge - (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration);
  4508. return Math.min(Math.max(min, syncPosition), max);
  4509. }
  4510. }, {
  4511. key: "drift",
  4512. get: function get() {
  4513. var levelDetails = this.levelDetails;
  4514. if (levelDetails === null) {
  4515. return 1;
  4516. }
  4517. return levelDetails.drift;
  4518. }
  4519. }, {
  4520. key: "edgeStalled",
  4521. get: function get() {
  4522. var levelDetails = this.levelDetails;
  4523. if (levelDetails === null) {
  4524. return 0;
  4525. }
  4526. var maxLevelUpdateAge = (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration) * 3;
  4527. return Math.max(levelDetails.age - maxLevelUpdateAge, 0);
  4528. }
  4529. }, {
  4530. key: "forwardBufferLength",
  4531. get: function get() {
  4532. var media = this.media,
  4533. levelDetails = this.levelDetails;
  4534. if (!media || !levelDetails) {
  4535. return 0;
  4536. }
  4537. var bufferedRanges = media.buffered.length;
  4538. return (bufferedRanges ? media.buffered.end(bufferedRanges - 1) : levelDetails.edge) - this.currentTime;
  4539. }
  4540. }]);
  4541. return LatencyController;
  4542. }();
  4543. var HdcpLevels = ['NONE', 'TYPE-0', 'TYPE-1', null];
  4544. function isHdcpLevel(value) {
  4545. return HdcpLevels.indexOf(value) > -1;
  4546. }
  4547. var VideoRangeValues = ['SDR', 'PQ', 'HLG'];
  4548. function isVideoRange(value) {
  4549. return !!value && VideoRangeValues.indexOf(value) > -1;
  4550. }
  4551. var HlsSkip = {
  4552. No: "",
  4553. Yes: "YES",
  4554. v2: "v2"
  4555. };
  4556. function getSkipValue(details) {
  4557. var canSkipUntil = details.canSkipUntil,
  4558. canSkipDateRanges = details.canSkipDateRanges,
  4559. age = details.age;
  4560. // A Client SHOULD NOT request a Playlist Delta Update unless it already
  4561. // has a version of the Playlist that is no older than one-half of the Skip Boundary.
  4562. // @see: https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis#section-6.3.7
  4563. var playlistRecentEnough = age < canSkipUntil / 2;
  4564. if (canSkipUntil && playlistRecentEnough) {
  4565. if (canSkipDateRanges) {
  4566. return HlsSkip.v2;
  4567. }
  4568. return HlsSkip.Yes;
  4569. }
  4570. return HlsSkip.No;
  4571. }
  4572. var HlsUrlParameters = /*#__PURE__*/function () {
  4573. function HlsUrlParameters(msn, part, skip) {
  4574. this.msn = void 0;
  4575. this.part = void 0;
  4576. this.skip = void 0;
  4577. this.msn = msn;
  4578. this.part = part;
  4579. this.skip = skip;
  4580. }
  4581. var _proto = HlsUrlParameters.prototype;
  4582. _proto.addDirectives = function addDirectives(uri) {
  4583. var url = new self.URL(uri);
  4584. if (this.msn !== undefined) {
  4585. url.searchParams.set('_HLS_msn', this.msn.toString());
  4586. }
  4587. if (this.part !== undefined) {
  4588. url.searchParams.set('_HLS_part', this.part.toString());
  4589. }
  4590. if (this.skip) {
  4591. url.searchParams.set('_HLS_skip', this.skip);
  4592. }
  4593. return url.href;
  4594. };
  4595. return HlsUrlParameters;
  4596. }();
  4597. var Level = /*#__PURE__*/function () {
  4598. function Level(data) {
  4599. this._attrs = void 0;
  4600. this.audioCodec = void 0;
  4601. this.bitrate = void 0;
  4602. this.codecSet = void 0;
  4603. this.url = void 0;
  4604. this.frameRate = void 0;
  4605. this.height = void 0;
  4606. this.id = void 0;
  4607. this.name = void 0;
  4608. this.videoCodec = void 0;
  4609. this.width = void 0;
  4610. this.details = void 0;
  4611. this.fragmentError = 0;
  4612. this.loadError = 0;
  4613. this.loaded = void 0;
  4614. this.realBitrate = 0;
  4615. this.supportedPromise = void 0;
  4616. this.supportedResult = void 0;
  4617. this._avgBitrate = 0;
  4618. this._audioGroups = void 0;
  4619. this._subtitleGroups = void 0;
  4620. // Deprecated (retained for backwards compatibility)
  4621. this._urlId = 0;
  4622. this.url = [data.url];
  4623. this._attrs = [data.attrs];
  4624. this.bitrate = data.bitrate;
  4625. if (data.details) {
  4626. this.details = data.details;
  4627. }
  4628. this.id = data.id || 0;
  4629. this.name = data.name;
  4630. this.width = data.width || 0;
  4631. this.height = data.height || 0;
  4632. this.frameRate = data.attrs.optionalFloat('FRAME-RATE', 0);
  4633. this._avgBitrate = data.attrs.decimalInteger('AVERAGE-BANDWIDTH');
  4634. this.audioCodec = data.audioCodec;
  4635. this.videoCodec = data.videoCodec;
  4636. this.codecSet = [data.videoCodec, data.audioCodec].filter(function (c) {
  4637. return !!c;
  4638. }).map(function (s) {
  4639. return s.substring(0, 4);
  4640. }).join(',');
  4641. this.addGroupId('audio', data.attrs.AUDIO);
  4642. this.addGroupId('text', data.attrs.SUBTITLES);
  4643. }
  4644. var _proto2 = Level.prototype;
  4645. _proto2.hasAudioGroup = function hasAudioGroup(groupId) {
  4646. return hasGroup(this._audioGroups, groupId);
  4647. };
  4648. _proto2.hasSubtitleGroup = function hasSubtitleGroup(groupId) {
  4649. return hasGroup(this._subtitleGroups, groupId);
  4650. };
  4651. _proto2.addGroupId = function addGroupId(type, groupId) {
  4652. if (!groupId) {
  4653. return;
  4654. }
  4655. if (type === 'audio') {
  4656. var audioGroups = this._audioGroups;
  4657. if (!audioGroups) {
  4658. audioGroups = this._audioGroups = [];
  4659. }
  4660. if (audioGroups.indexOf(groupId) === -1) {
  4661. audioGroups.push(groupId);
  4662. }
  4663. } else if (type === 'text') {
  4664. var subtitleGroups = this._subtitleGroups;
  4665. if (!subtitleGroups) {
  4666. subtitleGroups = this._subtitleGroups = [];
  4667. }
  4668. if (subtitleGroups.indexOf(groupId) === -1) {
  4669. subtitleGroups.push(groupId);
  4670. }
  4671. }
  4672. }
  4673. // Deprecated methods (retained for backwards compatibility)
  4674. ;
  4675. _proto2.addFallback = function addFallback() {};
  4676. _createClass(Level, [{
  4677. key: "maxBitrate",
  4678. get: function get() {
  4679. return Math.max(this.realBitrate, this.bitrate);
  4680. }
  4681. }, {
  4682. key: "averageBitrate",
  4683. get: function get() {
  4684. return this._avgBitrate || this.realBitrate || this.bitrate;
  4685. }
  4686. }, {
  4687. key: "attrs",
  4688. get: function get() {
  4689. return this._attrs[0];
  4690. }
  4691. }, {
  4692. key: "codecs",
  4693. get: function get() {
  4694. return this.attrs.CODECS || '';
  4695. }
  4696. }, {
  4697. key: "pathwayId",
  4698. get: function get() {
  4699. return this.attrs['PATHWAY-ID'] || '.';
  4700. }
  4701. }, {
  4702. key: "videoRange",
  4703. get: function get() {
  4704. return this.attrs['VIDEO-RANGE'] || 'SDR';
  4705. }
  4706. }, {
  4707. key: "score",
  4708. get: function get() {
  4709. return this.attrs.optionalFloat('SCORE', 0);
  4710. }
  4711. }, {
  4712. key: "uri",
  4713. get: function get() {
  4714. return this.url[0] || '';
  4715. }
  4716. }, {
  4717. key: "audioGroups",
  4718. get: function get() {
  4719. return this._audioGroups;
  4720. }
  4721. }, {
  4722. key: "subtitleGroups",
  4723. get: function get() {
  4724. return this._subtitleGroups;
  4725. }
  4726. }, {
  4727. key: "urlId",
  4728. get: function get() {
  4729. return 0;
  4730. },
  4731. set: function set(value) {}
  4732. }, {
  4733. key: "audioGroupIds",
  4734. get: function get() {
  4735. return this.audioGroups ? [this.audioGroupId] : undefined;
  4736. }
  4737. }, {
  4738. key: "textGroupIds",
  4739. get: function get() {
  4740. return this.subtitleGroups ? [this.textGroupId] : undefined;
  4741. }
  4742. }, {
  4743. key: "audioGroupId",
  4744. get: function get() {
  4745. var _this$audioGroups;
  4746. return (_this$audioGroups = this.audioGroups) == null ? void 0 : _this$audioGroups[0];
  4747. }
  4748. }, {
  4749. key: "textGroupId",
  4750. get: function get() {
  4751. var _this$subtitleGroups;
  4752. return (_this$subtitleGroups = this.subtitleGroups) == null ? void 0 : _this$subtitleGroups[0];
  4753. }
  4754. }]);
  4755. return Level;
  4756. }();
  4757. function hasGroup(groups, groupId) {
  4758. if (!groupId || !groups) {
  4759. return false;
  4760. }
  4761. return groups.indexOf(groupId) !== -1;
  4762. }
  4763. function updateFromToPTS(fragFrom, fragTo) {
  4764. var fragToPTS = fragTo.startPTS;
  4765. // if we know startPTS[toIdx]
  4766. if (isFiniteNumber(fragToPTS)) {
  4767. // update fragment duration.
  4768. // it helps to fix drifts between playlist reported duration and fragment real duration
  4769. var duration = 0;
  4770. var frag;
  4771. if (fragTo.sn > fragFrom.sn) {
  4772. duration = fragToPTS - fragFrom.start;
  4773. frag = fragFrom;
  4774. } else {
  4775. duration = fragFrom.start - fragToPTS;
  4776. frag = fragTo;
  4777. }
  4778. if (frag.duration !== duration) {
  4779. frag.duration = duration;
  4780. }
  4781. // we dont know startPTS[toIdx]
  4782. } else if (fragTo.sn > fragFrom.sn) {
  4783. var contiguous = fragFrom.cc === fragTo.cc;
  4784. // TODO: With part-loading end/durations we need to confirm the whole fragment is loaded before using (or setting) minEndPTS
  4785. if (contiguous && fragFrom.minEndPTS) {
  4786. fragTo.start = fragFrom.start + (fragFrom.minEndPTS - fragFrom.start);
  4787. } else {
  4788. fragTo.start = fragFrom.start + fragFrom.duration;
  4789. }
  4790. } else {
  4791. fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);
  4792. }
  4793. }
  4794. function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
  4795. var parsedMediaDuration = endPTS - startPTS;
  4796. if (parsedMediaDuration <= 0) {
  4797. logger.warn('Fragment should have a positive duration', frag);
  4798. endPTS = startPTS + frag.duration;
  4799. endDTS = startDTS + frag.duration;
  4800. }
  4801. var maxStartPTS = startPTS;
  4802. var minEndPTS = endPTS;
  4803. var fragStartPts = frag.startPTS;
  4804. var fragEndPts = frag.endPTS;
  4805. if (isFiniteNumber(fragStartPts)) {
  4806. // delta PTS between audio and video
  4807. var deltaPTS = Math.abs(fragStartPts - startPTS);
  4808. if (!isFiniteNumber(frag.deltaPTS)) {
  4809. frag.deltaPTS = deltaPTS;
  4810. } else {
  4811. frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
  4812. }
  4813. maxStartPTS = Math.max(startPTS, fragStartPts);
  4814. startPTS = Math.min(startPTS, fragStartPts);
  4815. startDTS = Math.min(startDTS, frag.startDTS);
  4816. minEndPTS = Math.min(endPTS, fragEndPts);
  4817. endPTS = Math.max(endPTS, fragEndPts);
  4818. endDTS = Math.max(endDTS, frag.endDTS);
  4819. }
  4820. var drift = startPTS - frag.start;
  4821. if (frag.start !== 0) {
  4822. frag.start = startPTS;
  4823. }
  4824. frag.duration = endPTS - frag.start;
  4825. frag.startPTS = startPTS;
  4826. frag.maxStartPTS = maxStartPTS;
  4827. frag.startDTS = startDTS;
  4828. frag.endPTS = endPTS;
  4829. frag.minEndPTS = minEndPTS;
  4830. frag.endDTS = endDTS;
  4831. var sn = frag.sn; // 'initSegment'
  4832. // exit if sn out of range
  4833. if (!details || sn < details.startSN || sn > details.endSN) {
  4834. return 0;
  4835. }
  4836. var i;
  4837. var fragIdx = sn - details.startSN;
  4838. var fragments = details.fragments;
  4839. // update frag reference in fragments array
  4840. // rationale is that fragments array might not contain this frag object.
  4841. // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()
  4842. // if we don't update frag, we won't be able to propagate PTS info on the playlist
  4843. // resulting in invalid sliding computation
  4844. fragments[fragIdx] = frag;
  4845. // adjust fragment PTS/duration from seqnum-1 to frag 0
  4846. for (i = fragIdx; i > 0; i--) {
  4847. updateFromToPTS(fragments[i], fragments[i - 1]);
  4848. }
  4849. // adjust fragment PTS/duration from seqnum to last frag
  4850. for (i = fragIdx; i < fragments.length - 1; i++) {
  4851. updateFromToPTS(fragments[i], fragments[i + 1]);
  4852. }
  4853. if (details.fragmentHint) {
  4854. updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint);
  4855. }
  4856. details.PTSKnown = details.alignedSliding = true;
  4857. return drift;
  4858. }
  4859. function mergeDetails(oldDetails, newDetails) {
  4860. // Track the last initSegment processed. Initialize it to the last one on the timeline.
  4861. var currentInitSegment = null;
  4862. var oldFragments = oldDetails.fragments;
  4863. for (var i = oldFragments.length - 1; i >= 0; i--) {
  4864. var oldInit = oldFragments[i].initSegment;
  4865. if (oldInit) {
  4866. currentInitSegment = oldInit;
  4867. break;
  4868. }
  4869. }
  4870. if (oldDetails.fragmentHint) {
  4871. // prevent PTS and duration from being adjusted on the next hint
  4872. delete oldDetails.fragmentHint.endPTS;
  4873. }
  4874. // check if old/new playlists have fragments in common
  4875. // loop through overlapping SN and update startPTS , cc, and duration if any found
  4876. var ccOffset = 0;
  4877. var PTSFrag;
  4878. mapFragmentIntersection(oldDetails, newDetails, function (oldFrag, newFrag) {
  4879. if (oldFrag.relurl) {
  4880. // Do not compare CC if the old fragment has no url. This is a level.fragmentHint used by LL-HLS parts.
  4881. // It maybe be off by 1 if it was created before any parts or discontinuity tags were appended to the end
  4882. // of the playlist.
  4883. ccOffset = oldFrag.cc - newFrag.cc;
  4884. }
  4885. if (isFiniteNumber(oldFrag.startPTS) && isFiniteNumber(oldFrag.endPTS)) {
  4886. newFrag.start = newFrag.startPTS = oldFrag.startPTS;
  4887. newFrag.startDTS = oldFrag.startDTS;
  4888. newFrag.maxStartPTS = oldFrag.maxStartPTS;
  4889. newFrag.endPTS = oldFrag.endPTS;
  4890. newFrag.endDTS = oldFrag.endDTS;
  4891. newFrag.minEndPTS = oldFrag.minEndPTS;
  4892. newFrag.duration = oldFrag.endPTS - oldFrag.startPTS;
  4893. if (newFrag.duration) {
  4894. PTSFrag = newFrag;
  4895. }
  4896. // PTS is known when any segment has startPTS and endPTS
  4897. newDetails.PTSKnown = newDetails.alignedSliding = true;
  4898. }
  4899. newFrag.elementaryStreams = oldFrag.elementaryStreams;
  4900. newFrag.loader = oldFrag.loader;
  4901. newFrag.stats = oldFrag.stats;
  4902. if (oldFrag.initSegment) {
  4903. newFrag.initSegment = oldFrag.initSegment;
  4904. currentInitSegment = oldFrag.initSegment;
  4905. }
  4906. });
  4907. if (currentInitSegment) {
  4908. var fragmentsToCheck = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
  4909. fragmentsToCheck.forEach(function (frag) {
  4910. var _currentInitSegment;
  4911. if (frag && (!frag.initSegment || frag.initSegment.relurl === ((_currentInitSegment = currentInitSegment) == null ? void 0 : _currentInitSegment.relurl))) {
  4912. frag.initSegment = currentInitSegment;
  4913. }
  4914. });
  4915. }
  4916. if (newDetails.skippedSegments) {
  4917. newDetails.deltaUpdateFailed = newDetails.fragments.some(function (frag) {
  4918. return !frag;
  4919. });
  4920. if (newDetails.deltaUpdateFailed) {
  4921. logger.warn('[level-helper] Previous playlist missing segments skipped in delta playlist');
  4922. for (var _i = newDetails.skippedSegments; _i--;) {
  4923. newDetails.fragments.shift();
  4924. }
  4925. newDetails.startSN = newDetails.fragments[0].sn;
  4926. newDetails.startCC = newDetails.fragments[0].cc;
  4927. } else if (newDetails.canSkipDateRanges) {
  4928. newDetails.dateRanges = mergeDateRanges(oldDetails.dateRanges, newDetails.dateRanges, newDetails.recentlyRemovedDateranges);
  4929. }
  4930. }
  4931. var newFragments = newDetails.fragments;
  4932. if (ccOffset) {
  4933. logger.warn('discontinuity sliding from playlist, take drift into account');
  4934. for (var _i2 = 0; _i2 < newFragments.length; _i2++) {
  4935. newFragments[_i2].cc += ccOffset;
  4936. }
  4937. }
  4938. if (newDetails.skippedSegments) {
  4939. newDetails.startCC = newDetails.fragments[0].cc;
  4940. }
  4941. // Merge parts
  4942. mapPartIntersection(oldDetails.partList, newDetails.partList, function (oldPart, newPart) {
  4943. newPart.elementaryStreams = oldPart.elementaryStreams;
  4944. newPart.stats = oldPart.stats;
  4945. });
  4946. // if at least one fragment contains PTS info, recompute PTS information for all fragments
  4947. if (PTSFrag) {
  4948. updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
  4949. } else {
  4950. // ensure that delta is within oldFragments range
  4951. // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])
  4952. // in that case we also need to adjust start offset of all fragments
  4953. adjustSliding(oldDetails, newDetails);
  4954. }
  4955. if (newFragments.length) {
  4956. newDetails.totalduration = newDetails.edge - newFragments[0].start;
  4957. }
  4958. newDetails.driftStartTime = oldDetails.driftStartTime;
  4959. newDetails.driftStart = oldDetails.driftStart;
  4960. var advancedDateTime = newDetails.advancedDateTime;
  4961. if (newDetails.advanced && advancedDateTime) {
  4962. var edge = newDetails.edge;
  4963. if (!newDetails.driftStart) {
  4964. newDetails.driftStartTime = advancedDateTime;
  4965. newDetails.driftStart = edge;
  4966. }
  4967. newDetails.driftEndTime = advancedDateTime;
  4968. newDetails.driftEnd = edge;
  4969. } else {
  4970. newDetails.driftEndTime = oldDetails.driftEndTime;
  4971. newDetails.driftEnd = oldDetails.driftEnd;
  4972. newDetails.advancedDateTime = oldDetails.advancedDateTime;
  4973. }
  4974. }
  4975. function mergeDateRanges(oldDateRanges, deltaDateRanges, recentlyRemovedDateranges) {
  4976. var dateRanges = _extends({}, oldDateRanges);
  4977. if (recentlyRemovedDateranges) {
  4978. recentlyRemovedDateranges.forEach(function (id) {
  4979. delete dateRanges[id];
  4980. });
  4981. }
  4982. Object.keys(deltaDateRanges).forEach(function (id) {
  4983. var dateRange = new DateRange(deltaDateRanges[id].attr, dateRanges[id]);
  4984. if (dateRange.isValid) {
  4985. dateRanges[id] = dateRange;
  4986. } else {
  4987. logger.warn("Ignoring invalid Playlist Delta Update DATERANGE tag: \"" + JSON.stringify(deltaDateRanges[id].attr) + "\"");
  4988. }
  4989. });
  4990. return dateRanges;
  4991. }
  4992. function mapPartIntersection(oldParts, newParts, intersectionFn) {
  4993. if (oldParts && newParts) {
  4994. var delta = 0;
  4995. for (var i = 0, len = oldParts.length; i <= len; i++) {
  4996. var _oldPart = oldParts[i];
  4997. var _newPart = newParts[i + delta];
  4998. if (_oldPart && _newPart && _oldPart.index === _newPart.index && _oldPart.fragment.sn === _newPart.fragment.sn) {
  4999. intersectionFn(_oldPart, _newPart);
  5000. } else {
  5001. delta--;
  5002. }
  5003. }
  5004. }
  5005. }
  5006. function mapFragmentIntersection(oldDetails, newDetails, intersectionFn) {
  5007. var skippedSegments = newDetails.skippedSegments;
  5008. var start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;
  5009. var end = (oldDetails.fragmentHint ? 1 : 0) + (skippedSegments ? newDetails.endSN : Math.min(oldDetails.endSN, newDetails.endSN)) - newDetails.startSN;
  5010. var delta = newDetails.startSN - oldDetails.startSN;
  5011. var newFrags = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
  5012. var oldFrags = oldDetails.fragmentHint ? oldDetails.fragments.concat(oldDetails.fragmentHint) : oldDetails.fragments;
  5013. for (var i = start; i <= end; i++) {
  5014. var _oldFrag = oldFrags[delta + i];
  5015. var _newFrag = newFrags[i];
  5016. if (skippedSegments && !_newFrag && i < skippedSegments) {
  5017. // Fill in skipped segments in delta playlist
  5018. _newFrag = newDetails.fragments[i] = _oldFrag;
  5019. }
  5020. if (_oldFrag && _newFrag) {
  5021. intersectionFn(_oldFrag, _newFrag);
  5022. }
  5023. }
  5024. }
  5025. function adjustSliding(oldDetails, newDetails) {
  5026. var delta = newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN;
  5027. var oldFragments = oldDetails.fragments;
  5028. if (delta < 0 || delta >= oldFragments.length) {
  5029. return;
  5030. }
  5031. addSliding(newDetails, oldFragments[delta].start);
  5032. }
  5033. function addSliding(details, start) {
  5034. if (start) {
  5035. var fragments = details.fragments;
  5036. for (var i = details.skippedSegments; i < fragments.length; i++) {
  5037. fragments[i].start += start;
  5038. }
  5039. if (details.fragmentHint) {
  5040. details.fragmentHint.start += start;
  5041. }
  5042. }
  5043. }
  5044. function computeReloadInterval(newDetails, distanceToLiveEdgeMs) {
  5045. if (distanceToLiveEdgeMs === void 0) {
  5046. distanceToLiveEdgeMs = Infinity;
  5047. }
  5048. var reloadInterval = 1000 * newDetails.targetduration;
  5049. if (newDetails.updated) {
  5050. // Use last segment duration when shorter than target duration and near live edge
  5051. var fragments = newDetails.fragments;
  5052. var liveEdgeMaxTargetDurations = 4;
  5053. if (fragments.length && reloadInterval * liveEdgeMaxTargetDurations > distanceToLiveEdgeMs) {
  5054. var lastSegmentDuration = fragments[fragments.length - 1].duration * 1000;
  5055. if (lastSegmentDuration < reloadInterval) {
  5056. reloadInterval = lastSegmentDuration;
  5057. }
  5058. }
  5059. } else {
  5060. // estimate = 'miss half average';
  5061. // follow HLS Spec, If the client reloads a Playlist file and finds that it has not
  5062. // changed then it MUST wait for a period of one-half the target
  5063. // duration before retrying.
  5064. reloadInterval /= 2;
  5065. }
  5066. return Math.round(reloadInterval);
  5067. }
  5068. function getFragmentWithSN(level, sn, fragCurrent) {
  5069. if (!(level != null && level.details)) {
  5070. return null;
  5071. }
  5072. var levelDetails = level.details;
  5073. var fragment = levelDetails.fragments[sn - levelDetails.startSN];
  5074. if (fragment) {
  5075. return fragment;
  5076. }
  5077. fragment = levelDetails.fragmentHint;
  5078. if (fragment && fragment.sn === sn) {
  5079. return fragment;
  5080. }
  5081. if (sn < levelDetails.startSN && fragCurrent && fragCurrent.sn === sn) {
  5082. return fragCurrent;
  5083. }
  5084. return null;
  5085. }
  5086. function getPartWith(level, sn, partIndex) {
  5087. var _level$details;
  5088. if (!(level != null && level.details)) {
  5089. return null;
  5090. }
  5091. return findPart((_level$details = level.details) == null ? void 0 : _level$details.partList, sn, partIndex);
  5092. }
  5093. function findPart(partList, sn, partIndex) {
  5094. if (partList) {
  5095. for (var i = partList.length; i--;) {
  5096. var part = partList[i];
  5097. if (part.index === partIndex && part.fragment.sn === sn) {
  5098. return part;
  5099. }
  5100. }
  5101. }
  5102. return null;
  5103. }
  5104. function reassignFragmentLevelIndexes(levels) {
  5105. levels.forEach(function (level, index) {
  5106. var details = level.details;
  5107. if (details != null && details.fragments) {
  5108. details.fragments.forEach(function (fragment) {
  5109. fragment.level = index;
  5110. });
  5111. }
  5112. });
  5113. }
  5114. function isTimeoutError(error) {
  5115. switch (error.details) {
  5116. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  5117. case ErrorDetails.KEY_LOAD_TIMEOUT:
  5118. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  5119. case ErrorDetails.MANIFEST_LOAD_TIMEOUT:
  5120. return true;
  5121. }
  5122. return false;
  5123. }
  5124. function getRetryConfig(loadPolicy, error) {
  5125. var isTimeout = isTimeoutError(error);
  5126. return loadPolicy.default[(isTimeout ? 'timeout' : 'error') + "Retry"];
  5127. }
  5128. function getRetryDelay(retryConfig, retryCount) {
  5129. // exponential backoff capped to max retry delay
  5130. var backoffFactor = retryConfig.backoff === 'linear' ? 1 : Math.pow(2, retryCount);
  5131. return Math.min(backoffFactor * retryConfig.retryDelayMs, retryConfig.maxRetryDelayMs);
  5132. }
  5133. function getLoaderConfigWithoutReties(loderConfig) {
  5134. return _objectSpread2(_objectSpread2({}, loderConfig), {
  5135. errorRetry: null,
  5136. timeoutRetry: null
  5137. });
  5138. }
  5139. function shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse) {
  5140. if (!retryConfig) {
  5141. return false;
  5142. }
  5143. var httpStatus = loaderResponse == null ? void 0 : loaderResponse.code;
  5144. var retry = retryCount < retryConfig.maxNumRetry && (retryForHttpStatus(httpStatus) || !!isTimeout);
  5145. return retryConfig.shouldRetry ? retryConfig.shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse, retry) : retry;
  5146. }
  5147. function retryForHttpStatus(httpStatus) {
  5148. // Do not retry on status 4xx, status 0 (CORS error), or undefined (decrypt/gap/parse error)
  5149. return httpStatus === 0 && navigator.onLine === false || !!httpStatus && (httpStatus < 400 || httpStatus > 499);
  5150. }
  5151. var BinarySearch = {
  5152. /**
  5153. * Searches for an item in an array which matches a certain condition.
  5154. * This requires the condition to only match one item in the array,
  5155. * and for the array to be ordered.
  5156. *
  5157. * @param list The array to search.
  5158. * @param comparisonFn
  5159. * Called and provided a candidate item as the first argument.
  5160. * Should return:
  5161. * > -1 if the item should be located at a lower index than the provided item.
  5162. * > 1 if the item should be located at a higher index than the provided item.
  5163. * > 0 if the item is the item you're looking for.
  5164. *
  5165. * @returns the object if found, otherwise returns null
  5166. */
  5167. search: function search(list, comparisonFn) {
  5168. var minIndex = 0;
  5169. var maxIndex = list.length - 1;
  5170. var currentIndex = null;
  5171. var currentElement = null;
  5172. while (minIndex <= maxIndex) {
  5173. currentIndex = (minIndex + maxIndex) / 2 | 0;
  5174. currentElement = list[currentIndex];
  5175. var comparisonResult = comparisonFn(currentElement);
  5176. if (comparisonResult > 0) {
  5177. minIndex = currentIndex + 1;
  5178. } else if (comparisonResult < 0) {
  5179. maxIndex = currentIndex - 1;
  5180. } else {
  5181. return currentElement;
  5182. }
  5183. }
  5184. return null;
  5185. }
  5186. };
  5187. /**
  5188. * Returns first fragment whose endPdt value exceeds the given PDT, or null.
  5189. * @param fragments - The array of candidate fragments
  5190. * @param PDTValue - The PDT value which must be exceeded
  5191. * @param maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  5192. */
  5193. function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
  5194. if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !isFiniteNumber(PDTValue)) {
  5195. return null;
  5196. }
  5197. // if less than start
  5198. var startPDT = fragments[0].programDateTime;
  5199. if (PDTValue < (startPDT || 0)) {
  5200. return null;
  5201. }
  5202. var endPDT = fragments[fragments.length - 1].endProgramDateTime;
  5203. if (PDTValue >= (endPDT || 0)) {
  5204. return null;
  5205. }
  5206. maxFragLookUpTolerance = maxFragLookUpTolerance || 0;
  5207. for (var seg = 0; seg < fragments.length; ++seg) {
  5208. var frag = fragments[seg];
  5209. if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
  5210. return frag;
  5211. }
  5212. }
  5213. return null;
  5214. }
  5215. /**
  5216. * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.
  5217. * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus
  5218. * breaking any traps which would cause the same fragment to be continuously selected within a small range.
  5219. * @param fragPrevious - The last frag successfully appended
  5220. * @param fragments - The array of candidate fragments
  5221. * @param bufferEnd - The end of the contiguous buffered range the playhead is currently within
  5222. * @param maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  5223. * @returns a matching fragment or null
  5224. */
  5225. function findFragmentByPTS(fragPrevious, fragments, bufferEnd, maxFragLookUpTolerance, nextFragLookupTolerance) {
  5226. if (bufferEnd === void 0) {
  5227. bufferEnd = 0;
  5228. }
  5229. if (maxFragLookUpTolerance === void 0) {
  5230. maxFragLookUpTolerance = 0;
  5231. }
  5232. if (nextFragLookupTolerance === void 0) {
  5233. nextFragLookupTolerance = 0.005;
  5234. }
  5235. var fragNext = null;
  5236. if (fragPrevious) {
  5237. fragNext = fragments[fragPrevious.sn - fragments[0].sn + 1] || null;
  5238. // check for buffer-end rounding error
  5239. var bufferEdgeError = fragPrevious.endDTS - bufferEnd;
  5240. if (bufferEdgeError > 0 && bufferEdgeError < 0.0000015) {
  5241. bufferEnd += 0.0000015;
  5242. }
  5243. } else if (bufferEnd === 0 && fragments[0].start === 0) {
  5244. fragNext = fragments[0];
  5245. }
  5246. // Prefer the next fragment if it's within tolerance
  5247. if (fragNext && ((!fragPrevious || fragPrevious.level === fragNext.level) && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0 || fragmentWithinFastStartSwitch(fragNext, fragPrevious, Math.min(nextFragLookupTolerance, maxFragLookUpTolerance)))) {
  5248. return fragNext;
  5249. }
  5250. // We might be seeking past the tolerance so find the best match
  5251. var foundFragment = BinarySearch.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
  5252. if (foundFragment && (foundFragment !== fragPrevious || !fragNext)) {
  5253. return foundFragment;
  5254. }
  5255. // If no match was found return the next fragment after fragPrevious, or null
  5256. return fragNext;
  5257. }
  5258. function fragmentWithinFastStartSwitch(fragNext, fragPrevious, nextFragLookupTolerance) {
  5259. if (fragPrevious && fragPrevious.start === 0 && fragPrevious.level < fragNext.level && (fragPrevious.endPTS || 0) > 0) {
  5260. var firstDuration = fragPrevious.tagList.reduce(function (duration, tag) {
  5261. if (tag[0] === 'INF') {
  5262. duration += parseFloat(tag[1]);
  5263. }
  5264. return duration;
  5265. }, nextFragLookupTolerance);
  5266. return fragNext.start <= firstDuration;
  5267. }
  5268. return false;
  5269. }
  5270. /**
  5271. * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.
  5272. * @param candidate - The fragment to test
  5273. * @param bufferEnd - The end of the current buffered range the playhead is currently within
  5274. * @param maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous
  5275. * @returns 0 if it matches, 1 if too low, -1 if too high
  5276. */
  5277. function fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, candidate) {
  5278. if (bufferEnd === void 0) {
  5279. bufferEnd = 0;
  5280. }
  5281. if (maxFragLookUpTolerance === void 0) {
  5282. maxFragLookUpTolerance = 0;
  5283. }
  5284. // eagerly accept an accurate match (no tolerance)
  5285. if (candidate.start <= bufferEnd && candidate.start + candidate.duration > bufferEnd) {
  5286. return 0;
  5287. }
  5288. // offset should be within fragment boundary - config.maxFragLookUpTolerance
  5289. // this is to cope with situations like
  5290. // bufferEnd = 9.991
  5291. // frag[Ø] : [0,10]
  5292. // frag[1] : [10,20]
  5293. // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
  5294. // frag start frag start+duration
  5295. // |-----------------------------|
  5296. // <---> <--->
  5297. // ...--------><-----------------------------><---------....
  5298. // previous frag matching fragment next frag
  5299. // return -1 return 0 return 1
  5300. // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
  5301. // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
  5302. var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
  5303. if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
  5304. return 1;
  5305. } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
  5306. // if maxFragLookUpTolerance will have negative value then don't return -1 for first element
  5307. return -1;
  5308. }
  5309. return 0;
  5310. }
  5311. /**
  5312. * The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.
  5313. * This function tests the candidate's program date time values, as represented in Unix time
  5314. * @param candidate - The fragment to test
  5315. * @param pdtBufferEnd - The Unix time representing the end of the current buffered range
  5316. * @param maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous
  5317. * @returns true if contiguous, false otherwise
  5318. */
  5319. function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
  5320. var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000;
  5321. // endProgramDateTime can be null, default to zero
  5322. var endProgramDateTime = candidate.endProgramDateTime || 0;
  5323. return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
  5324. }
  5325. function findFragWithCC(fragments, cc) {
  5326. return BinarySearch.search(fragments, function (candidate) {
  5327. if (candidate.cc < cc) {
  5328. return 1;
  5329. } else if (candidate.cc > cc) {
  5330. return -1;
  5331. } else {
  5332. return 0;
  5333. }
  5334. });
  5335. }
  5336. var NetworkErrorAction = {
  5337. DoNothing: 0,
  5338. SendEndCallback: 1,
  5339. SendAlternateToPenaltyBox: 2,
  5340. RemoveAlternatePermanently: 3,
  5341. InsertDiscontinuity: 4,
  5342. RetryRequest: 5
  5343. };
  5344. var ErrorActionFlags = {
  5345. None: 0,
  5346. MoveAllAlternatesMatchingHost: 1,
  5347. MoveAllAlternatesMatchingHDCP: 2,
  5348. SwitchToSDR: 4
  5349. }; // Reserved for future use
  5350. var ErrorController = /*#__PURE__*/function () {
  5351. function ErrorController(hls) {
  5352. this.hls = void 0;
  5353. this.playlistError = 0;
  5354. this.penalizedRenditions = {};
  5355. this.log = void 0;
  5356. this.warn = void 0;
  5357. this.error = void 0;
  5358. this.hls = hls;
  5359. this.log = logger.log.bind(logger, "[info]:");
  5360. this.warn = logger.warn.bind(logger, "[warning]:");
  5361. this.error = logger.error.bind(logger, "[error]:");
  5362. this.registerListeners();
  5363. }
  5364. var _proto = ErrorController.prototype;
  5365. _proto.registerListeners = function registerListeners() {
  5366. var hls = this.hls;
  5367. hls.on(Events.ERROR, this.onError, this);
  5368. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  5369. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  5370. };
  5371. _proto.unregisterListeners = function unregisterListeners() {
  5372. var hls = this.hls;
  5373. if (!hls) {
  5374. return;
  5375. }
  5376. hls.off(Events.ERROR, this.onError, this);
  5377. hls.off(Events.ERROR, this.onErrorOut, this);
  5378. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  5379. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  5380. };
  5381. _proto.destroy = function destroy() {
  5382. this.unregisterListeners();
  5383. // @ts-ignore
  5384. this.hls = null;
  5385. this.penalizedRenditions = {};
  5386. };
  5387. _proto.startLoad = function startLoad(startPosition) {};
  5388. _proto.stopLoad = function stopLoad() {
  5389. this.playlistError = 0;
  5390. };
  5391. _proto.getVariantLevelIndex = function getVariantLevelIndex(frag) {
  5392. return (frag == null ? void 0 : frag.type) === PlaylistLevelType.MAIN ? frag.level : this.hls.loadLevel;
  5393. };
  5394. _proto.onManifestLoading = function onManifestLoading() {
  5395. this.playlistError = 0;
  5396. this.penalizedRenditions = {};
  5397. };
  5398. _proto.onLevelUpdated = function onLevelUpdated() {
  5399. this.playlistError = 0;
  5400. };
  5401. _proto.onError = function onError(event, data) {
  5402. var _data$frag, _data$level;
  5403. if (data.fatal) {
  5404. return;
  5405. }
  5406. var hls = this.hls;
  5407. var context = data.context;
  5408. switch (data.details) {
  5409. case ErrorDetails.FRAG_LOAD_ERROR:
  5410. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  5411. case ErrorDetails.KEY_LOAD_ERROR:
  5412. case ErrorDetails.KEY_LOAD_TIMEOUT:
  5413. data.errorAction = this.getFragRetryOrSwitchAction(data);
  5414. return;
  5415. case ErrorDetails.FRAG_PARSING_ERROR:
  5416. // ignore empty segment errors marked as gap
  5417. if ((_data$frag = data.frag) != null && _data$frag.gap) {
  5418. data.errorAction = {
  5419. action: NetworkErrorAction.DoNothing,
  5420. flags: ErrorActionFlags.None
  5421. };
  5422. return;
  5423. }
  5424. // falls through
  5425. case ErrorDetails.FRAG_GAP:
  5426. case ErrorDetails.FRAG_DECRYPT_ERROR:
  5427. {
  5428. // Switch level if possible, otherwise allow retry count to reach max error retries
  5429. data.errorAction = this.getFragRetryOrSwitchAction(data);
  5430. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  5431. return;
  5432. }
  5433. case ErrorDetails.LEVEL_EMPTY_ERROR:
  5434. case ErrorDetails.LEVEL_PARSING_ERROR:
  5435. {
  5436. var _data$context, _data$context$levelDe;
  5437. // Only retry when empty and live
  5438. var levelIndex = data.parent === PlaylistLevelType.MAIN ? data.level : hls.loadLevel;
  5439. if (data.details === ErrorDetails.LEVEL_EMPTY_ERROR && !!((_data$context = data.context) != null && (_data$context$levelDe = _data$context.levelDetails) != null && _data$context$levelDe.live)) {
  5440. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, levelIndex);
  5441. } else {
  5442. // Escalate to fatal if not retrying or switching
  5443. data.levelRetry = false;
  5444. data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  5445. }
  5446. }
  5447. return;
  5448. case ErrorDetails.LEVEL_LOAD_ERROR:
  5449. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  5450. if (typeof (context == null ? void 0 : context.level) === 'number') {
  5451. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, context.level);
  5452. }
  5453. return;
  5454. case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
  5455. case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
  5456. case ErrorDetails.SUBTITLE_LOAD_ERROR:
  5457. case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:
  5458. if (context) {
  5459. var level = hls.levels[hls.loadLevel];
  5460. if (level && (context.type === PlaylistContextType.AUDIO_TRACK && level.hasAudioGroup(context.groupId) || context.type === PlaylistContextType.SUBTITLE_TRACK && level.hasSubtitleGroup(context.groupId))) {
  5461. // Perform Pathway switch or Redundant failover if possible for fastest recovery
  5462. // otherwise allow playlist retry count to reach max error retries
  5463. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, hls.loadLevel);
  5464. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  5465. data.errorAction.flags = ErrorActionFlags.MoveAllAlternatesMatchingHost;
  5466. return;
  5467. }
  5468. }
  5469. return;
  5470. case ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:
  5471. {
  5472. var _level = hls.levels[hls.loadLevel];
  5473. var restrictedHdcpLevel = _level == null ? void 0 : _level.attrs['HDCP-LEVEL'];
  5474. if (restrictedHdcpLevel) {
  5475. data.errorAction = {
  5476. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  5477. flags: ErrorActionFlags.MoveAllAlternatesMatchingHDCP,
  5478. hdcpLevel: restrictedHdcpLevel
  5479. };
  5480. } else {
  5481. this.keySystemError(data);
  5482. }
  5483. }
  5484. return;
  5485. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  5486. case ErrorDetails.REMUX_ALLOC_ERROR:
  5487. case ErrorDetails.BUFFER_APPEND_ERROR:
  5488. data.errorAction = this.getLevelSwitchAction(data, (_data$level = data.level) != null ? _data$level : hls.loadLevel);
  5489. return;
  5490. case ErrorDetails.INTERNAL_EXCEPTION:
  5491. case ErrorDetails.BUFFER_APPENDING_ERROR:
  5492. case ErrorDetails.BUFFER_FULL_ERROR:
  5493. case ErrorDetails.LEVEL_SWITCH_ERROR:
  5494. case ErrorDetails.BUFFER_STALLED_ERROR:
  5495. case ErrorDetails.BUFFER_SEEK_OVER_HOLE:
  5496. case ErrorDetails.BUFFER_NUDGE_ON_STALL:
  5497. data.errorAction = {
  5498. action: NetworkErrorAction.DoNothing,
  5499. flags: ErrorActionFlags.None
  5500. };
  5501. return;
  5502. }
  5503. if (data.type === ErrorTypes.KEY_SYSTEM_ERROR) {
  5504. this.keySystemError(data);
  5505. }
  5506. };
  5507. _proto.keySystemError = function keySystemError(data) {
  5508. var levelIndex = this.getVariantLevelIndex(data.frag);
  5509. // Do not retry level. Escalate to fatal if switching levels fails.
  5510. data.levelRetry = false;
  5511. data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  5512. };
  5513. _proto.getPlaylistRetryOrSwitchAction = function getPlaylistRetryOrSwitchAction(data, levelIndex) {
  5514. var hls = this.hls;
  5515. var retryConfig = getRetryConfig(hls.config.playlistLoadPolicy, data);
  5516. var retryCount = this.playlistError++;
  5517. var retry = shouldRetry(retryConfig, retryCount, isTimeoutError(data), data.response);
  5518. if (retry) {
  5519. return {
  5520. action: NetworkErrorAction.RetryRequest,
  5521. flags: ErrorActionFlags.None,
  5522. retryConfig: retryConfig,
  5523. retryCount: retryCount
  5524. };
  5525. }
  5526. var errorAction = this.getLevelSwitchAction(data, levelIndex);
  5527. if (retryConfig) {
  5528. errorAction.retryConfig = retryConfig;
  5529. errorAction.retryCount = retryCount;
  5530. }
  5531. return errorAction;
  5532. };
  5533. _proto.getFragRetryOrSwitchAction = function getFragRetryOrSwitchAction(data) {
  5534. var hls = this.hls;
  5535. // Share fragment error count accross media options (main, audio, subs)
  5536. // This allows for level based rendition switching when media option assets fail
  5537. var variantLevelIndex = this.getVariantLevelIndex(data.frag);
  5538. var level = hls.levels[variantLevelIndex];
  5539. var _hls$config = hls.config,
  5540. fragLoadPolicy = _hls$config.fragLoadPolicy,
  5541. keyLoadPolicy = _hls$config.keyLoadPolicy;
  5542. var retryConfig = getRetryConfig(data.details.startsWith('key') ? keyLoadPolicy : fragLoadPolicy, data);
  5543. var fragmentErrors = hls.levels.reduce(function (acc, level) {
  5544. return acc + level.fragmentError;
  5545. }, 0);
  5546. // Switch levels when out of retried or level index out of bounds
  5547. if (level) {
  5548. if (data.details !== ErrorDetails.FRAG_GAP) {
  5549. level.fragmentError++;
  5550. }
  5551. var retry = shouldRetry(retryConfig, fragmentErrors, isTimeoutError(data), data.response);
  5552. if (retry) {
  5553. return {
  5554. action: NetworkErrorAction.RetryRequest,
  5555. flags: ErrorActionFlags.None,
  5556. retryConfig: retryConfig,
  5557. retryCount: fragmentErrors
  5558. };
  5559. }
  5560. }
  5561. // Reach max retry count, or Missing level reference
  5562. // Switch to valid index
  5563. var errorAction = this.getLevelSwitchAction(data, variantLevelIndex);
  5564. // Add retry details to allow skipping of FRAG_PARSING_ERROR
  5565. if (retryConfig) {
  5566. errorAction.retryConfig = retryConfig;
  5567. errorAction.retryCount = fragmentErrors;
  5568. }
  5569. return errorAction;
  5570. };
  5571. _proto.getLevelSwitchAction = function getLevelSwitchAction(data, levelIndex) {
  5572. var hls = this.hls;
  5573. if (levelIndex === null || levelIndex === undefined) {
  5574. levelIndex = hls.loadLevel;
  5575. }
  5576. var level = this.hls.levels[levelIndex];
  5577. if (level) {
  5578. var _data$frag2, _data$context2;
  5579. var errorDetails = data.details;
  5580. level.loadError++;
  5581. if (errorDetails === ErrorDetails.BUFFER_APPEND_ERROR) {
  5582. level.fragmentError++;
  5583. }
  5584. // Search for next level to retry
  5585. var nextLevel = -1;
  5586. var levels = hls.levels,
  5587. loadLevel = hls.loadLevel,
  5588. minAutoLevel = hls.minAutoLevel,
  5589. maxAutoLevel = hls.maxAutoLevel;
  5590. if (!hls.autoLevelEnabled) {
  5591. hls.loadLevel = -1;
  5592. }
  5593. var fragErrorType = (_data$frag2 = data.frag) == null ? void 0 : _data$frag2.type;
  5594. // Find alternate audio codec if available on audio codec error
  5595. var isAudioCodecError = fragErrorType === PlaylistLevelType.AUDIO && errorDetails === ErrorDetails.FRAG_PARSING_ERROR || data.sourceBufferName === 'audio' && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  5596. var findAudioCodecAlternate = isAudioCodecError && levels.some(function (_ref) {
  5597. var audioCodec = _ref.audioCodec;
  5598. return level.audioCodec !== audioCodec;
  5599. });
  5600. // Find alternate video codec if available on video codec error
  5601. var isVideoCodecError = data.sourceBufferName === 'video' && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  5602. var findVideoCodecAlternate = isVideoCodecError && levels.some(function (_ref2) {
  5603. var codecSet = _ref2.codecSet,
  5604. audioCodec = _ref2.audioCodec;
  5605. return level.codecSet !== codecSet && level.audioCodec === audioCodec;
  5606. });
  5607. var _ref3 = (_data$context2 = data.context) != null ? _data$context2 : {},
  5608. playlistErrorType = _ref3.type,
  5609. playlistErrorGroupId = _ref3.groupId;
  5610. var _loop = function _loop() {
  5611. var candidate = (i + loadLevel) % levels.length;
  5612. if (candidate !== loadLevel && candidate >= minAutoLevel && candidate <= maxAutoLevel && levels[candidate].loadError === 0) {
  5613. var _level$audioGroups, _level$subtitleGroups;
  5614. var levelCandidate = levels[candidate];
  5615. // Skip level switch if GAP tag is found in next level at same position
  5616. if (errorDetails === ErrorDetails.FRAG_GAP && fragErrorType === PlaylistLevelType.MAIN && data.frag) {
  5617. var levelDetails = levels[candidate].details;
  5618. if (levelDetails) {
  5619. var fragCandidate = findFragmentByPTS(data.frag, levelDetails.fragments, data.frag.start);
  5620. if (fragCandidate != null && fragCandidate.gap) {
  5621. return 0; // continue
  5622. }
  5623. }
  5624. } else if (playlistErrorType === PlaylistContextType.AUDIO_TRACK && levelCandidate.hasAudioGroup(playlistErrorGroupId) || playlistErrorType === PlaylistContextType.SUBTITLE_TRACK && levelCandidate.hasSubtitleGroup(playlistErrorGroupId)) {
  5625. // For audio/subs playlist errors find another group ID or fallthrough to redundant fail-over
  5626. return 0; // continue
  5627. } else if (fragErrorType === PlaylistLevelType.AUDIO && (_level$audioGroups = level.audioGroups) != null && _level$audioGroups.some(function (groupId) {
  5628. return levelCandidate.hasAudioGroup(groupId);
  5629. }) || fragErrorType === PlaylistLevelType.SUBTITLE && (_level$subtitleGroups = level.subtitleGroups) != null && _level$subtitleGroups.some(function (groupId) {
  5630. return levelCandidate.hasSubtitleGroup(groupId);
  5631. }) || findAudioCodecAlternate && level.audioCodec === levelCandidate.audioCodec || !findAudioCodecAlternate && level.audioCodec !== levelCandidate.audioCodec || findVideoCodecAlternate && level.codecSet === levelCandidate.codecSet) {
  5632. // For video/audio/subs frag errors find another group ID or fallthrough to redundant fail-over
  5633. return 0; // continue
  5634. }
  5635. nextLevel = candidate;
  5636. return 1; // break
  5637. }
  5638. },
  5639. _ret;
  5640. for (var i = levels.length; i--;) {
  5641. _ret = _loop();
  5642. if (_ret === 0) continue;
  5643. if (_ret === 1) break;
  5644. }
  5645. if (nextLevel > -1 && hls.loadLevel !== nextLevel) {
  5646. data.levelRetry = true;
  5647. this.playlistError = 0;
  5648. return {
  5649. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  5650. flags: ErrorActionFlags.None,
  5651. nextAutoLevel: nextLevel
  5652. };
  5653. }
  5654. }
  5655. // No levels to switch / Manual level selection / Level not found
  5656. // Resolve with Pathway switch, Redundant fail-over, or stay on lowest Level
  5657. return {
  5658. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  5659. flags: ErrorActionFlags.MoveAllAlternatesMatchingHost
  5660. };
  5661. };
  5662. _proto.onErrorOut = function onErrorOut(event, data) {
  5663. var _data$errorAction;
  5664. switch ((_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.action) {
  5665. case NetworkErrorAction.DoNothing:
  5666. break;
  5667. case NetworkErrorAction.SendAlternateToPenaltyBox:
  5668. this.sendAlternateToPenaltyBox(data);
  5669. if (!data.errorAction.resolved && data.details !== ErrorDetails.FRAG_GAP) {
  5670. data.fatal = true;
  5671. } else if (/MediaSource readyState: ended/.test(data.error.message)) {
  5672. this.warn("MediaSource ended after \"" + data.sourceBufferName + "\" sourceBuffer append error. Attempting to recover from media error.");
  5673. this.hls.recoverMediaError();
  5674. }
  5675. break;
  5676. }
  5677. if (data.fatal) {
  5678. this.hls.stopLoad();
  5679. return;
  5680. }
  5681. };
  5682. _proto.sendAlternateToPenaltyBox = function sendAlternateToPenaltyBox(data) {
  5683. var hls = this.hls;
  5684. var errorAction = data.errorAction;
  5685. if (!errorAction) {
  5686. return;
  5687. }
  5688. var flags = errorAction.flags,
  5689. hdcpLevel = errorAction.hdcpLevel,
  5690. nextAutoLevel = errorAction.nextAutoLevel;
  5691. switch (flags) {
  5692. case ErrorActionFlags.None:
  5693. this.switchLevel(data, nextAutoLevel);
  5694. break;
  5695. case ErrorActionFlags.MoveAllAlternatesMatchingHDCP:
  5696. if (hdcpLevel) {
  5697. hls.maxHdcpLevel = HdcpLevels[HdcpLevels.indexOf(hdcpLevel) - 1];
  5698. errorAction.resolved = true;
  5699. }
  5700. this.warn("Restricting playback to HDCP-LEVEL of \"" + hls.maxHdcpLevel + "\" or lower");
  5701. break;
  5702. }
  5703. // If not resolved by previous actions try to switch to next level
  5704. if (!errorAction.resolved) {
  5705. this.switchLevel(data, nextAutoLevel);
  5706. }
  5707. };
  5708. _proto.switchLevel = function switchLevel(data, levelIndex) {
  5709. if (levelIndex !== undefined && data.errorAction) {
  5710. this.warn("switching to level " + levelIndex + " after " + data.details);
  5711. this.hls.nextAutoLevel = levelIndex;
  5712. data.errorAction.resolved = true;
  5713. // Stream controller is responsible for this but won't switch on false start
  5714. this.hls.nextLoadLevel = this.hls.nextAutoLevel;
  5715. }
  5716. };
  5717. return ErrorController;
  5718. }();
  5719. var BasePlaylistController = /*#__PURE__*/function () {
  5720. function BasePlaylistController(hls, logPrefix) {
  5721. this.hls = void 0;
  5722. this.timer = -1;
  5723. this.requestScheduled = -1;
  5724. this.canLoad = false;
  5725. this.log = void 0;
  5726. this.warn = void 0;
  5727. this.log = logger.log.bind(logger, logPrefix + ":");
  5728. this.warn = logger.warn.bind(logger, logPrefix + ":");
  5729. this.hls = hls;
  5730. }
  5731. var _proto = BasePlaylistController.prototype;
  5732. _proto.destroy = function destroy() {
  5733. this.clearTimer();
  5734. // @ts-ignore
  5735. this.hls = this.log = this.warn = null;
  5736. };
  5737. _proto.clearTimer = function clearTimer() {
  5738. if (this.timer !== -1) {
  5739. self.clearTimeout(this.timer);
  5740. this.timer = -1;
  5741. }
  5742. };
  5743. _proto.startLoad = function startLoad() {
  5744. this.canLoad = true;
  5745. this.requestScheduled = -1;
  5746. this.loadPlaylist();
  5747. };
  5748. _proto.stopLoad = function stopLoad() {
  5749. this.canLoad = false;
  5750. this.clearTimer();
  5751. };
  5752. _proto.switchParams = function switchParams(playlistUri, previous, current) {
  5753. var renditionReports = previous == null ? void 0 : previous.renditionReports;
  5754. if (renditionReports) {
  5755. var foundIndex = -1;
  5756. for (var i = 0; i < renditionReports.length; i++) {
  5757. var attr = renditionReports[i];
  5758. var uri = void 0;
  5759. try {
  5760. uri = new self.URL(attr.URI, previous.url).href;
  5761. } catch (error) {
  5762. logger.warn("Could not construct new URL for Rendition Report: " + error);
  5763. uri = attr.URI || '';
  5764. }
  5765. // Use exact match. Otherwise, the last partial match, if any, will be used
  5766. // (Playlist URI includes a query string that the Rendition Report does not)
  5767. if (uri === playlistUri) {
  5768. foundIndex = i;
  5769. break;
  5770. } else if (uri === playlistUri.substring(0, uri.length)) {
  5771. foundIndex = i;
  5772. }
  5773. }
  5774. if (foundIndex !== -1) {
  5775. var _attr = renditionReports[foundIndex];
  5776. var msn = parseInt(_attr['LAST-MSN']) || (previous == null ? void 0 : previous.lastPartSn);
  5777. var part = parseInt(_attr['LAST-PART']) || (previous == null ? void 0 : previous.lastPartIndex);
  5778. if (this.hls.config.lowLatencyMode) {
  5779. var currentGoal = Math.min(previous.age - previous.partTarget, previous.targetduration);
  5780. if (part >= 0 && currentGoal > previous.partTarget) {
  5781. part += 1;
  5782. }
  5783. }
  5784. var skip = current && getSkipValue(current);
  5785. return new HlsUrlParameters(msn, part >= 0 ? part : undefined, skip);
  5786. }
  5787. }
  5788. };
  5789. _proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {
  5790. if (this.requestScheduled === -1) {
  5791. this.requestScheduled = self.performance.now();
  5792. }
  5793. // Loading is handled by the subclasses
  5794. };
  5795. _proto.shouldLoadPlaylist = function shouldLoadPlaylist(playlist) {
  5796. return this.canLoad && !!playlist && !!playlist.url && (!playlist.details || playlist.details.live);
  5797. };
  5798. _proto.shouldReloadPlaylist = function shouldReloadPlaylist(playlist) {
  5799. return this.timer === -1 && this.requestScheduled === -1 && this.shouldLoadPlaylist(playlist);
  5800. };
  5801. _proto.playlistLoaded = function playlistLoaded(index, data, previousDetails) {
  5802. var _this = this;
  5803. var details = data.details,
  5804. stats = data.stats;
  5805. // Set last updated date-time
  5806. var now = self.performance.now();
  5807. var elapsed = stats.loading.first ? Math.max(0, now - stats.loading.first) : 0;
  5808. details.advancedDateTime = Date.now() - elapsed;
  5809. // if current playlist is a live playlist, arm a timer to reload it
  5810. if (details.live || previousDetails != null && previousDetails.live) {
  5811. details.reloaded(previousDetails);
  5812. if (previousDetails) {
  5813. this.log("live playlist " + index + " " + (details.advanced ? 'REFRESHED ' + details.lastPartSn + '-' + details.lastPartIndex : details.updated ? 'UPDATED' : 'MISSED'));
  5814. }
  5815. // Merge live playlists to adjust fragment starts and fill in delta playlist skipped segments
  5816. if (previousDetails && details.fragments.length > 0) {
  5817. mergeDetails(previousDetails, details);
  5818. }
  5819. if (!this.canLoad || !details.live) {
  5820. return;
  5821. }
  5822. var deliveryDirectives;
  5823. var msn = undefined;
  5824. var part = undefined;
  5825. if (details.canBlockReload && details.endSN && details.advanced) {
  5826. // Load level with LL-HLS delivery directives
  5827. var lowLatencyMode = this.hls.config.lowLatencyMode;
  5828. var lastPartSn = details.lastPartSn;
  5829. var endSn = details.endSN;
  5830. var lastPartIndex = details.lastPartIndex;
  5831. var hasParts = lastPartIndex !== -1;
  5832. var lastPart = lastPartSn === endSn;
  5833. // When low latency mode is disabled, we'll skip part requests once the last part index is found
  5834. var nextSnStartIndex = lowLatencyMode ? 0 : lastPartIndex;
  5835. if (hasParts) {
  5836. msn = lastPart ? endSn + 1 : lastPartSn;
  5837. part = lastPart ? nextSnStartIndex : lastPartIndex + 1;
  5838. } else {
  5839. msn = endSn + 1;
  5840. }
  5841. // Low-Latency CDN Tune-in: "age" header and time since load indicates we're behind by more than one part
  5842. // Update directives to obtain the Playlist that has the estimated additional duration of media
  5843. var lastAdvanced = details.age;
  5844. var cdnAge = lastAdvanced + details.ageHeader;
  5845. var currentGoal = Math.min(cdnAge - details.partTarget, details.targetduration * 1.5);
  5846. if (currentGoal > 0) {
  5847. if (previousDetails && currentGoal > previousDetails.tuneInGoal) {
  5848. // If we attempted to get the next or latest playlist update, but currentGoal increased,
  5849. // then we either can't catchup, or the "age" header cannot be trusted.
  5850. this.warn("CDN Tune-in goal increased from: " + previousDetails.tuneInGoal + " to: " + currentGoal + " with playlist age: " + details.age);
  5851. currentGoal = 0;
  5852. } else {
  5853. var segments = Math.floor(currentGoal / details.targetduration);
  5854. msn += segments;
  5855. if (part !== undefined) {
  5856. var parts = Math.round(currentGoal % details.targetduration / details.partTarget);
  5857. part += parts;
  5858. }
  5859. this.log("CDN Tune-in age: " + details.ageHeader + "s last advanced " + lastAdvanced.toFixed(2) + "s goal: " + currentGoal + " skip sn " + segments + " to part " + part);
  5860. }
  5861. details.tuneInGoal = currentGoal;
  5862. }
  5863. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  5864. if (lowLatencyMode || !lastPart) {
  5865. this.loadPlaylist(deliveryDirectives);
  5866. return;
  5867. }
  5868. } else if (details.canBlockReload || details.canSkipUntil) {
  5869. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  5870. }
  5871. var bufferInfo = this.hls.mainForwardBufferInfo;
  5872. var position = bufferInfo ? bufferInfo.end - bufferInfo.len : 0;
  5873. var distanceToLiveEdgeMs = (details.edge - position) * 1000;
  5874. var reloadInterval = computeReloadInterval(details, distanceToLiveEdgeMs);
  5875. if (details.updated && now > this.requestScheduled + reloadInterval) {
  5876. this.requestScheduled = stats.loading.start;
  5877. }
  5878. if (msn !== undefined && details.canBlockReload) {
  5879. this.requestScheduled = stats.loading.first + reloadInterval - (details.partTarget * 1000 || 1000);
  5880. } else if (this.requestScheduled === -1 || this.requestScheduled + reloadInterval < now) {
  5881. this.requestScheduled = now;
  5882. } else if (this.requestScheduled - now <= 0) {
  5883. this.requestScheduled += reloadInterval;
  5884. }
  5885. var estimatedTimeUntilUpdate = this.requestScheduled - now;
  5886. estimatedTimeUntilUpdate = Math.max(0, estimatedTimeUntilUpdate);
  5887. this.log("reload live playlist " + index + " in " + Math.round(estimatedTimeUntilUpdate) + " ms");
  5888. // this.log(
  5889. // `live reload ${details.updated ? 'REFRESHED' : 'MISSED'}
  5890. // reload in ${estimatedTimeUntilUpdate / 1000}
  5891. // round trip ${(stats.loading.end - stats.loading.start) / 1000}
  5892. // diff ${
  5893. // (reloadInterval -
  5894. // (estimatedTimeUntilUpdate +
  5895. // stats.loading.end -
  5896. // stats.loading.start)) /
  5897. // 1000
  5898. // }
  5899. // reload interval ${reloadInterval / 1000}
  5900. // target duration ${details.targetduration}
  5901. // distance to edge ${distanceToLiveEdgeMs / 1000}`
  5902. // );
  5903. this.timer = self.setTimeout(function () {
  5904. return _this.loadPlaylist(deliveryDirectives);
  5905. }, estimatedTimeUntilUpdate);
  5906. } else {
  5907. this.clearTimer();
  5908. }
  5909. };
  5910. _proto.getDeliveryDirectives = function getDeliveryDirectives(details, previousDeliveryDirectives, msn, part) {
  5911. var skip = getSkipValue(details);
  5912. if (previousDeliveryDirectives != null && previousDeliveryDirectives.skip && details.deltaUpdateFailed) {
  5913. msn = previousDeliveryDirectives.msn;
  5914. part = previousDeliveryDirectives.part;
  5915. skip = HlsSkip.No;
  5916. }
  5917. return new HlsUrlParameters(msn, part, skip);
  5918. };
  5919. _proto.checkRetry = function checkRetry(errorEvent) {
  5920. var _this2 = this;
  5921. var errorDetails = errorEvent.details;
  5922. var isTimeout = isTimeoutError(errorEvent);
  5923. var errorAction = errorEvent.errorAction;
  5924. var _ref = errorAction || {},
  5925. action = _ref.action,
  5926. _ref$retryCount = _ref.retryCount,
  5927. retryCount = _ref$retryCount === void 0 ? 0 : _ref$retryCount,
  5928. retryConfig = _ref.retryConfig;
  5929. var retry = !!errorAction && !!retryConfig && (action === NetworkErrorAction.RetryRequest || !errorAction.resolved && action === NetworkErrorAction.SendAlternateToPenaltyBox);
  5930. if (retry) {
  5931. var _errorEvent$context;
  5932. this.requestScheduled = -1;
  5933. if (retryCount >= retryConfig.maxNumRetry) {
  5934. return false;
  5935. }
  5936. if (isTimeout && (_errorEvent$context = errorEvent.context) != null && _errorEvent$context.deliveryDirectives) {
  5937. // The LL-HLS request already timed out so retry immediately
  5938. this.warn("Retrying playlist loading " + (retryCount + 1) + "/" + retryConfig.maxNumRetry + " after \"" + errorDetails + "\" without delivery-directives");
  5939. this.loadPlaylist();
  5940. } else {
  5941. var delay = getRetryDelay(retryConfig, retryCount);
  5942. // Schedule level/track reload
  5943. this.timer = self.setTimeout(function () {
  5944. return _this2.loadPlaylist();
  5945. }, delay);
  5946. this.warn("Retrying playlist loading " + (retryCount + 1) + "/" + retryConfig.maxNumRetry + " after \"" + errorDetails + "\" in " + delay + "ms");
  5947. }
  5948. // `levelRetry = true` used to inform other controllers that a retry is happening
  5949. errorEvent.levelRetry = true;
  5950. errorAction.resolved = true;
  5951. }
  5952. return retry;
  5953. };
  5954. return BasePlaylistController;
  5955. }();
  5956. /*
  5957. * compute an Exponential Weighted moving average
  5958. * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  5959. * - heavily inspired from shaka-player
  5960. */
  5961. var EWMA = /*#__PURE__*/function () {
  5962. // About half of the estimated value will be from the last |halfLife| samples by weight.
  5963. function EWMA(halfLife, estimate, weight) {
  5964. if (estimate === void 0) {
  5965. estimate = 0;
  5966. }
  5967. if (weight === void 0) {
  5968. weight = 0;
  5969. }
  5970. this.halfLife = void 0;
  5971. this.alpha_ = void 0;
  5972. this.estimate_ = void 0;
  5973. this.totalWeight_ = void 0;
  5974. this.halfLife = halfLife;
  5975. // Larger values of alpha expire historical data more slowly.
  5976. this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
  5977. this.estimate_ = estimate;
  5978. this.totalWeight_ = weight;
  5979. }
  5980. var _proto = EWMA.prototype;
  5981. _proto.sample = function sample(weight, value) {
  5982. var adjAlpha = Math.pow(this.alpha_, weight);
  5983. this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
  5984. this.totalWeight_ += weight;
  5985. };
  5986. _proto.getTotalWeight = function getTotalWeight() {
  5987. return this.totalWeight_;
  5988. };
  5989. _proto.getEstimate = function getEstimate() {
  5990. if (this.alpha_) {
  5991. var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
  5992. if (zeroFactor) {
  5993. return this.estimate_ / zeroFactor;
  5994. }
  5995. }
  5996. return this.estimate_;
  5997. };
  5998. return EWMA;
  5999. }();
  6000. /*
  6001. * EWMA Bandwidth Estimator
  6002. * - heavily inspired from shaka-player
  6003. * Tracks bandwidth samples and estimates available bandwidth.
  6004. * Based on the minimum of two exponentially-weighted moving averages with
  6005. * different half-lives.
  6006. */
  6007. var EwmaBandWidthEstimator = /*#__PURE__*/function () {
  6008. function EwmaBandWidthEstimator(slow, fast, defaultEstimate, defaultTTFB) {
  6009. if (defaultTTFB === void 0) {
  6010. defaultTTFB = 100;
  6011. }
  6012. this.defaultEstimate_ = void 0;
  6013. this.minWeight_ = void 0;
  6014. this.minDelayMs_ = void 0;
  6015. this.slow_ = void 0;
  6016. this.fast_ = void 0;
  6017. this.defaultTTFB_ = void 0;
  6018. this.ttfb_ = void 0;
  6019. this.defaultEstimate_ = defaultEstimate;
  6020. this.minWeight_ = 0.001;
  6021. this.minDelayMs_ = 50;
  6022. this.slow_ = new EWMA(slow);
  6023. this.fast_ = new EWMA(fast);
  6024. this.defaultTTFB_ = defaultTTFB;
  6025. this.ttfb_ = new EWMA(slow);
  6026. }
  6027. var _proto = EwmaBandWidthEstimator.prototype;
  6028. _proto.update = function update(slow, fast) {
  6029. var slow_ = this.slow_,
  6030. fast_ = this.fast_,
  6031. ttfb_ = this.ttfb_;
  6032. if (slow_.halfLife !== slow) {
  6033. this.slow_ = new EWMA(slow, slow_.getEstimate(), slow_.getTotalWeight());
  6034. }
  6035. if (fast_.halfLife !== fast) {
  6036. this.fast_ = new EWMA(fast, fast_.getEstimate(), fast_.getTotalWeight());
  6037. }
  6038. if (ttfb_.halfLife !== slow) {
  6039. this.ttfb_ = new EWMA(slow, ttfb_.getEstimate(), ttfb_.getTotalWeight());
  6040. }
  6041. };
  6042. _proto.sample = function sample(durationMs, numBytes) {
  6043. durationMs = Math.max(durationMs, this.minDelayMs_);
  6044. var numBits = 8 * numBytes;
  6045. // weight is duration in seconds
  6046. var durationS = durationMs / 1000;
  6047. // value is bandwidth in bits/s
  6048. var bandwidthInBps = numBits / durationS;
  6049. this.fast_.sample(durationS, bandwidthInBps);
  6050. this.slow_.sample(durationS, bandwidthInBps);
  6051. };
  6052. _proto.sampleTTFB = function sampleTTFB(ttfb) {
  6053. // weight is frequency curve applied to TTFB in seconds
  6054. // (longer times have less weight with expected input under 1 second)
  6055. var seconds = ttfb / 1000;
  6056. var weight = Math.sqrt(2) * Math.exp(-Math.pow(seconds, 2) / 2);
  6057. this.ttfb_.sample(weight, Math.max(ttfb, 5));
  6058. };
  6059. _proto.canEstimate = function canEstimate() {
  6060. return this.fast_.getTotalWeight() >= this.minWeight_;
  6061. };
  6062. _proto.getEstimate = function getEstimate() {
  6063. if (this.canEstimate()) {
  6064. // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));
  6065. // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));
  6066. // Take the minimum of these two estimates. This should have the effect of
  6067. // adapting down quickly, but up more slowly.
  6068. return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
  6069. } else {
  6070. return this.defaultEstimate_;
  6071. }
  6072. };
  6073. _proto.getEstimateTTFB = function getEstimateTTFB() {
  6074. if (this.ttfb_.getTotalWeight() >= this.minWeight_) {
  6075. return this.ttfb_.getEstimate();
  6076. } else {
  6077. return this.defaultTTFB_;
  6078. }
  6079. };
  6080. _proto.destroy = function destroy() {};
  6081. return EwmaBandWidthEstimator;
  6082. }();
  6083. /**
  6084. * @returns Whether we can detect and validate HDR capability within the window context
  6085. */
  6086. function isHdrSupported() {
  6087. if (typeof matchMedia === 'function') {
  6088. var mediaQueryList = matchMedia('(dynamic-range: high)');
  6089. var badQuery = matchMedia('bad query');
  6090. if (mediaQueryList.media !== badQuery.media) {
  6091. return mediaQueryList.matches === true;
  6092. }
  6093. }
  6094. return false;
  6095. }
  6096. /**
  6097. * Sanitizes inputs to return the active video selection options for HDR/SDR.
  6098. * When both inputs are null:
  6099. *
  6100. * `{ preferHDR: false, allowedVideoRanges: [] }`
  6101. *
  6102. * When `currentVideoRange` non-null, maintain the active range:
  6103. *
  6104. * `{ preferHDR: currentVideoRange !== 'SDR', allowedVideoRanges: [currentVideoRange] }`
  6105. *
  6106. * When VideoSelectionOption non-null:
  6107. *
  6108. * - Allow all video ranges if `allowedVideoRanges` unspecified.
  6109. * - If `preferHDR` is non-null use the value to filter `allowedVideoRanges`.
  6110. * - Else check window for HDR support and set `preferHDR` to the result.
  6111. *
  6112. * @param currentVideoRange
  6113. * @param videoPreference
  6114. */
  6115. function getVideoSelectionOptions(currentVideoRange, videoPreference) {
  6116. var preferHDR = false;
  6117. var allowedVideoRanges = [];
  6118. if (currentVideoRange) {
  6119. preferHDR = currentVideoRange !== 'SDR';
  6120. allowedVideoRanges = [currentVideoRange];
  6121. }
  6122. if (videoPreference) {
  6123. allowedVideoRanges = videoPreference.allowedVideoRanges || VideoRangeValues.slice(0);
  6124. preferHDR = videoPreference.preferHDR !== undefined ? videoPreference.preferHDR : isHdrSupported();
  6125. if (preferHDR) {
  6126. allowedVideoRanges = allowedVideoRanges.filter(function (range) {
  6127. return range !== 'SDR';
  6128. });
  6129. } else {
  6130. allowedVideoRanges = ['SDR'];
  6131. }
  6132. }
  6133. return {
  6134. preferHDR: preferHDR,
  6135. allowedVideoRanges: allowedVideoRanges
  6136. };
  6137. }
  6138. function getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference) {
  6139. var codecSets = Object.keys(codecTiers);
  6140. var channelsPreference = audioPreference == null ? void 0 : audioPreference.channels;
  6141. var audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec;
  6142. var preferStereo = channelsPreference && parseInt(channelsPreference) === 2;
  6143. // Use first level set to determine stereo, and minimum resolution and framerate
  6144. var hasStereo = true;
  6145. var hasCurrentVideoRange = false;
  6146. var minHeight = Infinity;
  6147. var minFramerate = Infinity;
  6148. var minBitrate = Infinity;
  6149. var selectedScore = 0;
  6150. var videoRanges = [];
  6151. var _getVideoSelectionOpt = getVideoSelectionOptions(currentVideoRange, videoPreference),
  6152. preferHDR = _getVideoSelectionOpt.preferHDR,
  6153. allowedVideoRanges = _getVideoSelectionOpt.allowedVideoRanges;
  6154. var _loop = function _loop() {
  6155. var tier = codecTiers[codecSets[i]];
  6156. hasStereo = tier.channels[2] > 0;
  6157. minHeight = Math.min(minHeight, tier.minHeight);
  6158. minFramerate = Math.min(minFramerate, tier.minFramerate);
  6159. minBitrate = Math.min(minBitrate, tier.minBitrate);
  6160. var matchingVideoRanges = allowedVideoRanges.filter(function (range) {
  6161. return tier.videoRanges[range] > 0;
  6162. });
  6163. if (matchingVideoRanges.length > 0) {
  6164. hasCurrentVideoRange = true;
  6165. videoRanges = matchingVideoRanges;
  6166. }
  6167. };
  6168. for (var i = codecSets.length; i--;) {
  6169. _loop();
  6170. }
  6171. minHeight = isFiniteNumber(minHeight) ? minHeight : 0;
  6172. minFramerate = isFiniteNumber(minFramerate) ? minFramerate : 0;
  6173. var maxHeight = Math.max(1080, minHeight);
  6174. var maxFramerate = Math.max(30, minFramerate);
  6175. minBitrate = isFiniteNumber(minBitrate) ? minBitrate : currentBw;
  6176. currentBw = Math.max(minBitrate, currentBw);
  6177. // If there are no variants with matching preference, set currentVideoRange to undefined
  6178. if (!hasCurrentVideoRange) {
  6179. currentVideoRange = undefined;
  6180. videoRanges = [];
  6181. }
  6182. var codecSet = codecSets.reduce(function (selected, candidate) {
  6183. // 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
  6184. var candidateTier = codecTiers[candidate];
  6185. if (candidate === selected) {
  6186. return selected;
  6187. }
  6188. if (candidateTier.minBitrate > currentBw) {
  6189. logStartCodecCandidateIgnored(candidate, "min bitrate of " + candidateTier.minBitrate + " > current estimate of " + currentBw);
  6190. return selected;
  6191. }
  6192. if (!candidateTier.hasDefaultAudio) {
  6193. logStartCodecCandidateIgnored(candidate, "no renditions with default or auto-select sound found");
  6194. return selected;
  6195. }
  6196. if (audioCodecPreference && candidate.indexOf(audioCodecPreference.substring(0, 4)) % 5 !== 0) {
  6197. logStartCodecCandidateIgnored(candidate, "audio codec preference \"" + audioCodecPreference + "\" not found");
  6198. return selected;
  6199. }
  6200. if (channelsPreference && !preferStereo) {
  6201. if (!candidateTier.channels[channelsPreference]) {
  6202. logStartCodecCandidateIgnored(candidate, "no renditions with " + channelsPreference + " channel sound found (channels options: " + Object.keys(candidateTier.channels) + ")");
  6203. return selected;
  6204. }
  6205. } else if ((!audioCodecPreference || preferStereo) && hasStereo && candidateTier.channels['2'] === 0) {
  6206. logStartCodecCandidateIgnored(candidate, "no renditions with stereo sound found");
  6207. return selected;
  6208. }
  6209. if (candidateTier.minHeight > maxHeight) {
  6210. logStartCodecCandidateIgnored(candidate, "min resolution of " + candidateTier.minHeight + " > maximum of " + maxHeight);
  6211. return selected;
  6212. }
  6213. if (candidateTier.minFramerate > maxFramerate) {
  6214. logStartCodecCandidateIgnored(candidate, "min framerate of " + candidateTier.minFramerate + " > maximum of " + maxFramerate);
  6215. return selected;
  6216. }
  6217. if (!videoRanges.some(function (range) {
  6218. return candidateTier.videoRanges[range] > 0;
  6219. })) {
  6220. logStartCodecCandidateIgnored(candidate, "no variants with VIDEO-RANGE of " + JSON.stringify(videoRanges) + " found");
  6221. return selected;
  6222. }
  6223. if (candidateTier.maxScore < selectedScore) {
  6224. logStartCodecCandidateIgnored(candidate, "max score of " + candidateTier.maxScore + " < selected max of " + selectedScore);
  6225. return selected;
  6226. }
  6227. // Remove candiates with less preferred codecs or more errors
  6228. if (selected && (codecsSetSelectionPreferenceValue(candidate) >= codecsSetSelectionPreferenceValue(selected) || candidateTier.fragmentError > codecTiers[selected].fragmentError)) {
  6229. return selected;
  6230. }
  6231. selectedScore = candidateTier.maxScore;
  6232. return candidate;
  6233. }, undefined);
  6234. return {
  6235. codecSet: codecSet,
  6236. videoRanges: videoRanges,
  6237. preferHDR: preferHDR,
  6238. minFramerate: minFramerate,
  6239. minBitrate: minBitrate
  6240. };
  6241. }
  6242. function logStartCodecCandidateIgnored(codeSet, reason) {
  6243. logger.log("[abr] start candidates with \"" + codeSet + "\" ignored because " + reason);
  6244. }
  6245. function getAudioTracksByGroup(allAudioTracks) {
  6246. return allAudioTracks.reduce(function (audioTracksByGroup, track) {
  6247. var trackGroup = audioTracksByGroup.groups[track.groupId];
  6248. if (!trackGroup) {
  6249. trackGroup = audioTracksByGroup.groups[track.groupId] = {
  6250. tracks: [],
  6251. channels: {
  6252. 2: 0
  6253. },
  6254. hasDefault: false,
  6255. hasAutoSelect: false
  6256. };
  6257. }
  6258. trackGroup.tracks.push(track);
  6259. var channelsKey = track.channels || '2';
  6260. trackGroup.channels[channelsKey] = (trackGroup.channels[channelsKey] || 0) + 1;
  6261. trackGroup.hasDefault = trackGroup.hasDefault || track.default;
  6262. trackGroup.hasAutoSelect = trackGroup.hasAutoSelect || track.autoselect;
  6263. if (trackGroup.hasDefault) {
  6264. audioTracksByGroup.hasDefaultAudio = true;
  6265. }
  6266. if (trackGroup.hasAutoSelect) {
  6267. audioTracksByGroup.hasAutoSelectAudio = true;
  6268. }
  6269. return audioTracksByGroup;
  6270. }, {
  6271. hasDefaultAudio: false,
  6272. hasAutoSelectAudio: false,
  6273. groups: {}
  6274. });
  6275. }
  6276. function getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel) {
  6277. return levels.slice(minAutoLevel, maxAutoLevel + 1).reduce(function (tiers, level) {
  6278. if (!level.codecSet) {
  6279. return tiers;
  6280. }
  6281. var audioGroups = level.audioGroups;
  6282. var tier = tiers[level.codecSet];
  6283. if (!tier) {
  6284. tiers[level.codecSet] = tier = {
  6285. minBitrate: Infinity,
  6286. minHeight: Infinity,
  6287. minFramerate: Infinity,
  6288. maxScore: 0,
  6289. videoRanges: {
  6290. SDR: 0
  6291. },
  6292. channels: {
  6293. '2': 0
  6294. },
  6295. hasDefaultAudio: !audioGroups,
  6296. fragmentError: 0
  6297. };
  6298. }
  6299. tier.minBitrate = Math.min(tier.minBitrate, level.bitrate);
  6300. var lesserWidthOrHeight = Math.min(level.height, level.width);
  6301. tier.minHeight = Math.min(tier.minHeight, lesserWidthOrHeight);
  6302. tier.minFramerate = Math.min(tier.minFramerate, level.frameRate);
  6303. tier.maxScore = Math.max(tier.maxScore, level.score);
  6304. tier.fragmentError += level.fragmentError;
  6305. tier.videoRanges[level.videoRange] = (tier.videoRanges[level.videoRange] || 0) + 1;
  6306. return tiers;
  6307. }, {});
  6308. }
  6309. var AbrController = /*#__PURE__*/function () {
  6310. function AbrController(_hls) {
  6311. var _this = this;
  6312. this.hls = void 0;
  6313. this.lastLevelLoadSec = 0;
  6314. this.lastLoadedFragLevel = -1;
  6315. this.firstSelection = -1;
  6316. this._nextAutoLevel = -1;
  6317. this.nextAutoLevelKey = '';
  6318. this.audioTracksByGroup = null;
  6319. this.codecTiers = null;
  6320. this.timer = -1;
  6321. this.fragCurrent = null;
  6322. this.partCurrent = null;
  6323. this.bitrateTestDelay = 0;
  6324. this.bwEstimator = void 0;
  6325. /*
  6326. This method monitors the download rate of the current fragment, and will downswitch if that fragment will not load
  6327. quickly enough to prevent underbuffering
  6328. */
  6329. this._abandonRulesCheck = function () {
  6330. var frag = _this.fragCurrent,
  6331. part = _this.partCurrent,
  6332. hls = _this.hls;
  6333. var autoLevelEnabled = hls.autoLevelEnabled,
  6334. media = hls.media;
  6335. if (!frag || !media) {
  6336. return;
  6337. }
  6338. var now = performance.now();
  6339. var stats = part ? part.stats : frag.stats;
  6340. var duration = part ? part.duration : frag.duration;
  6341. var timeLoading = now - stats.loading.start;
  6342. var minAutoLevel = hls.minAutoLevel;
  6343. // If frag loading is aborted, complete, or from lowest level, stop timer and return
  6344. if (stats.aborted || stats.loaded && stats.loaded === stats.total || frag.level <= minAutoLevel) {
  6345. _this.clearTimer();
  6346. // reset forced auto level value so that next level will be selected
  6347. _this._nextAutoLevel = -1;
  6348. return;
  6349. }
  6350. // This check only runs if we're in ABR mode and actually playing
  6351. if (!autoLevelEnabled || media.paused || !media.playbackRate || !media.readyState) {
  6352. return;
  6353. }
  6354. var bufferInfo = hls.mainForwardBufferInfo;
  6355. if (bufferInfo === null) {
  6356. return;
  6357. }
  6358. var ttfbEstimate = _this.bwEstimator.getEstimateTTFB();
  6359. var playbackRate = Math.abs(media.playbackRate);
  6360. // To maintain stable adaptive playback, only begin monitoring frag loading after half or more of its playback duration has passed
  6361. if (timeLoading <= Math.max(ttfbEstimate, 1000 * (duration / (playbackRate * 2)))) {
  6362. return;
  6363. }
  6364. // bufferStarvationDelay is an estimate of the amount time (in seconds) it will take to exhaust the buffer
  6365. var bufferStarvationDelay = bufferInfo.len / playbackRate;
  6366. var ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  6367. var loadedFirstByte = stats.loaded && ttfb > -1;
  6368. var bwEstimate = _this.getBwEstimate();
  6369. var levels = hls.levels;
  6370. var level = levels[frag.level];
  6371. var expectedLen = stats.total || Math.max(stats.loaded, Math.round(duration * level.averageBitrate / 8));
  6372. var timeStreaming = loadedFirstByte ? timeLoading - ttfb : timeLoading;
  6373. if (timeStreaming < 1 && loadedFirstByte) {
  6374. timeStreaming = Math.min(timeLoading, stats.loaded * 8 / bwEstimate);
  6375. }
  6376. var loadRate = loadedFirstByte ? stats.loaded * 1000 / timeStreaming : 0;
  6377. // fragLoadDelay is an estimate of the time (in seconds) it will take to buffer the remainder of the fragment
  6378. var fragLoadedDelay = loadRate ? (expectedLen - stats.loaded) / loadRate : expectedLen * 8 / bwEstimate + ttfbEstimate / 1000;
  6379. // Only downswitch if the time to finish loading the current fragment is greater than the amount of buffer left
  6380. if (fragLoadedDelay <= bufferStarvationDelay) {
  6381. return;
  6382. }
  6383. var bwe = loadRate ? loadRate * 8 : bwEstimate;
  6384. var fragLevelNextLoadedDelay = Number.POSITIVE_INFINITY;
  6385. var nextLoadLevel;
  6386. // Iterate through lower level and try to find the largest one that avoids rebuffering
  6387. for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
  6388. // compute time to load next fragment at lower level
  6389. // 8 = bits per byte (bps/Bps)
  6390. var levelNextBitrate = levels[nextLoadLevel].maxBitrate;
  6391. fragLevelNextLoadedDelay = _this.getTimeToLoadFrag(ttfbEstimate / 1000, bwe, duration * levelNextBitrate, !levels[nextLoadLevel].details);
  6392. if (fragLevelNextLoadedDelay < bufferStarvationDelay) {
  6393. break;
  6394. }
  6395. }
  6396. // Only emergency switch down if it takes less time to load a new fragment at lowest level instead of continuing
  6397. // to load the current one
  6398. if (fragLevelNextLoadedDelay >= fragLoadedDelay) {
  6399. return;
  6400. }
  6401. // if estimated load time of new segment is completely unreasonable, ignore and do not emergency switch down
  6402. if (fragLevelNextLoadedDelay > duration * 10) {
  6403. return;
  6404. }
  6405. hls.nextLoadLevel = hls.nextAutoLevel = nextLoadLevel;
  6406. if (loadedFirstByte) {
  6407. // If there has been loading progress, sample bandwidth using loading time offset by minimum TTFB time
  6408. _this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  6409. } else {
  6410. // If there has been no loading progress, sample TTFB
  6411. _this.bwEstimator.sampleTTFB(timeLoading);
  6412. }
  6413. var nextLoadLevelBitrate = levels[nextLoadLevel].maxBitrate;
  6414. if (_this.getBwEstimate() * _this.hls.config.abrBandWidthUpFactor > nextLoadLevelBitrate) {
  6415. _this.resetEstimator(nextLoadLevelBitrate);
  6416. }
  6417. _this.clearTimer();
  6418. logger.warn("[abr] Fragment " + frag.sn + (part ? ' part ' + part.index : '') + " of level " + frag.level + " is loading too slowly;\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");
  6419. hls.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED, {
  6420. frag: frag,
  6421. part: part,
  6422. stats: stats
  6423. });
  6424. };
  6425. this.hls = _hls;
  6426. this.bwEstimator = this.initEstimator();
  6427. this.registerListeners();
  6428. }
  6429. var _proto = AbrController.prototype;
  6430. _proto.resetEstimator = function resetEstimator(abrEwmaDefaultEstimate) {
  6431. if (abrEwmaDefaultEstimate) {
  6432. logger.log("setting initial bwe to " + abrEwmaDefaultEstimate);
  6433. this.hls.config.abrEwmaDefaultEstimate = abrEwmaDefaultEstimate;
  6434. }
  6435. this.firstSelection = -1;
  6436. this.bwEstimator = this.initEstimator();
  6437. };
  6438. _proto.initEstimator = function initEstimator() {
  6439. var config = this.hls.config;
  6440. return new EwmaBandWidthEstimator(config.abrEwmaSlowVoD, config.abrEwmaFastVoD, config.abrEwmaDefaultEstimate);
  6441. };
  6442. _proto.registerListeners = function registerListeners() {
  6443. var hls = this.hls;
  6444. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  6445. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  6446. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  6447. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  6448. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  6449. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  6450. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  6451. hls.on(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  6452. hls.on(Events.ERROR, this.onError, this);
  6453. };
  6454. _proto.unregisterListeners = function unregisterListeners() {
  6455. var hls = this.hls;
  6456. if (!hls) {
  6457. return;
  6458. }
  6459. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  6460. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  6461. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  6462. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  6463. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  6464. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  6465. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  6466. hls.off(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  6467. hls.off(Events.ERROR, this.onError, this);
  6468. };
  6469. _proto.destroy = function destroy() {
  6470. this.unregisterListeners();
  6471. this.clearTimer();
  6472. // @ts-ignore
  6473. this.hls = this._abandonRulesCheck = null;
  6474. this.fragCurrent = this.partCurrent = null;
  6475. };
  6476. _proto.onManifestLoading = function onManifestLoading(event, data) {
  6477. this.lastLoadedFragLevel = -1;
  6478. this.firstSelection = -1;
  6479. this.lastLevelLoadSec = 0;
  6480. this.fragCurrent = this.partCurrent = null;
  6481. this.onLevelsUpdated();
  6482. this.clearTimer();
  6483. };
  6484. _proto.onLevelsUpdated = function onLevelsUpdated() {
  6485. if (this.lastLoadedFragLevel > -1 && this.fragCurrent) {
  6486. this.lastLoadedFragLevel = this.fragCurrent.level;
  6487. }
  6488. this._nextAutoLevel = -1;
  6489. this.onMaxAutoLevelUpdated();
  6490. this.codecTiers = null;
  6491. this.audioTracksByGroup = null;
  6492. };
  6493. _proto.onMaxAutoLevelUpdated = function onMaxAutoLevelUpdated() {
  6494. this.firstSelection = -1;
  6495. this.nextAutoLevelKey = '';
  6496. };
  6497. _proto.onFragLoading = function onFragLoading(event, data) {
  6498. var frag = data.frag;
  6499. if (this.ignoreFragment(frag)) {
  6500. return;
  6501. }
  6502. if (!frag.bitrateTest) {
  6503. var _data$part;
  6504. this.fragCurrent = frag;
  6505. this.partCurrent = (_data$part = data.part) != null ? _data$part : null;
  6506. }
  6507. this.clearTimer();
  6508. this.timer = self.setInterval(this._abandonRulesCheck, 100);
  6509. };
  6510. _proto.onLevelSwitching = function onLevelSwitching(event, data) {
  6511. this.clearTimer();
  6512. };
  6513. _proto.onError = function onError(event, data) {
  6514. if (data.fatal) {
  6515. return;
  6516. }
  6517. switch (data.details) {
  6518. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  6519. case ErrorDetails.BUFFER_APPEND_ERROR:
  6520. // Reset last loaded level so that a new selection can be made after calling recoverMediaError
  6521. this.lastLoadedFragLevel = -1;
  6522. this.firstSelection = -1;
  6523. break;
  6524. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  6525. {
  6526. var frag = data.frag;
  6527. var fragCurrent = this.fragCurrent,
  6528. part = this.partCurrent;
  6529. if (frag && fragCurrent && frag.sn === fragCurrent.sn && frag.level === fragCurrent.level) {
  6530. var now = performance.now();
  6531. var stats = part ? part.stats : frag.stats;
  6532. var timeLoading = now - stats.loading.start;
  6533. var ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  6534. var loadedFirstByte = stats.loaded && ttfb > -1;
  6535. if (loadedFirstByte) {
  6536. var ttfbEstimate = this.bwEstimator.getEstimateTTFB();
  6537. this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  6538. } else {
  6539. this.bwEstimator.sampleTTFB(timeLoading);
  6540. }
  6541. }
  6542. break;
  6543. }
  6544. }
  6545. };
  6546. _proto.getTimeToLoadFrag = function getTimeToLoadFrag(timeToFirstByteSec, bandwidth, fragSizeBits, isSwitch) {
  6547. var fragLoadSec = timeToFirstByteSec + fragSizeBits / bandwidth;
  6548. var playlistLoadSec = isSwitch ? this.lastLevelLoadSec : 0;
  6549. return fragLoadSec + playlistLoadSec;
  6550. };
  6551. _proto.onLevelLoaded = function onLevelLoaded(event, data) {
  6552. var config = this.hls.config;
  6553. var loading = data.stats.loading;
  6554. var timeLoadingMs = loading.end - loading.start;
  6555. if (isFiniteNumber(timeLoadingMs)) {
  6556. this.lastLevelLoadSec = timeLoadingMs / 1000;
  6557. }
  6558. if (data.details.live) {
  6559. this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive);
  6560. } else {
  6561. this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD);
  6562. }
  6563. };
  6564. _proto.onFragLoaded = function onFragLoaded(event, _ref) {
  6565. var frag = _ref.frag,
  6566. part = _ref.part;
  6567. var stats = part ? part.stats : frag.stats;
  6568. if (frag.type === PlaylistLevelType.MAIN) {
  6569. this.bwEstimator.sampleTTFB(stats.loading.first - stats.loading.start);
  6570. }
  6571. if (this.ignoreFragment(frag)) {
  6572. return;
  6573. }
  6574. // stop monitoring bw once frag loaded
  6575. this.clearTimer();
  6576. // reset forced auto level value so that next level will be selected
  6577. if (frag.level === this._nextAutoLevel) {
  6578. this._nextAutoLevel = -1;
  6579. }
  6580. this.firstSelection = -1;
  6581. // compute level average bitrate
  6582. if (this.hls.config.abrMaxWithRealBitrate) {
  6583. var duration = part ? part.duration : frag.duration;
  6584. var level = this.hls.levels[frag.level];
  6585. var loadedBytes = (level.loaded ? level.loaded.bytes : 0) + stats.loaded;
  6586. var loadedDuration = (level.loaded ? level.loaded.duration : 0) + duration;
  6587. level.loaded = {
  6588. bytes: loadedBytes,
  6589. duration: loadedDuration
  6590. };
  6591. level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
  6592. }
  6593. if (frag.bitrateTest) {
  6594. var fragBufferedData = {
  6595. stats: stats,
  6596. frag: frag,
  6597. part: part,
  6598. id: frag.type
  6599. };
  6600. this.onFragBuffered(Events.FRAG_BUFFERED, fragBufferedData);
  6601. frag.bitrateTest = false;
  6602. } else {
  6603. // store level id after successful fragment load for playback
  6604. this.lastLoadedFragLevel = frag.level;
  6605. }
  6606. };
  6607. _proto.onFragBuffered = function onFragBuffered(event, data) {
  6608. var frag = data.frag,
  6609. part = data.part;
  6610. var stats = part != null && part.stats.loaded ? part.stats : frag.stats;
  6611. if (stats.aborted) {
  6612. return;
  6613. }
  6614. if (this.ignoreFragment(frag)) {
  6615. return;
  6616. }
  6617. // Use the difference between parsing and request instead of buffering and request to compute fragLoadingProcessing;
  6618. // rationale is that buffer appending only happens once media is attached. This can happen when config.startFragPrefetch
  6619. // is used. If we used buffering in that case, our BW estimate sample will be very large.
  6620. var processingMs = stats.parsing.end - stats.loading.start - Math.min(stats.loading.first - stats.loading.start, this.bwEstimator.getEstimateTTFB());
  6621. this.bwEstimator.sample(processingMs, stats.loaded);
  6622. stats.bwEstimate = this.getBwEstimate();
  6623. if (frag.bitrateTest) {
  6624. this.bitrateTestDelay = processingMs / 1000;
  6625. } else {
  6626. this.bitrateTestDelay = 0;
  6627. }
  6628. };
  6629. _proto.ignoreFragment = function ignoreFragment(frag) {
  6630. // Only count non-alt-audio frags which were actually buffered in our BW calculations
  6631. return frag.type !== PlaylistLevelType.MAIN || frag.sn === 'initSegment';
  6632. };
  6633. _proto.clearTimer = function clearTimer() {
  6634. if (this.timer > -1) {
  6635. self.clearInterval(this.timer);
  6636. this.timer = -1;
  6637. }
  6638. };
  6639. _proto.getAutoLevelKey = function getAutoLevelKey() {
  6640. return this.getBwEstimate() + "_" + this.getStarvationDelay().toFixed(2);
  6641. };
  6642. _proto.getNextABRAutoLevel = function getNextABRAutoLevel() {
  6643. var fragCurrent = this.fragCurrent,
  6644. partCurrent = this.partCurrent,
  6645. hls = this.hls;
  6646. var maxAutoLevel = hls.maxAutoLevel,
  6647. config = hls.config,
  6648. minAutoLevel = hls.minAutoLevel;
  6649. var currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  6650. var avgbw = this.getBwEstimate();
  6651. // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.
  6652. var bufferStarvationDelay = this.getStarvationDelay();
  6653. var bwFactor = config.abrBandWidthFactor;
  6654. var bwUpFactor = config.abrBandWidthUpFactor;
  6655. // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all
  6656. if (bufferStarvationDelay) {
  6657. var _bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, 0, bwFactor, bwUpFactor);
  6658. if (_bestLevel >= 0) {
  6659. return _bestLevel;
  6660. }
  6661. }
  6662. // not possible to get rid of rebuffering... try to find level that will guarantee less than maxStarvationDelay of rebuffering
  6663. var maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay;
  6664. if (!bufferStarvationDelay) {
  6665. // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test
  6666. var bitrateTestDelay = this.bitrateTestDelay;
  6667. if (bitrateTestDelay) {
  6668. // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value
  6669. // max video loading delay used in automatic start level selection :
  6670. // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +
  6671. // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )
  6672. // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration
  6673. var maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
  6674. maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
  6675. logger.info("[abr] bitrate test took " + Math.round(1000 * bitrateTestDelay) + "ms, set first fragment max fetchDuration to " + Math.round(1000 * maxStarvationDelay) + " ms");
  6676. // don't use conservative factor on bitrate test
  6677. bwFactor = bwUpFactor = 1;
  6678. }
  6679. }
  6680. var bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor);
  6681. logger.info("[abr] " + (bufferStarvationDelay ? 'rebuffering expected' : 'buffer is empty') + ", optimal quality level " + bestLevel);
  6682. if (bestLevel > -1) {
  6683. return bestLevel;
  6684. }
  6685. // If no matching level found, see if min auto level would be a better option
  6686. var minLevel = hls.levels[minAutoLevel];
  6687. var autoLevel = hls.levels[hls.loadLevel];
  6688. if ((minLevel == null ? void 0 : minLevel.bitrate) < (autoLevel == null ? void 0 : autoLevel.bitrate)) {
  6689. return minAutoLevel;
  6690. }
  6691. // or if bitrate is not lower, continue to use loadLevel
  6692. return hls.loadLevel;
  6693. };
  6694. _proto.getStarvationDelay = function getStarvationDelay() {
  6695. var hls = this.hls;
  6696. var media = hls.media;
  6697. if (!media) {
  6698. return Infinity;
  6699. }
  6700. // playbackRate is the absolute value of the playback rate; if media.playbackRate is 0, we use 1 to load as
  6701. // if we're playing back at the normal rate.
  6702. var playbackRate = media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1.0;
  6703. var bufferInfo = hls.mainForwardBufferInfo;
  6704. return (bufferInfo ? bufferInfo.len : 0) / playbackRate;
  6705. };
  6706. _proto.getBwEstimate = function getBwEstimate() {
  6707. return this.bwEstimator.canEstimate() ? this.bwEstimator.getEstimate() : this.hls.config.abrEwmaDefaultEstimate;
  6708. };
  6709. _proto.findBestLevel = function findBestLevel(currentBw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor) {
  6710. var _level$details,
  6711. _this2 = this;
  6712. var maxFetchDuration = bufferStarvationDelay + maxStarvationDelay;
  6713. var lastLoadedFragLevel = this.lastLoadedFragLevel;
  6714. var selectionBaseLevel = lastLoadedFragLevel === -1 ? this.hls.firstLevel : lastLoadedFragLevel;
  6715. var fragCurrent = this.fragCurrent,
  6716. partCurrent = this.partCurrent;
  6717. var _this$hls = this.hls,
  6718. levels = _this$hls.levels,
  6719. allAudioTracks = _this$hls.allAudioTracks,
  6720. loadLevel = _this$hls.loadLevel,
  6721. config = _this$hls.config;
  6722. if (levels.length === 1) {
  6723. return 0;
  6724. }
  6725. var level = levels[selectionBaseLevel];
  6726. var live = !!(level != null && (_level$details = level.details) != null && _level$details.live);
  6727. var firstSelection = loadLevel === -1 || lastLoadedFragLevel === -1;
  6728. var currentCodecSet;
  6729. var currentVideoRange = 'SDR';
  6730. var currentFrameRate = (level == null ? void 0 : level.frameRate) || 0;
  6731. var audioPreference = config.audioPreference,
  6732. videoPreference = config.videoPreference;
  6733. var audioTracksByGroup = this.audioTracksByGroup || (this.audioTracksByGroup = getAudioTracksByGroup(allAudioTracks));
  6734. if (firstSelection) {
  6735. if (this.firstSelection !== -1) {
  6736. return this.firstSelection;
  6737. }
  6738. var codecTiers = this.codecTiers || (this.codecTiers = getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel));
  6739. var startTier = getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference);
  6740. var codecSet = startTier.codecSet,
  6741. videoRanges = startTier.videoRanges,
  6742. minFramerate = startTier.minFramerate,
  6743. minBitrate = startTier.minBitrate,
  6744. preferHDR = startTier.preferHDR;
  6745. currentCodecSet = codecSet;
  6746. currentVideoRange = preferHDR ? videoRanges[videoRanges.length - 1] : videoRanges[0];
  6747. currentFrameRate = minFramerate;
  6748. currentBw = Math.max(currentBw, minBitrate);
  6749. logger.log("[abr] picked start tier " + JSON.stringify(startTier));
  6750. } else {
  6751. currentCodecSet = level == null ? void 0 : level.codecSet;
  6752. currentVideoRange = level == null ? void 0 : level.videoRange;
  6753. }
  6754. var currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  6755. var ttfbEstimateSec = this.bwEstimator.getEstimateTTFB() / 1000;
  6756. var levelsSkipped = [];
  6757. var _loop = function _loop() {
  6758. var _levelInfo$supportedR;
  6759. var levelInfo = levels[i];
  6760. var upSwitch = i > selectionBaseLevel;
  6761. if (!levelInfo) {
  6762. return 0; // continue
  6763. }
  6764. // skip candidates which change codec-family or video-range,
  6765. // and which decrease or increase frame-rate for up and down-switch respectfully
  6766. if (currentCodecSet && levelInfo.codecSet !== currentCodecSet || currentVideoRange && levelInfo.videoRange !== currentVideoRange || upSwitch && currentFrameRate > levelInfo.frameRate || !upSwitch && currentFrameRate > 0 && currentFrameRate < levelInfo.frameRate || levelInfo.supportedResult && !((_levelInfo$supportedR = levelInfo.supportedResult.decodingInfoResults) != null && _levelInfo$supportedR[0].smooth)) {
  6767. levelsSkipped.push(i);
  6768. return 0; // continue
  6769. }
  6770. var levelDetails = levelInfo.details;
  6771. var avgDuration = (partCurrent ? levelDetails == null ? void 0 : levelDetails.partTarget : levelDetails == null ? void 0 : levelDetails.averagetargetduration) || currentFragDuration;
  6772. var adjustedbw;
  6773. // follow algorithm captured from stagefright :
  6774. // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
  6775. // Pick the highest bandwidth stream below or equal to estimated bandwidth.
  6776. // consider only 80% of the available bandwidth, but if we are switching up,
  6777. // be even more conservative (70%) to avoid overestimating and immediately
  6778. // switching back.
  6779. if (!upSwitch) {
  6780. adjustedbw = bwFactor * currentBw;
  6781. } else {
  6782. adjustedbw = bwUpFactor * currentBw;
  6783. }
  6784. // Use average bitrate when starvation delay (buffer length) is gt or eq two segment durations and rebuffering is not expected (maxStarvationDelay > 0)
  6785. var bitrate = currentFragDuration && bufferStarvationDelay >= currentFragDuration * 2 && maxStarvationDelay === 0 ? levels[i].averageBitrate : levels[i].maxBitrate;
  6786. var fetchDuration = _this2.getTimeToLoadFrag(ttfbEstimateSec, adjustedbw, bitrate * avgDuration, levelDetails === undefined);
  6787. var canSwitchWithinTolerance =
  6788. // if adjusted bw is greater than level bitrate AND
  6789. adjustedbw >= bitrate && (
  6790. // no level change, or new level has no error history
  6791. i === lastLoadedFragLevel || levelInfo.loadError === 0 && levelInfo.fragmentError === 0) && (
  6792. // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
  6793. // 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 ...
  6794. // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1
  6795. fetchDuration <= ttfbEstimateSec || !isFiniteNumber(fetchDuration) || live && !_this2.bitrateTestDelay || fetchDuration < maxFetchDuration);
  6796. if (canSwitchWithinTolerance) {
  6797. var forcedAutoLevel = _this2.forcedAutoLevel;
  6798. if (i !== loadLevel && (forcedAutoLevel === -1 || forcedAutoLevel !== loadLevel)) {
  6799. if (levelsSkipped.length) {
  6800. logger.trace("[abr] Skipped level(s) " + levelsSkipped.join(',') + " of " + maxAutoLevel + " max with CODECS and VIDEO-RANGE:\"" + levels[levelsSkipped[0]].codecs + "\" " + levels[levelsSkipped[0]].videoRange + "; not compatible with \"" + level.codecs + "\" " + currentVideoRange);
  6801. }
  6802. logger.info("[abr] 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:" + currentCodecSet + " videoRange:" + currentVideoRange + " hls.loadLevel:" + loadLevel);
  6803. }
  6804. if (firstSelection) {
  6805. _this2.firstSelection = i;
  6806. }
  6807. // as we are looping from highest to lowest, this will return the best achievable quality level
  6808. return {
  6809. v: i
  6810. };
  6811. }
  6812. },
  6813. _ret;
  6814. for (var i = maxAutoLevel; i >= minAutoLevel; i--) {
  6815. _ret = _loop();
  6816. if (_ret === 0) continue;
  6817. if (_ret) return _ret.v;
  6818. }
  6819. // not enough time budget even with quality level 0 ... rebuffering might happen
  6820. return -1;
  6821. };
  6822. _createClass(AbrController, [{
  6823. key: "firstAutoLevel",
  6824. get: function get() {
  6825. var _this$hls2 = this.hls,
  6826. maxAutoLevel = _this$hls2.maxAutoLevel,
  6827. minAutoLevel = _this$hls2.minAutoLevel;
  6828. var bwEstimate = this.getBwEstimate();
  6829. var maxStartDelay = this.hls.config.maxStarvationDelay;
  6830. var abrAutoLevel = this.findBestLevel(bwEstimate, minAutoLevel, maxAutoLevel, 0, maxStartDelay, 1, 1);
  6831. if (abrAutoLevel > -1) {
  6832. return abrAutoLevel;
  6833. }
  6834. var firstLevel = this.hls.firstLevel;
  6835. var clamped = Math.min(Math.max(firstLevel, minAutoLevel), maxAutoLevel);
  6836. logger.warn("[abr] Could not find best starting auto level. Defaulting to first in playlist " + firstLevel + " clamped to " + clamped);
  6837. return clamped;
  6838. }
  6839. }, {
  6840. key: "forcedAutoLevel",
  6841. get: function get() {
  6842. if (this.nextAutoLevelKey) {
  6843. return -1;
  6844. }
  6845. return this._nextAutoLevel;
  6846. }
  6847. // return next auto level
  6848. }, {
  6849. key: "nextAutoLevel",
  6850. get: function get() {
  6851. var forcedAutoLevel = this.forcedAutoLevel;
  6852. var bwEstimator = this.bwEstimator;
  6853. var useEstimate = bwEstimator.canEstimate();
  6854. var loadedFirstFrag = this.lastLoadedFragLevel > -1;
  6855. // in case next auto level has been forced, and bw not available or not reliable, return forced value
  6856. if (forcedAutoLevel !== -1 && (!useEstimate || !loadedFirstFrag || this.nextAutoLevelKey === this.getAutoLevelKey())) {
  6857. return forcedAutoLevel;
  6858. }
  6859. // compute next level using ABR logic
  6860. var nextABRAutoLevel = useEstimate && loadedFirstFrag ? this.getNextABRAutoLevel() : this.firstAutoLevel;
  6861. // use forced auto level while it hasn't errored more than ABR selection
  6862. if (forcedAutoLevel !== -1) {
  6863. var levels = this.hls.levels;
  6864. if (levels.length > Math.max(forcedAutoLevel, nextABRAutoLevel) && levels[forcedAutoLevel].loadError <= levels[nextABRAutoLevel].loadError) {
  6865. return forcedAutoLevel;
  6866. }
  6867. }
  6868. // save result until state has changed
  6869. this._nextAutoLevel = nextABRAutoLevel;
  6870. this.nextAutoLevelKey = this.getAutoLevelKey();
  6871. return nextABRAutoLevel;
  6872. },
  6873. set: function set(nextLevel) {
  6874. var _this$hls3 = this.hls,
  6875. maxAutoLevel = _this$hls3.maxAutoLevel,
  6876. minAutoLevel = _this$hls3.minAutoLevel;
  6877. var value = Math.min(Math.max(nextLevel, minAutoLevel), maxAutoLevel);
  6878. if (this._nextAutoLevel !== value) {
  6879. this.nextAutoLevelKey = '';
  6880. this._nextAutoLevel = value;
  6881. }
  6882. }
  6883. }]);
  6884. return AbrController;
  6885. }();
  6886. /**
  6887. * Provides methods dealing with buffer length retrieval for example.
  6888. *
  6889. * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.
  6890. *
  6891. * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered
  6892. */
  6893. var noopBuffered = {
  6894. length: 0,
  6895. start: function start() {
  6896. return 0;
  6897. },
  6898. end: function end() {
  6899. return 0;
  6900. }
  6901. };
  6902. var BufferHelper = /*#__PURE__*/function () {
  6903. function BufferHelper() {}
  6904. /**
  6905. * Return true if `media`'s buffered include `position`
  6906. */
  6907. BufferHelper.isBuffered = function isBuffered(media, position) {
  6908. try {
  6909. if (media) {
  6910. var buffered = BufferHelper.getBuffered(media);
  6911. for (var i = 0; i < buffered.length; i++) {
  6912. if (position >= buffered.start(i) && position <= buffered.end(i)) {
  6913. return true;
  6914. }
  6915. }
  6916. }
  6917. } catch (error) {
  6918. // this is to catch
  6919. // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
  6920. // This SourceBuffer has been removed from the parent media source
  6921. }
  6922. return false;
  6923. };
  6924. BufferHelper.bufferInfo = function bufferInfo(media, pos, maxHoleDuration) {
  6925. try {
  6926. if (media) {
  6927. var vbuffered = BufferHelper.getBuffered(media);
  6928. var buffered = [];
  6929. var i;
  6930. for (i = 0; i < vbuffered.length; i++) {
  6931. buffered.push({
  6932. start: vbuffered.start(i),
  6933. end: vbuffered.end(i)
  6934. });
  6935. }
  6936. return this.bufferedInfo(buffered, pos, maxHoleDuration);
  6937. }
  6938. } catch (error) {
  6939. // this is to catch
  6940. // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
  6941. // This SourceBuffer has been removed from the parent media source
  6942. }
  6943. return {
  6944. len: 0,
  6945. start: pos,
  6946. end: pos,
  6947. nextStart: undefined
  6948. };
  6949. };
  6950. BufferHelper.bufferedInfo = function bufferedInfo(buffered, pos, maxHoleDuration) {
  6951. pos = Math.max(0, pos);
  6952. // sort on buffer.start/smaller end (IE does not always return sorted buffered range)
  6953. buffered.sort(function (a, b) {
  6954. var diff = a.start - b.start;
  6955. if (diff) {
  6956. return diff;
  6957. } else {
  6958. return b.end - a.end;
  6959. }
  6960. });
  6961. var buffered2 = [];
  6962. if (maxHoleDuration) {
  6963. // there might be some small holes between buffer time range
  6964. // consider that holes smaller than maxHoleDuration are irrelevant and build another
  6965. // buffer time range representations that discards those holes
  6966. for (var i = 0; i < buffered.length; i++) {
  6967. var buf2len = buffered2.length;
  6968. if (buf2len) {
  6969. var buf2end = buffered2[buf2len - 1].end;
  6970. // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)
  6971. if (buffered[i].start - buf2end < maxHoleDuration) {
  6972. // merge overlapping time ranges
  6973. // update lastRange.end only if smaller than item.end
  6974. // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)
  6975. // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])
  6976. if (buffered[i].end > buf2end) {
  6977. buffered2[buf2len - 1].end = buffered[i].end;
  6978. }
  6979. } else {
  6980. // big hole
  6981. buffered2.push(buffered[i]);
  6982. }
  6983. } else {
  6984. // first value
  6985. buffered2.push(buffered[i]);
  6986. }
  6987. }
  6988. } else {
  6989. buffered2 = buffered;
  6990. }
  6991. var bufferLen = 0;
  6992. // bufferStartNext can possibly be undefined based on the conditional logic below
  6993. var bufferStartNext;
  6994. // bufferStart and bufferEnd are buffer boundaries around current video position
  6995. var bufferStart = pos;
  6996. var bufferEnd = pos;
  6997. for (var _i = 0; _i < buffered2.length; _i++) {
  6998. var start = buffered2[_i].start;
  6999. var end = buffered2[_i].end;
  7000. // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));
  7001. if (pos + maxHoleDuration >= start && pos < end) {
  7002. // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
  7003. bufferStart = start;
  7004. bufferEnd = end;
  7005. bufferLen = bufferEnd - pos;
  7006. } else if (pos + maxHoleDuration < start) {
  7007. bufferStartNext = start;
  7008. break;
  7009. }
  7010. }
  7011. return {
  7012. len: bufferLen,
  7013. start: bufferStart || 0,
  7014. end: bufferEnd || 0,
  7015. nextStart: bufferStartNext
  7016. };
  7017. }
  7018. /**
  7019. * Safe method to get buffered property.
  7020. * SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource
  7021. */;
  7022. BufferHelper.getBuffered = function getBuffered(media) {
  7023. try {
  7024. return media.buffered;
  7025. } catch (e) {
  7026. logger.log('failed to get media.buffered', e);
  7027. return noopBuffered;
  7028. }
  7029. };
  7030. return BufferHelper;
  7031. }();
  7032. var BufferOperationQueue = /*#__PURE__*/function () {
  7033. function BufferOperationQueue(sourceBufferReference) {
  7034. this.buffers = void 0;
  7035. this.queues = {
  7036. video: [],
  7037. audio: [],
  7038. audiovideo: []
  7039. };
  7040. this.buffers = sourceBufferReference;
  7041. }
  7042. var _proto = BufferOperationQueue.prototype;
  7043. _proto.append = function append(operation, type, pending) {
  7044. var queue = this.queues[type];
  7045. queue.push(operation);
  7046. if (queue.length === 1 && !pending) {
  7047. this.executeNext(type);
  7048. }
  7049. };
  7050. _proto.insertAbort = function insertAbort(operation, type) {
  7051. var queue = this.queues[type];
  7052. queue.unshift(operation);
  7053. this.executeNext(type);
  7054. };
  7055. _proto.appendBlocker = function appendBlocker(type) {
  7056. var execute;
  7057. var promise = new Promise(function (resolve) {
  7058. execute = resolve;
  7059. });
  7060. var operation = {
  7061. execute: execute,
  7062. onStart: function onStart() {},
  7063. onComplete: function onComplete() {},
  7064. onError: function onError() {}
  7065. };
  7066. this.append(operation, type);
  7067. return promise;
  7068. };
  7069. _proto.executeNext = function executeNext(type) {
  7070. var queue = this.queues[type];
  7071. if (queue.length) {
  7072. var operation = queue[0];
  7073. try {
  7074. // Operations are expected to result in an 'updateend' event being fired. If not, the queue will lock. Operations
  7075. // which do not end with this event must call _onSBUpdateEnd manually
  7076. operation.execute();
  7077. } catch (error) {
  7078. logger.warn("[buffer-operation-queue]: Exception executing \"" + type + "\" SourceBuffer operation: " + error);
  7079. operation.onError(error);
  7080. // Only shift the current operation off, otherwise the updateend handler will do this for us
  7081. var sb = this.buffers[type];
  7082. if (!(sb != null && sb.updating)) {
  7083. this.shiftAndExecuteNext(type);
  7084. }
  7085. }
  7086. }
  7087. };
  7088. _proto.shiftAndExecuteNext = function shiftAndExecuteNext(type) {
  7089. this.queues[type].shift();
  7090. this.executeNext(type);
  7091. };
  7092. _proto.current = function current(type) {
  7093. return this.queues[type][0];
  7094. };
  7095. return BufferOperationQueue;
  7096. }();
  7097. var VIDEO_CODEC_PROFILE_REPLACE = /(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;
  7098. var BufferController = /*#__PURE__*/function () {
  7099. function BufferController(hls) {
  7100. var _this = this;
  7101. // The level details used to determine duration, target-duration and live
  7102. this.details = null;
  7103. // cache the self generated object url to detect hijack of video tag
  7104. this._objectUrl = null;
  7105. // A queue of buffer operations which require the SourceBuffer to not be updating upon execution
  7106. this.operationQueue = void 0;
  7107. // References to event listeners for each SourceBuffer, so that they can be referenced for event removal
  7108. this.listeners = void 0;
  7109. this.hls = void 0;
  7110. // The number of BUFFER_CODEC events received before any sourceBuffers are created
  7111. this.bufferCodecEventsExpected = 0;
  7112. // The total number of BUFFER_CODEC events received
  7113. this._bufferCodecEventsTotal = 0;
  7114. // A reference to the attached media element
  7115. this.media = null;
  7116. // A reference to the active media source
  7117. this.mediaSource = null;
  7118. // Last MP3 audio chunk appended
  7119. this.lastMpegAudioChunk = null;
  7120. this.appendSource = void 0;
  7121. // counters
  7122. this.appendErrors = {
  7123. audio: 0,
  7124. video: 0,
  7125. audiovideo: 0
  7126. };
  7127. this.tracks = {};
  7128. this.pendingTracks = {};
  7129. this.sourceBuffer = void 0;
  7130. this.log = void 0;
  7131. this.warn = void 0;
  7132. this.error = void 0;
  7133. this._onEndStreaming = function (event) {
  7134. if (!_this.hls) {
  7135. return;
  7136. }
  7137. _this.hls.pauseBuffering();
  7138. };
  7139. this._onStartStreaming = function (event) {
  7140. if (!_this.hls) {
  7141. return;
  7142. }
  7143. _this.hls.resumeBuffering();
  7144. };
  7145. // Keep as arrow functions so that we can directly reference these functions directly as event listeners
  7146. this._onMediaSourceOpen = function () {
  7147. var media = _this.media,
  7148. mediaSource = _this.mediaSource;
  7149. _this.log('Media source opened');
  7150. if (media) {
  7151. media.removeEventListener('emptied', _this._onMediaEmptied);
  7152. _this.updateMediaElementDuration();
  7153. _this.hls.trigger(Events.MEDIA_ATTACHED, {
  7154. media: media,
  7155. mediaSource: mediaSource
  7156. });
  7157. }
  7158. if (mediaSource) {
  7159. // once received, don't listen anymore to sourceopen event
  7160. mediaSource.removeEventListener('sourceopen', _this._onMediaSourceOpen);
  7161. }
  7162. _this.checkPendingTracks();
  7163. };
  7164. this._onMediaSourceClose = function () {
  7165. _this.log('Media source closed');
  7166. };
  7167. this._onMediaSourceEnded = function () {
  7168. _this.log('Media source ended');
  7169. };
  7170. this._onMediaEmptied = function () {
  7171. var mediaSrc = _this.mediaSrc,
  7172. _objectUrl = _this._objectUrl;
  7173. if (mediaSrc !== _objectUrl) {
  7174. logger.error("Media element src was set while attaching MediaSource (" + _objectUrl + " > " + mediaSrc + ")");
  7175. }
  7176. };
  7177. this.hls = hls;
  7178. var logPrefix = '[buffer-controller]';
  7179. this.appendSource = isManagedMediaSource(getMediaSource(hls.config.preferManagedMediaSource));
  7180. this.log = logger.log.bind(logger, logPrefix);
  7181. this.warn = logger.warn.bind(logger, logPrefix);
  7182. this.error = logger.error.bind(logger, logPrefix);
  7183. this._initSourceBuffer();
  7184. this.registerListeners();
  7185. }
  7186. var _proto = BufferController.prototype;
  7187. _proto.hasSourceTypes = function hasSourceTypes() {
  7188. return this.getSourceBufferTypes().length > 0 || Object.keys(this.pendingTracks).length > 0;
  7189. };
  7190. _proto.destroy = function destroy() {
  7191. this.unregisterListeners();
  7192. this.details = null;
  7193. this.lastMpegAudioChunk = null;
  7194. // @ts-ignore
  7195. this.hls = null;
  7196. };
  7197. _proto.registerListeners = function registerListeners() {
  7198. var hls = this.hls;
  7199. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  7200. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  7201. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  7202. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  7203. hls.on(Events.BUFFER_RESET, this.onBufferReset, this);
  7204. hls.on(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  7205. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  7206. hls.on(Events.BUFFER_EOS, this.onBufferEos, this);
  7207. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  7208. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  7209. hls.on(Events.FRAG_PARSED, this.onFragParsed, this);
  7210. hls.on(Events.FRAG_CHANGED, this.onFragChanged, this);
  7211. };
  7212. _proto.unregisterListeners = function unregisterListeners() {
  7213. var hls = this.hls;
  7214. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  7215. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  7216. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  7217. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  7218. hls.off(Events.BUFFER_RESET, this.onBufferReset, this);
  7219. hls.off(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  7220. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  7221. hls.off(Events.BUFFER_EOS, this.onBufferEos, this);
  7222. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  7223. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  7224. hls.off(Events.FRAG_PARSED, this.onFragParsed, this);
  7225. hls.off(Events.FRAG_CHANGED, this.onFragChanged, this);
  7226. };
  7227. _proto._initSourceBuffer = function _initSourceBuffer() {
  7228. this.sourceBuffer = {};
  7229. this.operationQueue = new BufferOperationQueue(this.sourceBuffer);
  7230. this.listeners = {
  7231. audio: [],
  7232. video: [],
  7233. audiovideo: []
  7234. };
  7235. this.appendErrors = {
  7236. audio: 0,
  7237. video: 0,
  7238. audiovideo: 0
  7239. };
  7240. this.lastMpegAudioChunk = null;
  7241. };
  7242. _proto.onManifestLoading = function onManifestLoading() {
  7243. this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = 0;
  7244. this.details = null;
  7245. };
  7246. _proto.onManifestParsed = function onManifestParsed(event, data) {
  7247. // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller
  7248. // sourcebuffers will be created all at once when the expected nb of tracks will be reached
  7249. // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller
  7250. // it will contain the expected nb of source buffers, no need to compute it
  7251. var codecEvents = 2;
  7252. if (data.audio && !data.video || !data.altAudio || !false) {
  7253. codecEvents = 1;
  7254. }
  7255. this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = codecEvents;
  7256. this.log(this.bufferCodecEventsExpected + " bufferCodec event(s) expected");
  7257. };
  7258. _proto.onMediaAttaching = function onMediaAttaching(event, data) {
  7259. var media = this.media = data.media;
  7260. var MediaSource = getMediaSource(this.appendSource);
  7261. if (media && MediaSource) {
  7262. var _ms$constructor;
  7263. var ms = this.mediaSource = new MediaSource();
  7264. this.log("created media source: " + ((_ms$constructor = ms.constructor) == null ? void 0 : _ms$constructor.name));
  7265. // MediaSource listeners are arrow functions with a lexical scope, and do not need to be bound
  7266. ms.addEventListener('sourceopen', this._onMediaSourceOpen);
  7267. ms.addEventListener('sourceended', this._onMediaSourceEnded);
  7268. ms.addEventListener('sourceclose', this._onMediaSourceClose);
  7269. if (this.appendSource) {
  7270. ms.addEventListener('startstreaming', this._onStartStreaming);
  7271. ms.addEventListener('endstreaming', this._onEndStreaming);
  7272. }
  7273. // cache the locally generated object url
  7274. var objectUrl = this._objectUrl = self.URL.createObjectURL(ms);
  7275. // link video and media Source
  7276. if (this.appendSource) {
  7277. try {
  7278. media.removeAttribute('src');
  7279. // ManagedMediaSource will not open without disableRemotePlayback set to false or source alternatives
  7280. var MMS = self.ManagedMediaSource;
  7281. media.disableRemotePlayback = media.disableRemotePlayback || MMS && ms instanceof MMS;
  7282. removeSourceChildren(media);
  7283. addSource(media, objectUrl);
  7284. media.load();
  7285. } catch (error) {
  7286. media.src = objectUrl;
  7287. }
  7288. } else {
  7289. media.src = objectUrl;
  7290. }
  7291. media.addEventListener('emptied', this._onMediaEmptied);
  7292. }
  7293. };
  7294. _proto.onMediaDetaching = function onMediaDetaching() {
  7295. var media = this.media,
  7296. mediaSource = this.mediaSource,
  7297. _objectUrl = this._objectUrl;
  7298. if (mediaSource) {
  7299. this.log('media source detaching');
  7300. if (mediaSource.readyState === 'open') {
  7301. try {
  7302. // endOfStream could trigger exception if any sourcebuffer is in updating state
  7303. // we don't really care about checking sourcebuffer state here,
  7304. // as we are anyway detaching the MediaSource
  7305. // let's just avoid this exception to propagate
  7306. mediaSource.endOfStream();
  7307. } catch (err) {
  7308. this.warn("onMediaDetaching: " + err.message + " while calling endOfStream");
  7309. }
  7310. }
  7311. // Clean up the SourceBuffers by invoking onBufferReset
  7312. this.onBufferReset();
  7313. mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);
  7314. mediaSource.removeEventListener('sourceended', this._onMediaSourceEnded);
  7315. mediaSource.removeEventListener('sourceclose', this._onMediaSourceClose);
  7316. if (this.appendSource) {
  7317. mediaSource.removeEventListener('startstreaming', this._onStartStreaming);
  7318. mediaSource.removeEventListener('endstreaming', this._onEndStreaming);
  7319. }
  7320. // Detach properly the MediaSource from the HTMLMediaElement as
  7321. // suggested in https://github.com/w3c/media-source/issues/53.
  7322. if (media) {
  7323. media.removeEventListener('emptied', this._onMediaEmptied);
  7324. if (_objectUrl) {
  7325. self.URL.revokeObjectURL(_objectUrl);
  7326. }
  7327. // clean up video tag src only if it's our own url. some external libraries might
  7328. // hijack the video tag and change its 'src' without destroying the Hls instance first
  7329. if (this.mediaSrc === _objectUrl) {
  7330. media.removeAttribute('src');
  7331. if (this.appendSource) {
  7332. removeSourceChildren(media);
  7333. }
  7334. media.load();
  7335. } else {
  7336. this.warn('media|source.src was changed by a third party - skip cleanup');
  7337. }
  7338. }
  7339. this.mediaSource = null;
  7340. this.media = null;
  7341. this._objectUrl = null;
  7342. this.bufferCodecEventsExpected = this._bufferCodecEventsTotal;
  7343. this.pendingTracks = {};
  7344. this.tracks = {};
  7345. }
  7346. this.hls.trigger(Events.MEDIA_DETACHED, undefined);
  7347. };
  7348. _proto.onBufferReset = function onBufferReset() {
  7349. var _this2 = this;
  7350. this.getSourceBufferTypes().forEach(function (type) {
  7351. _this2.resetBuffer(type);
  7352. });
  7353. this._initSourceBuffer();
  7354. };
  7355. _proto.resetBuffer = function resetBuffer(type) {
  7356. var sb = this.sourceBuffer[type];
  7357. try {
  7358. if (sb) {
  7359. var _this$mediaSource;
  7360. this.removeBufferListeners(type);
  7361. // Synchronously remove the SB from the map before the next call in order to prevent an async function from
  7362. // accessing it
  7363. this.sourceBuffer[type] = undefined;
  7364. if ((_this$mediaSource = this.mediaSource) != null && _this$mediaSource.sourceBuffers.length) {
  7365. this.mediaSource.removeSourceBuffer(sb);
  7366. }
  7367. }
  7368. } catch (err) {
  7369. this.warn("onBufferReset " + type, err);
  7370. }
  7371. };
  7372. _proto.onBufferCodecs = function onBufferCodecs(event, data) {
  7373. var _this3 = this;
  7374. var sourceBufferCount = this.getSourceBufferTypes().length;
  7375. var trackNames = Object.keys(data);
  7376. trackNames.forEach(function (trackName) {
  7377. if (sourceBufferCount) {
  7378. // check if SourceBuffer codec needs to change
  7379. var track = _this3.tracks[trackName];
  7380. if (track && typeof track.buffer.changeType === 'function') {
  7381. var _trackCodec;
  7382. var _data$trackName = data[trackName],
  7383. id = _data$trackName.id,
  7384. codec = _data$trackName.codec,
  7385. levelCodec = _data$trackName.levelCodec,
  7386. container = _data$trackName.container,
  7387. metadata = _data$trackName.metadata;
  7388. var currentCodecFull = pickMostCompleteCodecName(track.codec, track.levelCodec);
  7389. var currentCodec = currentCodecFull == null ? void 0 : currentCodecFull.replace(VIDEO_CODEC_PROFILE_REPLACE, '$1');
  7390. var trackCodec = pickMostCompleteCodecName(codec, levelCodec);
  7391. var nextCodec = (_trackCodec = trackCodec) == null ? void 0 : _trackCodec.replace(VIDEO_CODEC_PROFILE_REPLACE, '$1');
  7392. if (trackCodec && currentCodec !== nextCodec) {
  7393. if (trackName.slice(0, 5) === 'audio') {
  7394. trackCodec = getCodecCompatibleName(trackCodec, _this3.appendSource);
  7395. }
  7396. var mimeType = container + ";codecs=" + trackCodec;
  7397. _this3.appendChangeType(trackName, mimeType);
  7398. _this3.log("switching codec " + currentCodecFull + " to " + trackCodec);
  7399. _this3.tracks[trackName] = {
  7400. buffer: track.buffer,
  7401. codec: codec,
  7402. container: container,
  7403. levelCodec: levelCodec,
  7404. metadata: metadata,
  7405. id: id
  7406. };
  7407. }
  7408. }
  7409. } else {
  7410. // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks
  7411. _this3.pendingTracks[trackName] = data[trackName];
  7412. }
  7413. });
  7414. // if sourcebuffers already created, do nothing ...
  7415. if (sourceBufferCount) {
  7416. return;
  7417. }
  7418. var bufferCodecEventsExpected = Math.max(this.bufferCodecEventsExpected - 1, 0);
  7419. if (this.bufferCodecEventsExpected !== bufferCodecEventsExpected) {
  7420. this.log(bufferCodecEventsExpected + " bufferCodec event(s) expected " + trackNames.join(','));
  7421. this.bufferCodecEventsExpected = bufferCodecEventsExpected;
  7422. }
  7423. if (this.mediaSource && this.mediaSource.readyState === 'open') {
  7424. this.checkPendingTracks();
  7425. }
  7426. };
  7427. _proto.appendChangeType = function appendChangeType(type, mimeType) {
  7428. var _this4 = this;
  7429. var operationQueue = this.operationQueue;
  7430. var operation = {
  7431. execute: function execute() {
  7432. var sb = _this4.sourceBuffer[type];
  7433. if (sb) {
  7434. _this4.log("changing " + type + " sourceBuffer type to " + mimeType);
  7435. sb.changeType(mimeType);
  7436. }
  7437. operationQueue.shiftAndExecuteNext(type);
  7438. },
  7439. onStart: function onStart() {},
  7440. onComplete: function onComplete() {},
  7441. onError: function onError(error) {
  7442. _this4.warn("Failed to change " + type + " SourceBuffer type", error);
  7443. }
  7444. };
  7445. operationQueue.append(operation, type, !!this.pendingTracks[type]);
  7446. };
  7447. _proto.onBufferAppending = function onBufferAppending(event, eventData) {
  7448. var _this5 = this;
  7449. var hls = this.hls,
  7450. operationQueue = this.operationQueue,
  7451. tracks = this.tracks;
  7452. var data = eventData.data,
  7453. type = eventData.type,
  7454. frag = eventData.frag,
  7455. part = eventData.part,
  7456. chunkMeta = eventData.chunkMeta;
  7457. var chunkStats = chunkMeta.buffering[type];
  7458. var bufferAppendingStart = self.performance.now();
  7459. chunkStats.start = bufferAppendingStart;
  7460. var fragBuffering = frag.stats.buffering;
  7461. var partBuffering = part ? part.stats.buffering : null;
  7462. if (fragBuffering.start === 0) {
  7463. fragBuffering.start = bufferAppendingStart;
  7464. }
  7465. if (partBuffering && partBuffering.start === 0) {
  7466. partBuffering.start = bufferAppendingStart;
  7467. }
  7468. // TODO: Only update timestampOffset when audio/mpeg fragment or part is not contiguous with previously appended
  7469. // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)
  7470. // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`
  7471. // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos).
  7472. // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486
  7473. var audioTrack = tracks.audio;
  7474. var checkTimestampOffset = false;
  7475. if (type === 'audio' && (audioTrack == null ? void 0 : audioTrack.container) === 'audio/mpeg') {
  7476. checkTimestampOffset = !this.lastMpegAudioChunk || chunkMeta.id === 1 || this.lastMpegAudioChunk.sn !== chunkMeta.sn;
  7477. this.lastMpegAudioChunk = chunkMeta;
  7478. }
  7479. var fragStart = frag.start;
  7480. var operation = {
  7481. execute: function execute() {
  7482. chunkStats.executeStart = self.performance.now();
  7483. if (checkTimestampOffset) {
  7484. var sb = _this5.sourceBuffer[type];
  7485. if (sb) {
  7486. var delta = fragStart - sb.timestampOffset;
  7487. if (Math.abs(delta) >= 0.1) {
  7488. _this5.log("Updating audio SourceBuffer timestampOffset to " + fragStart + " (delta: " + delta + ") sn: " + frag.sn + ")");
  7489. sb.timestampOffset = fragStart;
  7490. }
  7491. }
  7492. }
  7493. _this5.appendExecutor(data, type);
  7494. },
  7495. onStart: function onStart() {
  7496. // logger.debug(`[buffer-controller]: ${type} SourceBuffer updatestart`);
  7497. },
  7498. onComplete: function onComplete() {
  7499. // logger.debug(`[buffer-controller]: ${type} SourceBuffer updateend`);
  7500. var end = self.performance.now();
  7501. chunkStats.executeEnd = chunkStats.end = end;
  7502. if (fragBuffering.first === 0) {
  7503. fragBuffering.first = end;
  7504. }
  7505. if (partBuffering && partBuffering.first === 0) {
  7506. partBuffering.first = end;
  7507. }
  7508. var sourceBuffer = _this5.sourceBuffer;
  7509. var timeRanges = {};
  7510. for (var _type in sourceBuffer) {
  7511. timeRanges[_type] = BufferHelper.getBuffered(sourceBuffer[_type]);
  7512. }
  7513. _this5.appendErrors[type] = 0;
  7514. if (type === 'audio' || type === 'video') {
  7515. _this5.appendErrors.audiovideo = 0;
  7516. } else {
  7517. _this5.appendErrors.audio = 0;
  7518. _this5.appendErrors.video = 0;
  7519. }
  7520. _this5.hls.trigger(Events.BUFFER_APPENDED, {
  7521. type: type,
  7522. frag: frag,
  7523. part: part,
  7524. chunkMeta: chunkMeta,
  7525. parent: frag.type,
  7526. timeRanges: timeRanges
  7527. });
  7528. },
  7529. onError: function onError(error) {
  7530. // in case any error occured while appending, put back segment in segments table
  7531. var event = {
  7532. type: ErrorTypes.MEDIA_ERROR,
  7533. parent: frag.type,
  7534. details: ErrorDetails.BUFFER_APPEND_ERROR,
  7535. sourceBufferName: type,
  7536. frag: frag,
  7537. part: part,
  7538. chunkMeta: chunkMeta,
  7539. error: error,
  7540. err: error,
  7541. fatal: false
  7542. };
  7543. if (error.code === DOMException.QUOTA_EXCEEDED_ERR) {
  7544. // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
  7545. // let's stop appending any segments, and report BUFFER_FULL_ERROR error
  7546. event.details = ErrorDetails.BUFFER_FULL_ERROR;
  7547. } else {
  7548. var appendErrorCount = ++_this5.appendErrors[type];
  7549. event.details = ErrorDetails.BUFFER_APPEND_ERROR;
  7550. /* with UHD content, we could get loop of quota exceeded error until
  7551. browser is able to evict some data from sourcebuffer. Retrying can help recover.
  7552. */
  7553. _this5.warn("Failed " + appendErrorCount + "/" + hls.config.appendErrorMaxRetry + " times to append segment in \"" + type + "\" sourceBuffer");
  7554. if (appendErrorCount >= hls.config.appendErrorMaxRetry) {
  7555. event.fatal = true;
  7556. }
  7557. }
  7558. hls.trigger(Events.ERROR, event);
  7559. }
  7560. };
  7561. operationQueue.append(operation, type, !!this.pendingTracks[type]);
  7562. };
  7563. _proto.onBufferFlushing = function onBufferFlushing(event, data) {
  7564. var _this6 = this;
  7565. var operationQueue = this.operationQueue;
  7566. var flushOperation = function flushOperation(type) {
  7567. return {
  7568. execute: _this6.removeExecutor.bind(_this6, type, data.startOffset, data.endOffset),
  7569. onStart: function onStart() {
  7570. // logger.debug(`[buffer-controller]: Started flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
  7571. },
  7572. onComplete: function onComplete() {
  7573. // logger.debug(`[buffer-controller]: Finished flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
  7574. _this6.hls.trigger(Events.BUFFER_FLUSHED, {
  7575. type: type
  7576. });
  7577. },
  7578. onError: function onError(error) {
  7579. _this6.warn("Failed to remove from " + type + " SourceBuffer", error);
  7580. }
  7581. };
  7582. };
  7583. if (data.type) {
  7584. operationQueue.append(flushOperation(data.type), data.type);
  7585. } else {
  7586. this.getSourceBufferTypes().forEach(function (type) {
  7587. operationQueue.append(flushOperation(type), type);
  7588. });
  7589. }
  7590. };
  7591. _proto.onFragParsed = function onFragParsed(event, data) {
  7592. var _this7 = this;
  7593. var frag = data.frag,
  7594. part = data.part;
  7595. var buffersAppendedTo = [];
  7596. var elementaryStreams = part ? part.elementaryStreams : frag.elementaryStreams;
  7597. if (elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO]) {
  7598. buffersAppendedTo.push('audiovideo');
  7599. } else {
  7600. if (elementaryStreams[ElementaryStreamTypes.AUDIO]) {
  7601. buffersAppendedTo.push('audio');
  7602. }
  7603. if (elementaryStreams[ElementaryStreamTypes.VIDEO]) {
  7604. buffersAppendedTo.push('video');
  7605. }
  7606. }
  7607. var onUnblocked = function onUnblocked() {
  7608. var now = self.performance.now();
  7609. frag.stats.buffering.end = now;
  7610. if (part) {
  7611. part.stats.buffering.end = now;
  7612. }
  7613. var stats = part ? part.stats : frag.stats;
  7614. _this7.hls.trigger(Events.FRAG_BUFFERED, {
  7615. frag: frag,
  7616. part: part,
  7617. stats: stats,
  7618. id: frag.type
  7619. });
  7620. };
  7621. if (buffersAppendedTo.length === 0) {
  7622. this.warn("Fragments must have at least one ElementaryStreamType set. type: " + frag.type + " level: " + frag.level + " sn: " + frag.sn);
  7623. }
  7624. this.blockBuffers(onUnblocked, buffersAppendedTo);
  7625. };
  7626. _proto.onFragChanged = function onFragChanged(event, data) {
  7627. this.trimBuffers();
  7628. }
  7629. // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()
  7630. // an undefined data.type will mark all buffers as EOS.
  7631. ;
  7632. _proto.onBufferEos = function onBufferEos(event, data) {
  7633. var _this8 = this;
  7634. var ended = this.getSourceBufferTypes().reduce(function (acc, type) {
  7635. var sb = _this8.sourceBuffer[type];
  7636. if (sb && (!data.type || data.type === type)) {
  7637. sb.ending = true;
  7638. if (!sb.ended) {
  7639. sb.ended = true;
  7640. _this8.log(type + " sourceBuffer now EOS");
  7641. }
  7642. }
  7643. return acc && !!(!sb || sb.ended);
  7644. }, true);
  7645. if (ended) {
  7646. this.log("Queueing mediaSource.endOfStream()");
  7647. this.blockBuffers(function () {
  7648. _this8.getSourceBufferTypes().forEach(function (type) {
  7649. var sb = _this8.sourceBuffer[type];
  7650. if (sb) {
  7651. sb.ending = false;
  7652. }
  7653. });
  7654. var mediaSource = _this8.mediaSource;
  7655. if (!mediaSource || mediaSource.readyState !== 'open') {
  7656. if (mediaSource) {
  7657. _this8.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: " + mediaSource.readyState);
  7658. }
  7659. return;
  7660. }
  7661. _this8.log("Calling mediaSource.endOfStream()");
  7662. // Allow this to throw and be caught by the enqueueing function
  7663. mediaSource.endOfStream();
  7664. });
  7665. }
  7666. };
  7667. _proto.onLevelUpdated = function onLevelUpdated(event, _ref) {
  7668. var details = _ref.details;
  7669. if (!details.fragments.length) {
  7670. return;
  7671. }
  7672. this.details = details;
  7673. if (this.getSourceBufferTypes().length) {
  7674. this.blockBuffers(this.updateMediaElementDuration.bind(this));
  7675. } else {
  7676. this.updateMediaElementDuration();
  7677. }
  7678. };
  7679. _proto.trimBuffers = function trimBuffers() {
  7680. var hls = this.hls,
  7681. details = this.details,
  7682. media = this.media;
  7683. if (!media || details === null) {
  7684. return;
  7685. }
  7686. var sourceBufferTypes = this.getSourceBufferTypes();
  7687. if (!sourceBufferTypes.length) {
  7688. return;
  7689. }
  7690. var config = hls.config;
  7691. var currentTime = media.currentTime;
  7692. var targetDuration = details.levelTargetDuration;
  7693. // Support for deprecated liveBackBufferLength
  7694. var backBufferLength = details.live && config.liveBackBufferLength !== null ? config.liveBackBufferLength : config.backBufferLength;
  7695. if (isFiniteNumber(backBufferLength) && backBufferLength > 0) {
  7696. var maxBackBufferLength = Math.max(backBufferLength, targetDuration);
  7697. var targetBackBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration - maxBackBufferLength;
  7698. this.flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition);
  7699. }
  7700. if (isFiniteNumber(config.frontBufferFlushThreshold) && config.frontBufferFlushThreshold > 0) {
  7701. var frontBufferLength = Math.max(config.maxBufferLength, config.frontBufferFlushThreshold);
  7702. var maxFrontBufferLength = Math.max(frontBufferLength, targetDuration);
  7703. var targetFrontBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration + maxFrontBufferLength;
  7704. this.flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition);
  7705. }
  7706. };
  7707. _proto.flushBackBuffer = function flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition) {
  7708. var _this9 = this;
  7709. var details = this.details,
  7710. sourceBuffer = this.sourceBuffer;
  7711. var sourceBufferTypes = this.getSourceBufferTypes();
  7712. sourceBufferTypes.forEach(function (type) {
  7713. var sb = sourceBuffer[type];
  7714. if (sb) {
  7715. var buffered = BufferHelper.getBuffered(sb);
  7716. // when target buffer start exceeds actual buffer start
  7717. if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
  7718. _this9.hls.trigger(Events.BACK_BUFFER_REACHED, {
  7719. bufferEnd: targetBackBufferPosition
  7720. });
  7721. // Support for deprecated event:
  7722. if (details != null && details.live) {
  7723. _this9.hls.trigger(Events.LIVE_BACK_BUFFER_REACHED, {
  7724. bufferEnd: targetBackBufferPosition
  7725. });
  7726. } else if (sb.ended && buffered.end(buffered.length - 1) - currentTime < targetDuration * 2) {
  7727. _this9.log("Cannot flush " + type + " back buffer while SourceBuffer is in ended state");
  7728. return;
  7729. }
  7730. _this9.hls.trigger(Events.BUFFER_FLUSHING, {
  7731. startOffset: 0,
  7732. endOffset: targetBackBufferPosition,
  7733. type: type
  7734. });
  7735. }
  7736. }
  7737. });
  7738. };
  7739. _proto.flushFrontBuffer = function flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition) {
  7740. var _this10 = this;
  7741. var sourceBuffer = this.sourceBuffer;
  7742. var sourceBufferTypes = this.getSourceBufferTypes();
  7743. sourceBufferTypes.forEach(function (type) {
  7744. var sb = sourceBuffer[type];
  7745. if (sb) {
  7746. var buffered = BufferHelper.getBuffered(sb);
  7747. var numBufferedRanges = buffered.length;
  7748. // The buffer is either empty or contiguous
  7749. if (numBufferedRanges < 2) {
  7750. return;
  7751. }
  7752. var bufferStart = buffered.start(numBufferedRanges - 1);
  7753. var bufferEnd = buffered.end(numBufferedRanges - 1);
  7754. // No flush if we can tolerate the current buffer length or the current buffer range we would flush is contiguous with current position
  7755. if (targetFrontBufferPosition > bufferStart || currentTime >= bufferStart && currentTime <= bufferEnd) {
  7756. return;
  7757. } else if (sb.ended && currentTime - bufferEnd < 2 * targetDuration) {
  7758. _this10.log("Cannot flush " + type + " front buffer while SourceBuffer is in ended state");
  7759. return;
  7760. }
  7761. _this10.hls.trigger(Events.BUFFER_FLUSHING, {
  7762. startOffset: bufferStart,
  7763. endOffset: Infinity,
  7764. type: type
  7765. });
  7766. }
  7767. });
  7768. }
  7769. /**
  7770. * Update Media Source duration to current level duration or override to Infinity if configuration parameter
  7771. * 'liveDurationInfinity` is set to `true`
  7772. * More details: https://github.com/video-dev/hls.js/issues/355
  7773. */;
  7774. _proto.updateMediaElementDuration = function updateMediaElementDuration() {
  7775. if (!this.details || !this.media || !this.mediaSource || this.mediaSource.readyState !== 'open') {
  7776. return;
  7777. }
  7778. var details = this.details,
  7779. hls = this.hls,
  7780. media = this.media,
  7781. mediaSource = this.mediaSource;
  7782. var levelDuration = details.fragments[0].start + details.totalduration;
  7783. var mediaDuration = media.duration;
  7784. var msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : 0;
  7785. if (details.live && hls.config.liveDurationInfinity) {
  7786. // Override duration to Infinity
  7787. mediaSource.duration = Infinity;
  7788. this.updateSeekableRange(details);
  7789. } else if (levelDuration > msDuration && levelDuration > mediaDuration || !isFiniteNumber(mediaDuration)) {
  7790. // levelDuration was the last value we set.
  7791. // not using mediaSource.duration as the browser may tweak this value
  7792. // only update Media Source duration if its value increase, this is to avoid
  7793. // flushing already buffered portion when switching between quality level
  7794. this.log("Updating Media Source duration to " + levelDuration.toFixed(3));
  7795. mediaSource.duration = levelDuration;
  7796. }
  7797. };
  7798. _proto.updateSeekableRange = function updateSeekableRange(levelDetails) {
  7799. var mediaSource = this.mediaSource;
  7800. var fragments = levelDetails.fragments;
  7801. var len = fragments.length;
  7802. if (len && levelDetails.live && mediaSource != null && mediaSource.setLiveSeekableRange) {
  7803. var start = Math.max(0, fragments[0].start);
  7804. var end = Math.max(start, start + levelDetails.totalduration);
  7805. this.log("Media Source duration is set to " + mediaSource.duration + ". Setting seekable range to " + start + "-" + end + ".");
  7806. mediaSource.setLiveSeekableRange(start, end);
  7807. }
  7808. };
  7809. _proto.checkPendingTracks = function checkPendingTracks() {
  7810. var bufferCodecEventsExpected = this.bufferCodecEventsExpected,
  7811. operationQueue = this.operationQueue,
  7812. pendingTracks = this.pendingTracks;
  7813. // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.
  7814. // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after
  7815. // data has been appended to existing ones.
  7816. // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.
  7817. var pendingTracksCount = Object.keys(pendingTracks).length;
  7818. if (pendingTracksCount && (!bufferCodecEventsExpected || pendingTracksCount === 2 || 'audiovideo' in pendingTracks)) {
  7819. // ok, let's create them now !
  7820. this.createSourceBuffers(pendingTracks);
  7821. this.pendingTracks = {};
  7822. // append any pending segments now !
  7823. var buffers = this.getSourceBufferTypes();
  7824. if (buffers.length) {
  7825. this.hls.trigger(Events.BUFFER_CREATED, {
  7826. tracks: this.tracks
  7827. });
  7828. buffers.forEach(function (type) {
  7829. operationQueue.executeNext(type);
  7830. });
  7831. } else {
  7832. var error = new Error('could not create source buffer for media codec(s)');
  7833. this.hls.trigger(Events.ERROR, {
  7834. type: ErrorTypes.MEDIA_ERROR,
  7835. details: ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,
  7836. fatal: true,
  7837. error: error,
  7838. reason: error.message
  7839. });
  7840. }
  7841. }
  7842. };
  7843. _proto.createSourceBuffers = function createSourceBuffers(tracks) {
  7844. var _this11 = this;
  7845. var sourceBuffer = this.sourceBuffer,
  7846. mediaSource = this.mediaSource;
  7847. if (!mediaSource) {
  7848. throw Error('createSourceBuffers called when mediaSource was null');
  7849. }
  7850. var _loop = function _loop(trackName) {
  7851. if (!sourceBuffer[trackName]) {
  7852. var _track$levelCodec;
  7853. var track = tracks[trackName];
  7854. if (!track) {
  7855. throw Error("source buffer exists for track " + trackName + ", however track does not");
  7856. }
  7857. // use levelCodec as first priority unless it contains multiple comma-separated codec values
  7858. var codec = ((_track$levelCodec = track.levelCodec) == null ? void 0 : _track$levelCodec.indexOf(',')) === -1 ? track.levelCodec : track.codec;
  7859. if (codec) {
  7860. if (trackName.slice(0, 5) === 'audio') {
  7861. codec = getCodecCompatibleName(codec, _this11.appendSource);
  7862. }
  7863. }
  7864. var mimeType = track.container + ";codecs=" + codec;
  7865. _this11.log("creating sourceBuffer(" + mimeType + ")");
  7866. try {
  7867. var sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);
  7868. var sbName = trackName;
  7869. _this11.addBufferListener(sbName, 'updatestart', _this11._onSBUpdateStart);
  7870. _this11.addBufferListener(sbName, 'updateend', _this11._onSBUpdateEnd);
  7871. _this11.addBufferListener(sbName, 'error', _this11._onSBUpdateError);
  7872. // ManagedSourceBuffer bufferedchange event
  7873. if (_this11.appendSource) {
  7874. _this11.addBufferListener(sbName, 'bufferedchange', function (type, event) {
  7875. // If media was ejected check for a change. Added ranges are redundant with changes on 'updateend' event.
  7876. var removedRanges = event.removedRanges;
  7877. if (removedRanges != null && removedRanges.length) {
  7878. _this11.hls.trigger(Events.BUFFER_FLUSHED, {
  7879. type: trackName
  7880. });
  7881. }
  7882. });
  7883. }
  7884. _this11.tracks[trackName] = {
  7885. buffer: sb,
  7886. codec: codec,
  7887. container: track.container,
  7888. levelCodec: track.levelCodec,
  7889. metadata: track.metadata,
  7890. id: track.id
  7891. };
  7892. } catch (err) {
  7893. _this11.error("error while trying to add sourceBuffer: " + err.message);
  7894. _this11.hls.trigger(Events.ERROR, {
  7895. type: ErrorTypes.MEDIA_ERROR,
  7896. details: ErrorDetails.BUFFER_ADD_CODEC_ERROR,
  7897. fatal: false,
  7898. error: err,
  7899. sourceBufferName: trackName,
  7900. mimeType: mimeType
  7901. });
  7902. }
  7903. }
  7904. };
  7905. for (var trackName in tracks) {
  7906. _loop(trackName);
  7907. }
  7908. };
  7909. _proto._onSBUpdateStart = function _onSBUpdateStart(type) {
  7910. var operationQueue = this.operationQueue;
  7911. var operation = operationQueue.current(type);
  7912. operation.onStart();
  7913. };
  7914. _proto._onSBUpdateEnd = function _onSBUpdateEnd(type) {
  7915. var _this$mediaSource2;
  7916. if (((_this$mediaSource2 = this.mediaSource) == null ? void 0 : _this$mediaSource2.readyState) === 'closed') {
  7917. this.resetBuffer(type);
  7918. return;
  7919. }
  7920. var operationQueue = this.operationQueue;
  7921. var operation = operationQueue.current(type);
  7922. operation.onComplete();
  7923. operationQueue.shiftAndExecuteNext(type);
  7924. };
  7925. _proto._onSBUpdateError = function _onSBUpdateError(type, event) {
  7926. var _this$mediaSource3;
  7927. var error = new Error(type + " SourceBuffer error. MediaSource readyState: " + ((_this$mediaSource3 = this.mediaSource) == null ? void 0 : _this$mediaSource3.readyState));
  7928. this.error("" + error, event);
  7929. // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
  7930. // SourceBuffer errors are not necessarily fatal; if so, the HTMLMediaElement will fire an error event
  7931. this.hls.trigger(Events.ERROR, {
  7932. type: ErrorTypes.MEDIA_ERROR,
  7933. details: ErrorDetails.BUFFER_APPENDING_ERROR,
  7934. sourceBufferName: type,
  7935. error: error,
  7936. fatal: false
  7937. });
  7938. // updateend is always fired after error, so we'll allow that to shift the current operation off of the queue
  7939. var operation = this.operationQueue.current(type);
  7940. if (operation) {
  7941. operation.onError(error);
  7942. }
  7943. }
  7944. // This method must result in an updateend event; if remove is not called, _onSBUpdateEnd must be called manually
  7945. ;
  7946. _proto.removeExecutor = function removeExecutor(type, startOffset, endOffset) {
  7947. var media = this.media,
  7948. mediaSource = this.mediaSource,
  7949. operationQueue = this.operationQueue,
  7950. sourceBuffer = this.sourceBuffer;
  7951. var sb = sourceBuffer[type];
  7952. if (!media || !mediaSource || !sb) {
  7953. this.warn("Attempting to remove from the " + type + " SourceBuffer, but it does not exist");
  7954. operationQueue.shiftAndExecuteNext(type);
  7955. return;
  7956. }
  7957. var mediaDuration = isFiniteNumber(media.duration) ? media.duration : Infinity;
  7958. var msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : Infinity;
  7959. var removeStart = Math.max(0, startOffset);
  7960. var removeEnd = Math.min(endOffset, mediaDuration, msDuration);
  7961. if (removeEnd > removeStart && (!sb.ending || sb.ended)) {
  7962. sb.ended = false;
  7963. this.log("Removing [" + removeStart + "," + removeEnd + "] from the " + type + " SourceBuffer");
  7964. sb.remove(removeStart, removeEnd);
  7965. } else {
  7966. // Cycle the queue
  7967. operationQueue.shiftAndExecuteNext(type);
  7968. }
  7969. }
  7970. // This method must result in an updateend event; if append is not called, _onSBUpdateEnd must be called manually
  7971. ;
  7972. _proto.appendExecutor = function appendExecutor(data, type) {
  7973. var sb = this.sourceBuffer[type];
  7974. if (!sb) {
  7975. if (!this.pendingTracks[type]) {
  7976. throw new Error("Attempting to append to the " + type + " SourceBuffer, but it does not exist");
  7977. }
  7978. return;
  7979. }
  7980. sb.ended = false;
  7981. sb.appendBuffer(data);
  7982. }
  7983. // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises
  7984. // resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue
  7985. // upon completion, since we already do it here
  7986. ;
  7987. _proto.blockBuffers = function blockBuffers(onUnblocked, buffers) {
  7988. var _this12 = this;
  7989. if (buffers === void 0) {
  7990. buffers = this.getSourceBufferTypes();
  7991. }
  7992. if (!buffers.length) {
  7993. this.log('Blocking operation requested, but no SourceBuffers exist');
  7994. Promise.resolve().then(onUnblocked);
  7995. return;
  7996. }
  7997. var operationQueue = this.operationQueue;
  7998. // logger.debug(`[buffer-controller]: Blocking ${buffers} SourceBuffer`);
  7999. var blockingOperations = buffers.map(function (type) {
  8000. return operationQueue.appendBlocker(type);
  8001. });
  8002. Promise.all(blockingOperations).then(function () {
  8003. // logger.debug(`[buffer-controller]: Blocking operation resolved; unblocking ${buffers} SourceBuffer`);
  8004. onUnblocked();
  8005. buffers.forEach(function (type) {
  8006. var sb = _this12.sourceBuffer[type];
  8007. // Only cycle the queue if the SB is not updating. There's a bug in Chrome which sets the SB updating flag to
  8008. // true when changing the MediaSource duration (https://bugs.chromium.org/p/chromium/issues/detail?id=959359&can=2&q=mediasource%20duration)
  8009. // While this is a workaround, it's probably useful to have around
  8010. if (!(sb != null && sb.updating)) {
  8011. operationQueue.shiftAndExecuteNext(type);
  8012. }
  8013. });
  8014. });
  8015. };
  8016. _proto.getSourceBufferTypes = function getSourceBufferTypes() {
  8017. return Object.keys(this.sourceBuffer);
  8018. };
  8019. _proto.addBufferListener = function addBufferListener(type, event, fn) {
  8020. var buffer = this.sourceBuffer[type];
  8021. if (!buffer) {
  8022. return;
  8023. }
  8024. var listener = fn.bind(this, type);
  8025. this.listeners[type].push({
  8026. event: event,
  8027. listener: listener
  8028. });
  8029. buffer.addEventListener(event, listener);
  8030. };
  8031. _proto.removeBufferListeners = function removeBufferListeners(type) {
  8032. var buffer = this.sourceBuffer[type];
  8033. if (!buffer) {
  8034. return;
  8035. }
  8036. this.listeners[type].forEach(function (l) {
  8037. buffer.removeEventListener(l.event, l.listener);
  8038. });
  8039. };
  8040. _createClass(BufferController, [{
  8041. key: "mediaSrc",
  8042. get: function get() {
  8043. var _this$media, _this$media$querySele;
  8044. 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;
  8045. return media == null ? void 0 : media.src;
  8046. }
  8047. }]);
  8048. return BufferController;
  8049. }();
  8050. function removeSourceChildren(node) {
  8051. var sourceChildren = node.querySelectorAll('source');
  8052. [].slice.call(sourceChildren).forEach(function (source) {
  8053. node.removeChild(source);
  8054. });
  8055. }
  8056. function addSource(media, url) {
  8057. var source = self.document.createElement('source');
  8058. source.type = 'video/mp4';
  8059. source.src = url;
  8060. media.appendChild(source);
  8061. }
  8062. var CapLevelController = /*#__PURE__*/function () {
  8063. function CapLevelController(hls) {
  8064. this.hls = void 0;
  8065. this.autoLevelCapping = void 0;
  8066. this.firstLevel = void 0;
  8067. this.media = void 0;
  8068. this.restrictedLevels = void 0;
  8069. this.timer = void 0;
  8070. this.clientRect = void 0;
  8071. this.streamController = void 0;
  8072. this.hls = hls;
  8073. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  8074. this.firstLevel = -1;
  8075. this.media = null;
  8076. this.restrictedLevels = [];
  8077. this.timer = undefined;
  8078. this.clientRect = null;
  8079. this.registerListeners();
  8080. }
  8081. var _proto = CapLevelController.prototype;
  8082. _proto.setStreamController = function setStreamController(streamController) {
  8083. this.streamController = streamController;
  8084. };
  8085. _proto.destroy = function destroy() {
  8086. if (this.hls) {
  8087. this.unregisterListener();
  8088. }
  8089. if (this.timer) {
  8090. this.stopCapping();
  8091. }
  8092. this.media = null;
  8093. this.clientRect = null;
  8094. // @ts-ignore
  8095. this.hls = this.streamController = null;
  8096. };
  8097. _proto.registerListeners = function registerListeners() {
  8098. var hls = this.hls;
  8099. hls.on(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  8100. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  8101. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  8102. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  8103. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  8104. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  8105. };
  8106. _proto.unregisterListener = function unregisterListener() {
  8107. var hls = this.hls;
  8108. hls.off(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  8109. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  8110. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  8111. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  8112. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  8113. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  8114. };
  8115. _proto.onFpsDropLevelCapping = function onFpsDropLevelCapping(event, data) {
  8116. // Don't add a restricted level more than once
  8117. var level = this.hls.levels[data.droppedLevel];
  8118. if (this.isLevelAllowed(level)) {
  8119. this.restrictedLevels.push({
  8120. bitrate: level.bitrate,
  8121. height: level.height,
  8122. width: level.width
  8123. });
  8124. }
  8125. };
  8126. _proto.onMediaAttaching = function onMediaAttaching(event, data) {
  8127. this.media = data.media instanceof HTMLVideoElement ? data.media : null;
  8128. this.clientRect = null;
  8129. if (this.timer && this.hls.levels.length) {
  8130. this.detectPlayerSize();
  8131. }
  8132. };
  8133. _proto.onManifestParsed = function onManifestParsed(event, data) {
  8134. var hls = this.hls;
  8135. this.restrictedLevels = [];
  8136. this.firstLevel = data.firstLevel;
  8137. if (hls.config.capLevelToPlayerSize && data.video) {
  8138. // Start capping immediately if the manifest has signaled video codecs
  8139. this.startCapping();
  8140. }
  8141. };
  8142. _proto.onLevelsUpdated = function onLevelsUpdated(event, data) {
  8143. if (this.timer && isFiniteNumber(this.autoLevelCapping)) {
  8144. this.detectPlayerSize();
  8145. }
  8146. }
  8147. // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted
  8148. // to the first level
  8149. ;
  8150. _proto.onBufferCodecs = function onBufferCodecs(event, data) {
  8151. var hls = this.hls;
  8152. if (hls.config.capLevelToPlayerSize && data.video) {
  8153. // If the manifest did not signal a video codec capping has been deferred until we're certain video is present
  8154. this.startCapping();
  8155. }
  8156. };
  8157. _proto.onMediaDetaching = function onMediaDetaching() {
  8158. this.stopCapping();
  8159. };
  8160. _proto.detectPlayerSize = function detectPlayerSize() {
  8161. if (this.media) {
  8162. if (this.mediaHeight <= 0 || this.mediaWidth <= 0) {
  8163. this.clientRect = null;
  8164. return;
  8165. }
  8166. var levels = this.hls.levels;
  8167. if (levels.length) {
  8168. var hls = this.hls;
  8169. var maxLevel = this.getMaxLevel(levels.length - 1);
  8170. if (maxLevel !== this.autoLevelCapping) {
  8171. logger.log("Setting autoLevelCapping to " + maxLevel + ": " + levels[maxLevel].height + "p@" + levels[maxLevel].bitrate + " for media " + this.mediaWidth + "x" + this.mediaHeight);
  8172. }
  8173. hls.autoLevelCapping = maxLevel;
  8174. if (hls.autoLevelCapping > this.autoLevelCapping && this.streamController) {
  8175. // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch
  8176. // usually happen when the user go to the fullscreen mode.
  8177. this.streamController.nextLevelSwitch();
  8178. }
  8179. this.autoLevelCapping = hls.autoLevelCapping;
  8180. }
  8181. }
  8182. }
  8183. /*
  8184. * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
  8185. */;
  8186. _proto.getMaxLevel = function getMaxLevel(capLevelIndex) {
  8187. var _this = this;
  8188. var levels = this.hls.levels;
  8189. if (!levels.length) {
  8190. return -1;
  8191. }
  8192. var validLevels = levels.filter(function (level, index) {
  8193. return _this.isLevelAllowed(level) && index <= capLevelIndex;
  8194. });
  8195. this.clientRect = null;
  8196. return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
  8197. };
  8198. _proto.startCapping = function startCapping() {
  8199. if (this.timer) {
  8200. // Don't reset capping if started twice; this can happen if the manifest signals a video codec
  8201. return;
  8202. }
  8203. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  8204. self.clearInterval(this.timer);
  8205. this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1000);
  8206. this.detectPlayerSize();
  8207. };
  8208. _proto.stopCapping = function stopCapping() {
  8209. this.restrictedLevels = [];
  8210. this.firstLevel = -1;
  8211. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  8212. if (this.timer) {
  8213. self.clearInterval(this.timer);
  8214. this.timer = undefined;
  8215. }
  8216. };
  8217. _proto.getDimensions = function getDimensions() {
  8218. if (this.clientRect) {
  8219. return this.clientRect;
  8220. }
  8221. var media = this.media;
  8222. var boundsRect = {
  8223. width: 0,
  8224. height: 0
  8225. };
  8226. if (media) {
  8227. var clientRect = media.getBoundingClientRect();
  8228. boundsRect.width = clientRect.width;
  8229. boundsRect.height = clientRect.height;
  8230. if (!boundsRect.width && !boundsRect.height) {
  8231. // When the media element has no width or height (equivalent to not being in the DOM),
  8232. // then use its width and height attributes (media.width, media.height)
  8233. boundsRect.width = clientRect.right - clientRect.left || media.width || 0;
  8234. boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;
  8235. }
  8236. }
  8237. this.clientRect = boundsRect;
  8238. return boundsRect;
  8239. };
  8240. _proto.isLevelAllowed = function isLevelAllowed(level) {
  8241. var restrictedLevels = this.restrictedLevels;
  8242. return !restrictedLevels.some(function (restrictedLevel) {
  8243. return level.bitrate === restrictedLevel.bitrate && level.width === restrictedLevel.width && level.height === restrictedLevel.height;
  8244. });
  8245. };
  8246. CapLevelController.getMaxLevelByMediaSize = function getMaxLevelByMediaSize(levels, width, height) {
  8247. if (!(levels != null && levels.length)) {
  8248. return -1;
  8249. }
  8250. // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next
  8251. // to determine whether we've chosen the greatest bandwidth for the media's dimensions
  8252. var atGreatestBandwidth = function atGreatestBandwidth(curLevel, nextLevel) {
  8253. if (!nextLevel) {
  8254. return true;
  8255. }
  8256. return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
  8257. };
  8258. // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to
  8259. // the max level
  8260. var maxLevelIndex = levels.length - 1;
  8261. // Prevent changes in aspect-ratio from causing capping to toggle back and forth
  8262. var squareSize = Math.max(width, height);
  8263. for (var i = 0; i < levels.length; i += 1) {
  8264. var level = levels[i];
  8265. if ((level.width >= squareSize || level.height >= squareSize) && atGreatestBandwidth(level, levels[i + 1])) {
  8266. maxLevelIndex = i;
  8267. break;
  8268. }
  8269. }
  8270. return maxLevelIndex;
  8271. };
  8272. _createClass(CapLevelController, [{
  8273. key: "mediaWidth",
  8274. get: function get() {
  8275. return this.getDimensions().width * this.contentScaleFactor;
  8276. }
  8277. }, {
  8278. key: "mediaHeight",
  8279. get: function get() {
  8280. return this.getDimensions().height * this.contentScaleFactor;
  8281. }
  8282. }, {
  8283. key: "contentScaleFactor",
  8284. get: function get() {
  8285. var pixelRatio = 1;
  8286. if (!this.hls.config.ignoreDevicePixelRatio) {
  8287. try {
  8288. pixelRatio = self.devicePixelRatio;
  8289. } catch (e) {
  8290. /* no-op */
  8291. }
  8292. }
  8293. return pixelRatio;
  8294. }
  8295. }]);
  8296. return CapLevelController;
  8297. }();
  8298. var FPSController = /*#__PURE__*/function () {
  8299. function FPSController(hls) {
  8300. this.hls = void 0;
  8301. this.isVideoPlaybackQualityAvailable = false;
  8302. this.timer = void 0;
  8303. this.media = null;
  8304. this.lastTime = void 0;
  8305. this.lastDroppedFrames = 0;
  8306. this.lastDecodedFrames = 0;
  8307. // stream controller must be provided as a dependency!
  8308. this.streamController = void 0;
  8309. this.hls = hls;
  8310. this.registerListeners();
  8311. }
  8312. var _proto = FPSController.prototype;
  8313. _proto.setStreamController = function setStreamController(streamController) {
  8314. this.streamController = streamController;
  8315. };
  8316. _proto.registerListeners = function registerListeners() {
  8317. this.hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  8318. };
  8319. _proto.unregisterListeners = function unregisterListeners() {
  8320. this.hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  8321. };
  8322. _proto.destroy = function destroy() {
  8323. if (this.timer) {
  8324. clearInterval(this.timer);
  8325. }
  8326. this.unregisterListeners();
  8327. this.isVideoPlaybackQualityAvailable = false;
  8328. this.media = null;
  8329. };
  8330. _proto.onMediaAttaching = function onMediaAttaching(event, data) {
  8331. var config = this.hls.config;
  8332. if (config.capLevelOnFPSDrop) {
  8333. var media = data.media instanceof self.HTMLVideoElement ? data.media : null;
  8334. this.media = media;
  8335. if (media && typeof media.getVideoPlaybackQuality === 'function') {
  8336. this.isVideoPlaybackQualityAvailable = true;
  8337. }
  8338. self.clearInterval(this.timer);
  8339. this.timer = self.setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
  8340. }
  8341. };
  8342. _proto.checkFPS = function checkFPS(video, decodedFrames, droppedFrames) {
  8343. var currentTime = performance.now();
  8344. if (decodedFrames) {
  8345. if (this.lastTime) {
  8346. var currentPeriod = currentTime - this.lastTime;
  8347. var currentDropped = droppedFrames - this.lastDroppedFrames;
  8348. var currentDecoded = decodedFrames - this.lastDecodedFrames;
  8349. var droppedFPS = 1000 * currentDropped / currentPeriod;
  8350. var hls = this.hls;
  8351. hls.trigger(Events.FPS_DROP, {
  8352. currentDropped: currentDropped,
  8353. currentDecoded: currentDecoded,
  8354. totalDroppedFrames: droppedFrames
  8355. });
  8356. if (droppedFPS > 0) {
  8357. // logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));
  8358. if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
  8359. var currentLevel = hls.currentLevel;
  8360. logger.warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);
  8361. if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
  8362. currentLevel = currentLevel - 1;
  8363. hls.trigger(Events.FPS_DROP_LEVEL_CAPPING, {
  8364. level: currentLevel,
  8365. droppedLevel: hls.currentLevel
  8366. });
  8367. hls.autoLevelCapping = currentLevel;
  8368. this.streamController.nextLevelSwitch();
  8369. }
  8370. }
  8371. }
  8372. }
  8373. this.lastTime = currentTime;
  8374. this.lastDroppedFrames = droppedFrames;
  8375. this.lastDecodedFrames = decodedFrames;
  8376. }
  8377. };
  8378. _proto.checkFPSInterval = function checkFPSInterval() {
  8379. var video = this.media;
  8380. if (video) {
  8381. if (this.isVideoPlaybackQualityAvailable) {
  8382. var videoPlaybackQuality = video.getVideoPlaybackQuality();
  8383. this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
  8384. } else {
  8385. // HTMLVideoElement doesn't include the webkit types
  8386. this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
  8387. }
  8388. }
  8389. };
  8390. return FPSController;
  8391. }();
  8392. var PATHWAY_PENALTY_DURATION_MS = 300000;
  8393. var ContentSteeringController = /*#__PURE__*/function () {
  8394. function ContentSteeringController(hls) {
  8395. this.hls = void 0;
  8396. this.log = void 0;
  8397. this.loader = null;
  8398. this.uri = null;
  8399. this.pathwayId = '.';
  8400. this.pathwayPriority = null;
  8401. this.timeToLoad = 300;
  8402. this.reloadTimer = -1;
  8403. this.updated = 0;
  8404. this.started = false;
  8405. this.enabled = true;
  8406. this.levels = null;
  8407. this.audioTracks = null;
  8408. this.subtitleTracks = null;
  8409. this.penalizedPathways = {};
  8410. this.hls = hls;
  8411. this.log = logger.log.bind(logger, "[content-steering]:");
  8412. this.registerListeners();
  8413. }
  8414. var _proto = ContentSteeringController.prototype;
  8415. _proto.registerListeners = function registerListeners() {
  8416. var hls = this.hls;
  8417. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  8418. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  8419. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  8420. hls.on(Events.ERROR, this.onError, this);
  8421. };
  8422. _proto.unregisterListeners = function unregisterListeners() {
  8423. var hls = this.hls;
  8424. if (!hls) {
  8425. return;
  8426. }
  8427. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  8428. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  8429. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  8430. hls.off(Events.ERROR, this.onError, this);
  8431. };
  8432. _proto.startLoad = function startLoad() {
  8433. this.started = true;
  8434. this.clearTimeout();
  8435. if (this.enabled && this.uri) {
  8436. if (this.updated) {
  8437. var ttl = this.timeToLoad * 1000 - (performance.now() - this.updated);
  8438. if (ttl > 0) {
  8439. this.scheduleRefresh(this.uri, ttl);
  8440. return;
  8441. }
  8442. }
  8443. this.loadSteeringManifest(this.uri);
  8444. }
  8445. };
  8446. _proto.stopLoad = function stopLoad() {
  8447. this.started = false;
  8448. if (this.loader) {
  8449. this.loader.destroy();
  8450. this.loader = null;
  8451. }
  8452. this.clearTimeout();
  8453. };
  8454. _proto.clearTimeout = function clearTimeout() {
  8455. if (this.reloadTimer !== -1) {
  8456. self.clearTimeout(this.reloadTimer);
  8457. this.reloadTimer = -1;
  8458. }
  8459. };
  8460. _proto.destroy = function destroy() {
  8461. this.unregisterListeners();
  8462. this.stopLoad();
  8463. // @ts-ignore
  8464. this.hls = null;
  8465. this.levels = this.audioTracks = this.subtitleTracks = null;
  8466. };
  8467. _proto.removeLevel = function removeLevel(levelToRemove) {
  8468. var levels = this.levels;
  8469. if (levels) {
  8470. this.levels = levels.filter(function (level) {
  8471. return level !== levelToRemove;
  8472. });
  8473. }
  8474. };
  8475. _proto.onManifestLoading = function onManifestLoading() {
  8476. this.stopLoad();
  8477. this.enabled = true;
  8478. this.timeToLoad = 300;
  8479. this.updated = 0;
  8480. this.uri = null;
  8481. this.pathwayId = '.';
  8482. this.levels = this.audioTracks = this.subtitleTracks = null;
  8483. };
  8484. _proto.onManifestLoaded = function onManifestLoaded(event, data) {
  8485. var contentSteering = data.contentSteering;
  8486. if (contentSteering === null) {
  8487. return;
  8488. }
  8489. this.pathwayId = contentSteering.pathwayId;
  8490. this.uri = contentSteering.uri;
  8491. if (this.started) {
  8492. this.startLoad();
  8493. }
  8494. };
  8495. _proto.onManifestParsed = function onManifestParsed(event, data) {
  8496. this.audioTracks = data.audioTracks;
  8497. this.subtitleTracks = data.subtitleTracks;
  8498. };
  8499. _proto.onError = function onError(event, data) {
  8500. var errorAction = data.errorAction;
  8501. if ((errorAction == null ? void 0 : errorAction.action) === NetworkErrorAction.SendAlternateToPenaltyBox && errorAction.flags === ErrorActionFlags.MoveAllAlternatesMatchingHost) {
  8502. var levels = this.levels;
  8503. var pathwayPriority = this.pathwayPriority;
  8504. var errorPathway = this.pathwayId;
  8505. if (data.context) {
  8506. var _data$context = data.context,
  8507. groupId = _data$context.groupId,
  8508. _pathwayId = _data$context.pathwayId,
  8509. type = _data$context.type;
  8510. if (groupId && levels) {
  8511. errorPathway = this.getPathwayForGroupId(groupId, type, errorPathway);
  8512. } else if (_pathwayId) {
  8513. errorPathway = _pathwayId;
  8514. }
  8515. }
  8516. if (!(errorPathway in this.penalizedPathways)) {
  8517. this.penalizedPathways[errorPathway] = performance.now();
  8518. }
  8519. if (!pathwayPriority && levels) {
  8520. // If PATHWAY-PRIORITY was not provided, list pathways for error handling
  8521. pathwayPriority = levels.reduce(function (pathways, level) {
  8522. if (pathways.indexOf(level.pathwayId) === -1) {
  8523. pathways.push(level.pathwayId);
  8524. }
  8525. return pathways;
  8526. }, []);
  8527. }
  8528. if (pathwayPriority && pathwayPriority.length > 1) {
  8529. this.updatePathwayPriority(pathwayPriority);
  8530. errorAction.resolved = this.pathwayId !== errorPathway;
  8531. }
  8532. if (!errorAction.resolved) {
  8533. logger.warn("Could not resolve " + data.details + " (\"" + data.error.message + "\") with content-steering for Pathway: " + errorPathway + " levels: " + (levels ? levels.length : levels) + " priorities: " + JSON.stringify(pathwayPriority) + " penalized: " + JSON.stringify(this.penalizedPathways));
  8534. }
  8535. }
  8536. };
  8537. _proto.filterParsedLevels = function filterParsedLevels(levels) {
  8538. // Filter levels to only include those that are in the initial pathway
  8539. this.levels = levels;
  8540. var pathwayLevels = this.getLevelsForPathway(this.pathwayId);
  8541. if (pathwayLevels.length === 0) {
  8542. var _pathwayId2 = levels[0].pathwayId;
  8543. this.log("No levels found in Pathway " + this.pathwayId + ". Setting initial Pathway to \"" + _pathwayId2 + "\"");
  8544. pathwayLevels = this.getLevelsForPathway(_pathwayId2);
  8545. this.pathwayId = _pathwayId2;
  8546. }
  8547. if (pathwayLevels.length !== levels.length) {
  8548. this.log("Found " + pathwayLevels.length + "/" + levels.length + " levels in Pathway \"" + this.pathwayId + "\"");
  8549. return pathwayLevels;
  8550. }
  8551. return levels;
  8552. };
  8553. _proto.getLevelsForPathway = function getLevelsForPathway(pathwayId) {
  8554. if (this.levels === null) {
  8555. return [];
  8556. }
  8557. return this.levels.filter(function (level) {
  8558. return pathwayId === level.pathwayId;
  8559. });
  8560. };
  8561. _proto.updatePathwayPriority = function updatePathwayPriority(pathwayPriority) {
  8562. this.pathwayPriority = pathwayPriority;
  8563. var levels;
  8564. // Evaluate if we should remove the pathway from the penalized list
  8565. var penalizedPathways = this.penalizedPathways;
  8566. var now = performance.now();
  8567. Object.keys(penalizedPathways).forEach(function (pathwayId) {
  8568. if (now - penalizedPathways[pathwayId] > PATHWAY_PENALTY_DURATION_MS) {
  8569. delete penalizedPathways[pathwayId];
  8570. }
  8571. });
  8572. for (var i = 0; i < pathwayPriority.length; i++) {
  8573. var _pathwayId3 = pathwayPriority[i];
  8574. if (_pathwayId3 in penalizedPathways) {
  8575. continue;
  8576. }
  8577. if (_pathwayId3 === this.pathwayId) {
  8578. return;
  8579. }
  8580. var selectedIndex = this.hls.nextLoadLevel;
  8581. var selectedLevel = this.hls.levels[selectedIndex];
  8582. levels = this.getLevelsForPathway(_pathwayId3);
  8583. if (levels.length > 0) {
  8584. this.log("Setting Pathway to \"" + _pathwayId3 + "\"");
  8585. this.pathwayId = _pathwayId3;
  8586. reassignFragmentLevelIndexes(levels);
  8587. this.hls.trigger(Events.LEVELS_UPDATED, {
  8588. levels: levels
  8589. });
  8590. // Set LevelController's level to trigger LEVEL_SWITCHING which loads playlist if needed
  8591. var levelAfterChange = this.hls.levels[selectedIndex];
  8592. if (selectedLevel && levelAfterChange && this.levels) {
  8593. if (levelAfterChange.attrs['STABLE-VARIANT-ID'] !== selectedLevel.attrs['STABLE-VARIANT-ID'] && levelAfterChange.bitrate !== selectedLevel.bitrate) {
  8594. this.log("Unstable Pathways change from bitrate " + selectedLevel.bitrate + " to " + levelAfterChange.bitrate);
  8595. }
  8596. this.hls.nextLoadLevel = selectedIndex;
  8597. }
  8598. break;
  8599. }
  8600. }
  8601. };
  8602. _proto.getPathwayForGroupId = function getPathwayForGroupId(groupId, type, defaultPathway) {
  8603. var levels = this.getLevelsForPathway(defaultPathway).concat(this.levels || []);
  8604. for (var i = 0; i < levels.length; i++) {
  8605. if (type === PlaylistContextType.AUDIO_TRACK && levels[i].hasAudioGroup(groupId) || type === PlaylistContextType.SUBTITLE_TRACK && levels[i].hasSubtitleGroup(groupId)) {
  8606. return levels[i].pathwayId;
  8607. }
  8608. }
  8609. return defaultPathway;
  8610. };
  8611. _proto.clonePathways = function clonePathways(pathwayClones) {
  8612. var _this = this;
  8613. var levels = this.levels;
  8614. if (!levels) {
  8615. return;
  8616. }
  8617. var audioGroupCloneMap = {};
  8618. var subtitleGroupCloneMap = {};
  8619. pathwayClones.forEach(function (pathwayClone) {
  8620. var cloneId = pathwayClone.ID,
  8621. baseId = pathwayClone['BASE-ID'],
  8622. uriReplacement = pathwayClone['URI-REPLACEMENT'];
  8623. if (levels.some(function (level) {
  8624. return level.pathwayId === cloneId;
  8625. })) {
  8626. return;
  8627. }
  8628. var clonedVariants = _this.getLevelsForPathway(baseId).map(function (baseLevel) {
  8629. var attributes = new AttrList(baseLevel.attrs);
  8630. attributes['PATHWAY-ID'] = cloneId;
  8631. var clonedAudioGroupId = attributes.AUDIO && attributes.AUDIO + "_clone_" + cloneId;
  8632. var clonedSubtitleGroupId = attributes.SUBTITLES && attributes.SUBTITLES + "_clone_" + cloneId;
  8633. if (clonedAudioGroupId) {
  8634. audioGroupCloneMap[attributes.AUDIO] = clonedAudioGroupId;
  8635. attributes.AUDIO = clonedAudioGroupId;
  8636. }
  8637. if (clonedSubtitleGroupId) {
  8638. subtitleGroupCloneMap[attributes.SUBTITLES] = clonedSubtitleGroupId;
  8639. attributes.SUBTITLES = clonedSubtitleGroupId;
  8640. }
  8641. var url = performUriReplacement(baseLevel.uri, attributes['STABLE-VARIANT-ID'], 'PER-VARIANT-URIS', uriReplacement);
  8642. var clonedLevel = new Level({
  8643. attrs: attributes,
  8644. audioCodec: baseLevel.audioCodec,
  8645. bitrate: baseLevel.bitrate,
  8646. height: baseLevel.height,
  8647. name: baseLevel.name,
  8648. url: url,
  8649. videoCodec: baseLevel.videoCodec,
  8650. width: baseLevel.width
  8651. });
  8652. if (baseLevel.audioGroups) {
  8653. for (var i = 1; i < baseLevel.audioGroups.length; i++) {
  8654. clonedLevel.addGroupId('audio', baseLevel.audioGroups[i] + "_clone_" + cloneId);
  8655. }
  8656. }
  8657. if (baseLevel.subtitleGroups) {
  8658. for (var _i = 1; _i < baseLevel.subtitleGroups.length; _i++) {
  8659. clonedLevel.addGroupId('text', baseLevel.subtitleGroups[_i] + "_clone_" + cloneId);
  8660. }
  8661. }
  8662. return clonedLevel;
  8663. });
  8664. levels.push.apply(levels, clonedVariants);
  8665. cloneRenditionGroups(_this.audioTracks, audioGroupCloneMap, uriReplacement, cloneId);
  8666. cloneRenditionGroups(_this.subtitleTracks, subtitleGroupCloneMap, uriReplacement, cloneId);
  8667. });
  8668. };
  8669. _proto.loadSteeringManifest = function loadSteeringManifest(uri) {
  8670. var _this2 = this;
  8671. var config = this.hls.config;
  8672. var Loader = config.loader;
  8673. if (this.loader) {
  8674. this.loader.destroy();
  8675. }
  8676. this.loader = new Loader(config);
  8677. var url;
  8678. try {
  8679. url = new self.URL(uri);
  8680. } catch (error) {
  8681. this.enabled = false;
  8682. this.log("Failed to parse Steering Manifest URI: " + uri);
  8683. return;
  8684. }
  8685. if (url.protocol !== 'data:') {
  8686. var throughput = (this.hls.bandwidthEstimate || config.abrEwmaDefaultEstimate) | 0;
  8687. url.searchParams.set('_HLS_pathway', this.pathwayId);
  8688. url.searchParams.set('_HLS_throughput', '' + throughput);
  8689. }
  8690. var context = {
  8691. responseType: 'json',
  8692. url: url.href
  8693. };
  8694. var loadPolicy = config.steeringManifestLoadPolicy.default;
  8695. var legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  8696. var loaderConfig = {
  8697. loadPolicy: loadPolicy,
  8698. timeout: loadPolicy.maxLoadTimeMs,
  8699. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  8700. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  8701. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  8702. };
  8703. var callbacks = {
  8704. onSuccess: function onSuccess(response, stats, context, networkDetails) {
  8705. _this2.log("Loaded steering manifest: \"" + url + "\"");
  8706. var steeringData = response.data;
  8707. if (steeringData.VERSION !== 1) {
  8708. _this2.log("Steering VERSION " + steeringData.VERSION + " not supported!");
  8709. return;
  8710. }
  8711. _this2.updated = performance.now();
  8712. _this2.timeToLoad = steeringData.TTL;
  8713. var reloadUri = steeringData['RELOAD-URI'],
  8714. pathwayClones = steeringData['PATHWAY-CLONES'],
  8715. pathwayPriority = steeringData['PATHWAY-PRIORITY'];
  8716. if (reloadUri) {
  8717. try {
  8718. _this2.uri = new self.URL(reloadUri, url).href;
  8719. } catch (error) {
  8720. _this2.enabled = false;
  8721. _this2.log("Failed to parse Steering Manifest RELOAD-URI: " + reloadUri);
  8722. return;
  8723. }
  8724. }
  8725. _this2.scheduleRefresh(_this2.uri || context.url);
  8726. if (pathwayClones) {
  8727. _this2.clonePathways(pathwayClones);
  8728. }
  8729. var loadedSteeringData = {
  8730. steeringManifest: steeringData,
  8731. url: url.toString()
  8732. };
  8733. _this2.hls.trigger(Events.STEERING_MANIFEST_LOADED, loadedSteeringData);
  8734. if (pathwayPriority) {
  8735. _this2.updatePathwayPriority(pathwayPriority);
  8736. }
  8737. },
  8738. onError: function onError(error, context, networkDetails, stats) {
  8739. _this2.log("Error loading steering manifest: " + error.code + " " + error.text + " (" + context.url + ")");
  8740. _this2.stopLoad();
  8741. if (error.code === 410) {
  8742. _this2.enabled = false;
  8743. _this2.log("Steering manifest " + context.url + " no longer available");
  8744. return;
  8745. }
  8746. var ttl = _this2.timeToLoad * 1000;
  8747. if (error.code === 429) {
  8748. var loader = _this2.loader;
  8749. if (typeof (loader == null ? void 0 : loader.getResponseHeader) === 'function') {
  8750. var retryAfter = loader.getResponseHeader('Retry-After');
  8751. if (retryAfter) {
  8752. ttl = parseFloat(retryAfter) * 1000;
  8753. }
  8754. }
  8755. _this2.log("Steering manifest " + context.url + " rate limited");
  8756. return;
  8757. }
  8758. _this2.scheduleRefresh(_this2.uri || context.url, ttl);
  8759. },
  8760. onTimeout: function onTimeout(stats, context, networkDetails) {
  8761. _this2.log("Timeout loading steering manifest (" + context.url + ")");
  8762. _this2.scheduleRefresh(_this2.uri || context.url);
  8763. }
  8764. };
  8765. this.log("Requesting steering manifest: " + url);
  8766. this.loader.load(context, loaderConfig, callbacks);
  8767. };
  8768. _proto.scheduleRefresh = function scheduleRefresh(uri, ttlMs) {
  8769. var _this3 = this;
  8770. if (ttlMs === void 0) {
  8771. ttlMs = this.timeToLoad * 1000;
  8772. }
  8773. this.clearTimeout();
  8774. this.reloadTimer = self.setTimeout(function () {
  8775. var _this3$hls;
  8776. var media = (_this3$hls = _this3.hls) == null ? void 0 : _this3$hls.media;
  8777. if (media && !media.ended) {
  8778. _this3.loadSteeringManifest(uri);
  8779. return;
  8780. }
  8781. _this3.scheduleRefresh(uri, _this3.timeToLoad * 1000);
  8782. }, ttlMs);
  8783. };
  8784. return ContentSteeringController;
  8785. }();
  8786. function cloneRenditionGroups(tracks, groupCloneMap, uriReplacement, cloneId) {
  8787. if (!tracks) {
  8788. return;
  8789. }
  8790. Object.keys(groupCloneMap).forEach(function (audioGroupId) {
  8791. var clonedTracks = tracks.filter(function (track) {
  8792. return track.groupId === audioGroupId;
  8793. }).map(function (track) {
  8794. var clonedTrack = _extends({}, track);
  8795. clonedTrack.details = undefined;
  8796. clonedTrack.attrs = new AttrList(clonedTrack.attrs);
  8797. clonedTrack.url = clonedTrack.attrs.URI = performUriReplacement(track.url, track.attrs['STABLE-RENDITION-ID'], 'PER-RENDITION-URIS', uriReplacement);
  8798. clonedTrack.groupId = clonedTrack.attrs['GROUP-ID'] = groupCloneMap[audioGroupId];
  8799. clonedTrack.attrs['PATHWAY-ID'] = cloneId;
  8800. return clonedTrack;
  8801. });
  8802. tracks.push.apply(tracks, clonedTracks);
  8803. });
  8804. }
  8805. function performUriReplacement(uri, stableId, perOptionKey, uriReplacement) {
  8806. var host = uriReplacement.HOST,
  8807. params = uriReplacement.PARAMS,
  8808. perOptionUris = uriReplacement[perOptionKey];
  8809. var perVariantUri;
  8810. if (stableId) {
  8811. perVariantUri = perOptionUris == null ? void 0 : perOptionUris[stableId];
  8812. if (perVariantUri) {
  8813. uri = perVariantUri;
  8814. }
  8815. }
  8816. var url = new self.URL(uri);
  8817. if (host && !perVariantUri) {
  8818. url.host = host;
  8819. }
  8820. if (params) {
  8821. Object.keys(params).sort().forEach(function (key) {
  8822. if (key) {
  8823. url.searchParams.set(key, params[key]);
  8824. }
  8825. });
  8826. }
  8827. return url.href;
  8828. }
  8829. var AGE_HEADER_LINE_REGEX = /^age:\s*[\d.]+\s*$/im;
  8830. var XhrLoader = /*#__PURE__*/function () {
  8831. function XhrLoader(config) {
  8832. this.xhrSetup = void 0;
  8833. this.requestTimeout = void 0;
  8834. this.retryTimeout = void 0;
  8835. this.retryDelay = void 0;
  8836. this.config = null;
  8837. this.callbacks = null;
  8838. this.context = null;
  8839. this.loader = null;
  8840. this.stats = void 0;
  8841. this.xhrSetup = config ? config.xhrSetup || null : null;
  8842. this.stats = new LoadStats();
  8843. this.retryDelay = 0;
  8844. }
  8845. var _proto = XhrLoader.prototype;
  8846. _proto.destroy = function destroy() {
  8847. this.callbacks = null;
  8848. this.abortInternal();
  8849. this.loader = null;
  8850. this.config = null;
  8851. this.context = null;
  8852. this.xhrSetup = null;
  8853. };
  8854. _proto.abortInternal = function abortInternal() {
  8855. var loader = this.loader;
  8856. self.clearTimeout(this.requestTimeout);
  8857. self.clearTimeout(this.retryTimeout);
  8858. if (loader) {
  8859. loader.onreadystatechange = null;
  8860. loader.onprogress = null;
  8861. if (loader.readyState !== 4) {
  8862. this.stats.aborted = true;
  8863. loader.abort();
  8864. }
  8865. }
  8866. };
  8867. _proto.abort = function abort() {
  8868. var _this$callbacks;
  8869. this.abortInternal();
  8870. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  8871. this.callbacks.onAbort(this.stats, this.context, this.loader);
  8872. }
  8873. };
  8874. _proto.load = function load(context, config, callbacks) {
  8875. if (this.stats.loading.start) {
  8876. throw new Error('Loader can only be used once.');
  8877. }
  8878. this.stats.loading.start = self.performance.now();
  8879. this.context = context;
  8880. this.config = config;
  8881. this.callbacks = callbacks;
  8882. this.loadInternal();
  8883. };
  8884. _proto.loadInternal = function loadInternal() {
  8885. var _this = this;
  8886. var config = this.config,
  8887. context = this.context;
  8888. if (!config || !context) {
  8889. return;
  8890. }
  8891. var xhr = this.loader = new self.XMLHttpRequest();
  8892. var stats = this.stats;
  8893. stats.loading.first = 0;
  8894. stats.loaded = 0;
  8895. stats.aborted = false;
  8896. var xhrSetup = this.xhrSetup;
  8897. if (xhrSetup) {
  8898. Promise.resolve().then(function () {
  8899. if (_this.loader !== xhr || _this.stats.aborted) return;
  8900. return xhrSetup(xhr, context.url);
  8901. }).catch(function (error) {
  8902. if (_this.loader !== xhr || _this.stats.aborted) return;
  8903. xhr.open('GET', context.url, true);
  8904. return xhrSetup(xhr, context.url);
  8905. }).then(function () {
  8906. if (_this.loader !== xhr || _this.stats.aborted) return;
  8907. _this.openAndSendXhr(xhr, context, config);
  8908. }).catch(function (error) {
  8909. // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
  8910. _this.callbacks.onError({
  8911. code: xhr.status,
  8912. text: error.message
  8913. }, context, xhr, stats);
  8914. return;
  8915. });
  8916. } else {
  8917. this.openAndSendXhr(xhr, context, config);
  8918. }
  8919. };
  8920. _proto.openAndSendXhr = function openAndSendXhr(xhr, context, config) {
  8921. if (!xhr.readyState) {
  8922. xhr.open('GET', context.url, true);
  8923. }
  8924. var headers = context.headers;
  8925. var _config$loadPolicy = config.loadPolicy,
  8926. maxTimeToFirstByteMs = _config$loadPolicy.maxTimeToFirstByteMs,
  8927. maxLoadTimeMs = _config$loadPolicy.maxLoadTimeMs;
  8928. if (headers) {
  8929. for (var header in headers) {
  8930. xhr.setRequestHeader(header, headers[header]);
  8931. }
  8932. }
  8933. if (context.rangeEnd) {
  8934. xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));
  8935. }
  8936. xhr.onreadystatechange = this.readystatechange.bind(this);
  8937. xhr.onprogress = this.loadprogress.bind(this);
  8938. xhr.responseType = context.responseType;
  8939. // setup timeout before we perform request
  8940. self.clearTimeout(this.requestTimeout);
  8941. config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  8942. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);
  8943. xhr.send();
  8944. };
  8945. _proto.readystatechange = function readystatechange() {
  8946. var context = this.context,
  8947. xhr = this.loader,
  8948. stats = this.stats;
  8949. if (!context || !xhr) {
  8950. return;
  8951. }
  8952. var readyState = xhr.readyState;
  8953. var config = this.config;
  8954. // don't proceed if xhr has been aborted
  8955. if (stats.aborted) {
  8956. return;
  8957. }
  8958. // >= HEADERS_RECEIVED
  8959. if (readyState >= 2) {
  8960. if (stats.loading.first === 0) {
  8961. stats.loading.first = Math.max(self.performance.now(), stats.loading.start);
  8962. // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet
  8963. if (config.timeout !== config.loadPolicy.maxLoadTimeMs) {
  8964. self.clearTimeout(this.requestTimeout);
  8965. config.timeout = config.loadPolicy.maxLoadTimeMs;
  8966. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.loadPolicy.maxLoadTimeMs - (stats.loading.first - stats.loading.start));
  8967. }
  8968. }
  8969. if (readyState === 4) {
  8970. self.clearTimeout(this.requestTimeout);
  8971. xhr.onreadystatechange = null;
  8972. xhr.onprogress = null;
  8973. var _status = xhr.status;
  8974. // http status between 200 to 299 are all successful
  8975. var useResponse = xhr.responseType !== 'text';
  8976. if (_status >= 200 && _status < 300 && (useResponse && xhr.response || xhr.responseText !== null)) {
  8977. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  8978. var data = useResponse ? xhr.response : xhr.responseText;
  8979. var len = xhr.responseType === 'arraybuffer' ? data.byteLength : data.length;
  8980. stats.loaded = stats.total = len;
  8981. stats.bwEstimate = stats.total * 8000 / (stats.loading.end - stats.loading.first);
  8982. if (!this.callbacks) {
  8983. return;
  8984. }
  8985. var onProgress = this.callbacks.onProgress;
  8986. if (onProgress) {
  8987. onProgress(stats, context, data, xhr);
  8988. }
  8989. if (!this.callbacks) {
  8990. return;
  8991. }
  8992. var response = {
  8993. url: xhr.responseURL,
  8994. data: data,
  8995. code: _status
  8996. };
  8997. this.callbacks.onSuccess(response, stats, context, xhr);
  8998. } else {
  8999. var retryConfig = config.loadPolicy.errorRetry;
  9000. var retryCount = stats.retry;
  9001. // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error
  9002. var _response = {
  9003. url: context.url,
  9004. data: undefined,
  9005. code: _status
  9006. };
  9007. if (shouldRetry(retryConfig, retryCount, false, _response)) {
  9008. this.retry(retryConfig);
  9009. } else {
  9010. logger.error(_status + " while loading " + context.url);
  9011. this.callbacks.onError({
  9012. code: _status,
  9013. text: xhr.statusText
  9014. }, context, xhr, stats);
  9015. }
  9016. }
  9017. }
  9018. }
  9019. };
  9020. _proto.loadtimeout = function loadtimeout() {
  9021. if (!this.config) return;
  9022. var retryConfig = this.config.loadPolicy.timeoutRetry;
  9023. var retryCount = this.stats.retry;
  9024. if (shouldRetry(retryConfig, retryCount, true)) {
  9025. this.retry(retryConfig);
  9026. } else {
  9027. var _this$context;
  9028. logger.warn("timeout while loading " + ((_this$context = this.context) == null ? void 0 : _this$context.url));
  9029. var callbacks = this.callbacks;
  9030. if (callbacks) {
  9031. this.abortInternal();
  9032. callbacks.onTimeout(this.stats, this.context, this.loader);
  9033. }
  9034. }
  9035. };
  9036. _proto.retry = function retry(retryConfig) {
  9037. var context = this.context,
  9038. stats = this.stats;
  9039. this.retryDelay = getRetryDelay(retryConfig, stats.retry);
  9040. stats.retry++;
  9041. logger.warn((status ? 'HTTP Status ' + status : 'Timeout') + " while loading " + (context == null ? void 0 : context.url) + ", retrying " + stats.retry + "/" + retryConfig.maxNumRetry + " in " + this.retryDelay + "ms");
  9042. // abort and reset internal state
  9043. this.abortInternal();
  9044. this.loader = null;
  9045. // schedule retry
  9046. self.clearTimeout(this.retryTimeout);
  9047. this.retryTimeout = self.setTimeout(this.loadInternal.bind(this), this.retryDelay);
  9048. };
  9049. _proto.loadprogress = function loadprogress(event) {
  9050. var stats = this.stats;
  9051. stats.loaded = event.loaded;
  9052. if (event.lengthComputable) {
  9053. stats.total = event.total;
  9054. }
  9055. };
  9056. _proto.getCacheAge = function getCacheAge() {
  9057. var result = null;
  9058. if (this.loader && AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())) {
  9059. var ageHeader = this.loader.getResponseHeader('age');
  9060. result = ageHeader ? parseFloat(ageHeader) : null;
  9061. }
  9062. return result;
  9063. };
  9064. _proto.getResponseHeader = function getResponseHeader(name) {
  9065. if (this.loader && new RegExp("^" + name + ":\\s*[\\d.]+\\s*$", 'im').test(this.loader.getAllResponseHeaders())) {
  9066. return this.loader.getResponseHeader(name);
  9067. }
  9068. return null;
  9069. };
  9070. return XhrLoader;
  9071. }();
  9072. var ChunkCache = /*#__PURE__*/function () {
  9073. function ChunkCache() {
  9074. this.chunks = [];
  9075. this.dataLength = 0;
  9076. }
  9077. var _proto = ChunkCache.prototype;
  9078. _proto.push = function push(chunk) {
  9079. this.chunks.push(chunk);
  9080. this.dataLength += chunk.length;
  9081. };
  9082. _proto.flush = function flush() {
  9083. var chunks = this.chunks,
  9084. dataLength = this.dataLength;
  9085. var result;
  9086. if (!chunks.length) {
  9087. return new Uint8Array(0);
  9088. } else if (chunks.length === 1) {
  9089. result = chunks[0];
  9090. } else {
  9091. result = concatUint8Arrays(chunks, dataLength);
  9092. }
  9093. this.reset();
  9094. return result;
  9095. };
  9096. _proto.reset = function reset() {
  9097. this.chunks.length = 0;
  9098. this.dataLength = 0;
  9099. };
  9100. return ChunkCache;
  9101. }();
  9102. function concatUint8Arrays(chunks, dataLength) {
  9103. var result = new Uint8Array(dataLength);
  9104. var offset = 0;
  9105. for (var i = 0; i < chunks.length; i++) {
  9106. var chunk = chunks[i];
  9107. result.set(chunk, offset);
  9108. offset += chunk.length;
  9109. }
  9110. return result;
  9111. }
  9112. function fetchSupported() {
  9113. if (
  9114. // @ts-ignore
  9115. self.fetch && self.AbortController && self.ReadableStream && self.Request) {
  9116. try {
  9117. new self.ReadableStream({}); // eslint-disable-line no-new
  9118. return true;
  9119. } catch (e) {
  9120. /* noop */
  9121. }
  9122. }
  9123. return false;
  9124. }
  9125. var BYTERANGE = /(\d+)-(\d+)\/(\d+)/;
  9126. var FetchLoader = /*#__PURE__*/function () {
  9127. function FetchLoader(config /* HlsConfig */) {
  9128. this.fetchSetup = void 0;
  9129. this.requestTimeout = void 0;
  9130. this.request = null;
  9131. this.response = null;
  9132. this.controller = void 0;
  9133. this.context = null;
  9134. this.config = null;
  9135. this.callbacks = null;
  9136. this.stats = void 0;
  9137. this.loader = null;
  9138. this.fetchSetup = config.fetchSetup || getRequest;
  9139. this.controller = new self.AbortController();
  9140. this.stats = new LoadStats();
  9141. }
  9142. var _proto = FetchLoader.prototype;
  9143. _proto.destroy = function destroy() {
  9144. this.loader = this.callbacks = this.context = this.config = this.request = null;
  9145. this.abortInternal();
  9146. this.response = null;
  9147. // @ts-ignore
  9148. this.fetchSetup = this.controller = this.stats = null;
  9149. };
  9150. _proto.abortInternal = function abortInternal() {
  9151. if (this.controller && !this.stats.loading.end) {
  9152. this.stats.aborted = true;
  9153. this.controller.abort();
  9154. }
  9155. };
  9156. _proto.abort = function abort() {
  9157. var _this$callbacks;
  9158. this.abortInternal();
  9159. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  9160. this.callbacks.onAbort(this.stats, this.context, this.response);
  9161. }
  9162. };
  9163. _proto.load = function load(context, config, callbacks) {
  9164. var _this = this;
  9165. var stats = this.stats;
  9166. if (stats.loading.start) {
  9167. throw new Error('Loader can only be used once.');
  9168. }
  9169. stats.loading.start = self.performance.now();
  9170. var initParams = getRequestParameters(context, this.controller.signal);
  9171. var onProgress = callbacks.onProgress;
  9172. var isArrayBuffer = context.responseType === 'arraybuffer';
  9173. var LENGTH = isArrayBuffer ? 'byteLength' : 'length';
  9174. var _config$loadPolicy = config.loadPolicy,
  9175. maxTimeToFirstByteMs = _config$loadPolicy.maxTimeToFirstByteMs,
  9176. maxLoadTimeMs = _config$loadPolicy.maxLoadTimeMs;
  9177. this.context = context;
  9178. this.config = config;
  9179. this.callbacks = callbacks;
  9180. this.request = this.fetchSetup(context, initParams);
  9181. self.clearTimeout(this.requestTimeout);
  9182. config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  9183. this.requestTimeout = self.setTimeout(function () {
  9184. _this.abortInternal();
  9185. callbacks.onTimeout(stats, context, _this.response);
  9186. }, config.timeout);
  9187. self.fetch(this.request).then(function (response) {
  9188. _this.response = _this.loader = response;
  9189. var first = Math.max(self.performance.now(), stats.loading.start);
  9190. self.clearTimeout(_this.requestTimeout);
  9191. config.timeout = maxLoadTimeMs;
  9192. _this.requestTimeout = self.setTimeout(function () {
  9193. _this.abortInternal();
  9194. callbacks.onTimeout(stats, context, _this.response);
  9195. }, maxLoadTimeMs - (first - stats.loading.start));
  9196. if (!response.ok) {
  9197. var status = response.status,
  9198. statusText = response.statusText;
  9199. throw new FetchError(statusText || 'fetch, bad network response', status, response);
  9200. }
  9201. stats.loading.first = first;
  9202. stats.total = getContentLength(response.headers) || stats.total;
  9203. if (onProgress && isFiniteNumber(config.highWaterMark)) {
  9204. return _this.loadProgressively(response, stats, context, config.highWaterMark, onProgress);
  9205. }
  9206. if (isArrayBuffer) {
  9207. return response.arrayBuffer();
  9208. }
  9209. if (context.responseType === 'json') {
  9210. return response.json();
  9211. }
  9212. return response.text();
  9213. }).then(function (responseData) {
  9214. var response = _this.response;
  9215. if (!response) {
  9216. throw new Error('loader destroyed');
  9217. }
  9218. self.clearTimeout(_this.requestTimeout);
  9219. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  9220. var total = responseData[LENGTH];
  9221. if (total) {
  9222. stats.loaded = stats.total = total;
  9223. }
  9224. var loaderResponse = {
  9225. url: response.url,
  9226. data: responseData,
  9227. code: response.status
  9228. };
  9229. if (onProgress && !isFiniteNumber(config.highWaterMark)) {
  9230. onProgress(stats, context, responseData, response);
  9231. }
  9232. callbacks.onSuccess(loaderResponse, stats, context, response);
  9233. }).catch(function (error) {
  9234. self.clearTimeout(_this.requestTimeout);
  9235. if (stats.aborted) {
  9236. return;
  9237. }
  9238. // CORS errors result in an undefined code. Set it to 0 here to align with XHR's behavior
  9239. // when destroying, 'error' itself can be undefined
  9240. var code = !error ? 0 : error.code || 0;
  9241. var text = !error ? null : error.message;
  9242. callbacks.onError({
  9243. code: code,
  9244. text: text
  9245. }, context, error ? error.details : null, stats);
  9246. });
  9247. };
  9248. _proto.getCacheAge = function getCacheAge() {
  9249. var result = null;
  9250. if (this.response) {
  9251. var ageHeader = this.response.headers.get('age');
  9252. result = ageHeader ? parseFloat(ageHeader) : null;
  9253. }
  9254. return result;
  9255. };
  9256. _proto.getResponseHeader = function getResponseHeader(name) {
  9257. return this.response ? this.response.headers.get(name) : null;
  9258. };
  9259. _proto.loadProgressively = function loadProgressively(response, stats, context, highWaterMark, onProgress) {
  9260. if (highWaterMark === void 0) {
  9261. highWaterMark = 0;
  9262. }
  9263. var chunkCache = new ChunkCache();
  9264. var reader = response.body.getReader();
  9265. var pump = function pump() {
  9266. return reader.read().then(function (data) {
  9267. if (data.done) {
  9268. if (chunkCache.dataLength) {
  9269. onProgress(stats, context, chunkCache.flush(), response);
  9270. }
  9271. return Promise.resolve(new ArrayBuffer(0));
  9272. }
  9273. var chunk = data.value;
  9274. var len = chunk.length;
  9275. stats.loaded += len;
  9276. if (len < highWaterMark || chunkCache.dataLength) {
  9277. // The current chunk is too small to to be emitted or the cache already has data
  9278. // Push it to the cache
  9279. chunkCache.push(chunk);
  9280. if (chunkCache.dataLength >= highWaterMark) {
  9281. // flush in order to join the typed arrays
  9282. onProgress(stats, context, chunkCache.flush(), response);
  9283. }
  9284. } else {
  9285. // If there's nothing cached already, and the chache is large enough
  9286. // just emit the progress event
  9287. onProgress(stats, context, chunk, response);
  9288. }
  9289. return pump();
  9290. }).catch(function () {
  9291. /* aborted */
  9292. return Promise.reject();
  9293. });
  9294. };
  9295. return pump();
  9296. };
  9297. return FetchLoader;
  9298. }();
  9299. function getRequestParameters(context, signal) {
  9300. var initParams = {
  9301. method: 'GET',
  9302. mode: 'cors',
  9303. credentials: 'same-origin',
  9304. signal: signal,
  9305. headers: new self.Headers(_extends({}, context.headers))
  9306. };
  9307. if (context.rangeEnd) {
  9308. initParams.headers.set('Range', 'bytes=' + context.rangeStart + '-' + String(context.rangeEnd - 1));
  9309. }
  9310. return initParams;
  9311. }
  9312. function getByteRangeLength(byteRangeHeader) {
  9313. var result = BYTERANGE.exec(byteRangeHeader);
  9314. if (result) {
  9315. return parseInt(result[2]) - parseInt(result[1]) + 1;
  9316. }
  9317. }
  9318. function getContentLength(headers) {
  9319. var contentRange = headers.get('Content-Range');
  9320. if (contentRange) {
  9321. var byteRangeLength = getByteRangeLength(contentRange);
  9322. if (isFiniteNumber(byteRangeLength)) {
  9323. return byteRangeLength;
  9324. }
  9325. }
  9326. var contentLength = headers.get('Content-Length');
  9327. if (contentLength) {
  9328. return parseInt(contentLength);
  9329. }
  9330. }
  9331. function getRequest(context, initParams) {
  9332. return new self.Request(context.url, initParams);
  9333. }
  9334. var FetchError = /*#__PURE__*/function (_Error) {
  9335. _inheritsLoose(FetchError, _Error);
  9336. function FetchError(message, code, details) {
  9337. var _this2;
  9338. _this2 = _Error.call(this, message) || this;
  9339. _this2.code = void 0;
  9340. _this2.details = void 0;
  9341. _this2.code = code;
  9342. _this2.details = details;
  9343. return _this2;
  9344. }
  9345. return FetchError;
  9346. }( /*#__PURE__*/_wrapNativeSuper(Error));
  9347. /**
  9348. * @deprecated use fragLoadPolicy.default
  9349. */
  9350. /**
  9351. * @deprecated use manifestLoadPolicy.default and playlistLoadPolicy.default
  9352. */
  9353. var defaultLoadPolicy = {
  9354. maxTimeToFirstByteMs: 8000,
  9355. maxLoadTimeMs: 20000,
  9356. timeoutRetry: null,
  9357. errorRetry: null
  9358. };
  9359. /**
  9360. * @ignore
  9361. * If possible, keep hlsDefaultConfig shallow
  9362. * It is cloned whenever a new Hls instance is created, by keeping the config
  9363. * shallow the properties are cloned, and we don't end up manipulating the default
  9364. */
  9365. var hlsDefaultConfig = _objectSpread2(_objectSpread2({
  9366. autoStartLoad: true,
  9367. // used by stream-controller
  9368. startPosition: -1,
  9369. // used by stream-controller
  9370. defaultAudioCodec: undefined,
  9371. // used by stream-controller
  9372. debug: false,
  9373. // used by logger
  9374. capLevelOnFPSDrop: false,
  9375. // used by fps-controller
  9376. capLevelToPlayerSize: false,
  9377. // used by cap-level-controller
  9378. ignoreDevicePixelRatio: false,
  9379. // used by cap-level-controller
  9380. preferManagedMediaSource: true,
  9381. initialLiveManifestSize: 1,
  9382. // used by stream-controller
  9383. maxBufferLength: 30,
  9384. // used by stream-controller
  9385. backBufferLength: Infinity,
  9386. // used by buffer-controller
  9387. frontBufferFlushThreshold: Infinity,
  9388. maxBufferSize: 60 * 1000 * 1000,
  9389. // used by stream-controller
  9390. maxBufferHole: 0.1,
  9391. // used by stream-controller
  9392. highBufferWatchdogPeriod: 2,
  9393. // used by stream-controller
  9394. nudgeOffset: 0.1,
  9395. // used by stream-controller
  9396. nudgeMaxRetry: 3,
  9397. // used by stream-controller
  9398. maxFragLookUpTolerance: 0.25,
  9399. // used by stream-controller
  9400. liveSyncDurationCount: 3,
  9401. // used by latency-controller
  9402. liveMaxLatencyDurationCount: Infinity,
  9403. // used by latency-controller
  9404. liveSyncDuration: undefined,
  9405. // used by latency-controller
  9406. liveMaxLatencyDuration: undefined,
  9407. // used by latency-controller
  9408. maxLiveSyncPlaybackRate: 1,
  9409. // used by latency-controller
  9410. liveDurationInfinity: false,
  9411. // used by buffer-controller
  9412. /**
  9413. * @deprecated use backBufferLength
  9414. */
  9415. liveBackBufferLength: null,
  9416. // used by buffer-controller
  9417. maxMaxBufferLength: 600,
  9418. // used by stream-controller
  9419. enableWorker: true,
  9420. // used by transmuxer
  9421. workerPath: null,
  9422. // used by transmuxer
  9423. enableSoftwareAES: true,
  9424. // used by decrypter
  9425. startLevel: undefined,
  9426. // used by level-controller
  9427. startFragPrefetch: false,
  9428. // used by stream-controller
  9429. fpsDroppedMonitoringPeriod: 5000,
  9430. // used by fps-controller
  9431. fpsDroppedMonitoringThreshold: 0.2,
  9432. // used by fps-controller
  9433. appendErrorMaxRetry: 3,
  9434. // used by buffer-controller
  9435. loader: XhrLoader,
  9436. // loader: FetchLoader,
  9437. fLoader: undefined,
  9438. // used by fragment-loader
  9439. pLoader: undefined,
  9440. // used by playlist-loader
  9441. xhrSetup: undefined,
  9442. // used by xhr-loader
  9443. licenseXhrSetup: undefined,
  9444. // used by eme-controller
  9445. licenseResponseCallback: undefined,
  9446. // used by eme-controller
  9447. abrController: AbrController,
  9448. bufferController: BufferController,
  9449. capLevelController: CapLevelController,
  9450. errorController: ErrorController,
  9451. fpsController: FPSController,
  9452. stretchShortVideoTrack: false,
  9453. // used by mp4-remuxer
  9454. maxAudioFramesDrift: 1,
  9455. // used by mp4-remuxer
  9456. forceKeyFrameOnDiscontinuity: true,
  9457. // used by ts-demuxer
  9458. abrEwmaFastLive: 3,
  9459. // used by abr-controller
  9460. abrEwmaSlowLive: 9,
  9461. // used by abr-controller
  9462. abrEwmaFastVoD: 3,
  9463. // used by abr-controller
  9464. abrEwmaSlowVoD: 9,
  9465. // used by abr-controller
  9466. abrEwmaDefaultEstimate: 5e5,
  9467. // 500 kbps // used by abr-controller
  9468. abrEwmaDefaultEstimateMax: 5e6,
  9469. // 5 mbps
  9470. abrBandWidthFactor: 0.95,
  9471. // used by abr-controller
  9472. abrBandWidthUpFactor: 0.7,
  9473. // used by abr-controller
  9474. abrMaxWithRealBitrate: false,
  9475. // used by abr-controller
  9476. maxStarvationDelay: 4,
  9477. // used by abr-controller
  9478. maxLoadingDelay: 4,
  9479. // used by abr-controller
  9480. minAutoBitrate: 0,
  9481. // used by hls
  9482. emeEnabled: false,
  9483. // used by eme-controller
  9484. widevineLicenseUrl: undefined,
  9485. // used by eme-controller
  9486. drmSystems: {},
  9487. // used by eme-controller
  9488. drmSystemOptions: {},
  9489. // used by eme-controller
  9490. requestMediaKeySystemAccessFunc: null,
  9491. // used by eme-controller
  9492. testBandwidth: true,
  9493. progressive: false,
  9494. lowLatencyMode: true,
  9495. cmcd: undefined,
  9496. enableDateRangeMetadataCues: true,
  9497. enableEmsgMetadataCues: true,
  9498. enableID3MetadataCues: true,
  9499. useMediaCapabilities: false,
  9500. certLoadPolicy: {
  9501. default: defaultLoadPolicy
  9502. },
  9503. keyLoadPolicy: {
  9504. default: {
  9505. maxTimeToFirstByteMs: 8000,
  9506. maxLoadTimeMs: 20000,
  9507. timeoutRetry: {
  9508. maxNumRetry: 1,
  9509. retryDelayMs: 1000,
  9510. maxRetryDelayMs: 20000,
  9511. backoff: 'linear'
  9512. },
  9513. errorRetry: {
  9514. maxNumRetry: 8,
  9515. retryDelayMs: 1000,
  9516. maxRetryDelayMs: 20000,
  9517. backoff: 'linear'
  9518. }
  9519. }
  9520. },
  9521. manifestLoadPolicy: {
  9522. default: {
  9523. maxTimeToFirstByteMs: Infinity,
  9524. maxLoadTimeMs: 20000,
  9525. timeoutRetry: {
  9526. maxNumRetry: 2,
  9527. retryDelayMs: 0,
  9528. maxRetryDelayMs: 0
  9529. },
  9530. errorRetry: {
  9531. maxNumRetry: 1,
  9532. retryDelayMs: 1000,
  9533. maxRetryDelayMs: 8000
  9534. }
  9535. }
  9536. },
  9537. playlistLoadPolicy: {
  9538. default: {
  9539. maxTimeToFirstByteMs: 10000,
  9540. maxLoadTimeMs: 20000,
  9541. timeoutRetry: {
  9542. maxNumRetry: 2,
  9543. retryDelayMs: 0,
  9544. maxRetryDelayMs: 0
  9545. },
  9546. errorRetry: {
  9547. maxNumRetry: 2,
  9548. retryDelayMs: 1000,
  9549. maxRetryDelayMs: 8000
  9550. }
  9551. }
  9552. },
  9553. fragLoadPolicy: {
  9554. default: {
  9555. maxTimeToFirstByteMs: 10000,
  9556. maxLoadTimeMs: 120000,
  9557. timeoutRetry: {
  9558. maxNumRetry: 4,
  9559. retryDelayMs: 0,
  9560. maxRetryDelayMs: 0
  9561. },
  9562. errorRetry: {
  9563. maxNumRetry: 6,
  9564. retryDelayMs: 1000,
  9565. maxRetryDelayMs: 8000
  9566. }
  9567. }
  9568. },
  9569. steeringManifestLoadPolicy: {
  9570. default: {
  9571. maxTimeToFirstByteMs: 10000,
  9572. maxLoadTimeMs: 20000,
  9573. timeoutRetry: {
  9574. maxNumRetry: 2,
  9575. retryDelayMs: 0,
  9576. maxRetryDelayMs: 0
  9577. },
  9578. errorRetry: {
  9579. maxNumRetry: 1,
  9580. retryDelayMs: 1000,
  9581. maxRetryDelayMs: 8000
  9582. }
  9583. }
  9584. },
  9585. // These default settings are deprecated in favor of the above policies
  9586. // and are maintained for backwards compatibility
  9587. manifestLoadingTimeOut: 10000,
  9588. manifestLoadingMaxRetry: 1,
  9589. manifestLoadingRetryDelay: 1000,
  9590. manifestLoadingMaxRetryTimeout: 64000,
  9591. levelLoadingTimeOut: 10000,
  9592. levelLoadingMaxRetry: 4,
  9593. levelLoadingRetryDelay: 1000,
  9594. levelLoadingMaxRetryTimeout: 64000,
  9595. fragLoadingTimeOut: 20000,
  9596. fragLoadingMaxRetry: 6,
  9597. fragLoadingRetryDelay: 1000,
  9598. fragLoadingMaxRetryTimeout: 64000
  9599. }, timelineConfig()), {}, {
  9600. subtitleStreamController: undefined,
  9601. subtitleTrackController: undefined,
  9602. timelineController: undefined,
  9603. audioStreamController: undefined,
  9604. audioTrackController: undefined,
  9605. emeController: undefined,
  9606. cmcdController: undefined,
  9607. contentSteeringController: ContentSteeringController
  9608. });
  9609. function timelineConfig() {
  9610. return {
  9611. cueHandler: Cues,
  9612. // used by timeline-controller
  9613. enableWebVTT: false,
  9614. // used by timeline-controller
  9615. enableIMSC1: false,
  9616. // used by timeline-controller
  9617. enableCEA708Captions: false,
  9618. // used by timeline-controller
  9619. captionsTextTrack1Label: 'English',
  9620. // used by timeline-controller
  9621. captionsTextTrack1LanguageCode: 'en',
  9622. // used by timeline-controller
  9623. captionsTextTrack2Label: 'Spanish',
  9624. // used by timeline-controller
  9625. captionsTextTrack2LanguageCode: 'es',
  9626. // used by timeline-controller
  9627. captionsTextTrack3Label: 'Unknown CC',
  9628. // used by timeline-controller
  9629. captionsTextTrack3LanguageCode: '',
  9630. // used by timeline-controller
  9631. captionsTextTrack4Label: 'Unknown CC',
  9632. // used by timeline-controller
  9633. captionsTextTrack4LanguageCode: '',
  9634. // used by timeline-controller
  9635. renderTextTracksNatively: true
  9636. };
  9637. }
  9638. /**
  9639. * @ignore
  9640. */
  9641. function mergeConfig(defaultConfig, userConfig) {
  9642. if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {
  9643. throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");
  9644. }
  9645. if (userConfig.liveMaxLatencyDurationCount !== undefined && (userConfig.liveSyncDurationCount === undefined || userConfig.liveMaxLatencyDurationCount <= userConfig.liveSyncDurationCount)) {
  9646. throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');
  9647. }
  9648. if (userConfig.liveMaxLatencyDuration !== undefined && (userConfig.liveSyncDuration === undefined || userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)) {
  9649. throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');
  9650. }
  9651. var defaultsCopy = deepCpy(defaultConfig);
  9652. // Backwards compatibility with deprecated config values
  9653. var deprecatedSettingTypes = ['manifest', 'level', 'frag'];
  9654. var deprecatedSettings = ['TimeOut', 'MaxRetry', 'RetryDelay', 'MaxRetryTimeout'];
  9655. deprecatedSettingTypes.forEach(function (type) {
  9656. var policyName = (type === 'level' ? 'playlist' : type) + "LoadPolicy";
  9657. var policyNotSet = userConfig[policyName] === undefined;
  9658. var report = [];
  9659. deprecatedSettings.forEach(function (setting) {
  9660. var deprecatedSetting = type + "Loading" + setting;
  9661. var value = userConfig[deprecatedSetting];
  9662. if (value !== undefined && policyNotSet) {
  9663. report.push(deprecatedSetting);
  9664. var settings = defaultsCopy[policyName].default;
  9665. userConfig[policyName] = {
  9666. default: settings
  9667. };
  9668. switch (setting) {
  9669. case 'TimeOut':
  9670. settings.maxLoadTimeMs = value;
  9671. settings.maxTimeToFirstByteMs = value;
  9672. break;
  9673. case 'MaxRetry':
  9674. settings.errorRetry.maxNumRetry = value;
  9675. settings.timeoutRetry.maxNumRetry = value;
  9676. break;
  9677. case 'RetryDelay':
  9678. settings.errorRetry.retryDelayMs = value;
  9679. settings.timeoutRetry.retryDelayMs = value;
  9680. break;
  9681. case 'MaxRetryTimeout':
  9682. settings.errorRetry.maxRetryDelayMs = value;
  9683. settings.timeoutRetry.maxRetryDelayMs = value;
  9684. break;
  9685. }
  9686. }
  9687. });
  9688. if (report.length) {
  9689. logger.warn("hls.js config: \"" + report.join('", "') + "\" setting(s) are deprecated, use \"" + policyName + "\": " + JSON.stringify(userConfig[policyName]));
  9690. }
  9691. });
  9692. return _objectSpread2(_objectSpread2({}, defaultsCopy), userConfig);
  9693. }
  9694. function deepCpy(obj) {
  9695. if (obj && typeof obj === 'object') {
  9696. if (Array.isArray(obj)) {
  9697. return obj.map(deepCpy);
  9698. }
  9699. return Object.keys(obj).reduce(function (result, key) {
  9700. result[key] = deepCpy(obj[key]);
  9701. return result;
  9702. }, {});
  9703. }
  9704. return obj;
  9705. }
  9706. /**
  9707. * @ignore
  9708. */
  9709. function enableStreamingMode(config) {
  9710. var currentLoader = config.loader;
  9711. if (currentLoader !== FetchLoader && currentLoader !== XhrLoader) {
  9712. // If a developer has configured their own loader, respect that choice
  9713. logger.log('[config]: Custom loader detected, cannot enable progressive streaming');
  9714. config.progressive = false;
  9715. } else {
  9716. var canStreamProgressively = fetchSupported();
  9717. if (canStreamProgressively) {
  9718. config.loader = FetchLoader;
  9719. config.progressive = true;
  9720. config.enableSoftwareAES = true;
  9721. logger.log('[config]: Progressive streaming enabled, using FetchLoader');
  9722. }
  9723. }
  9724. }
  9725. var chromeOrFirefox;
  9726. var LevelController = /*#__PURE__*/function (_BasePlaylistControll) {
  9727. _inheritsLoose(LevelController, _BasePlaylistControll);
  9728. function LevelController(hls, contentSteeringController) {
  9729. var _this;
  9730. _this = _BasePlaylistControll.call(this, hls, '[level-controller]') || this;
  9731. _this._levels = [];
  9732. _this._firstLevel = -1;
  9733. _this._maxAutoLevel = -1;
  9734. _this._startLevel = void 0;
  9735. _this.currentLevel = null;
  9736. _this.currentLevelIndex = -1;
  9737. _this.manualLevelIndex = -1;
  9738. _this.steering = void 0;
  9739. _this.onParsedComplete = void 0;
  9740. _this.steering = contentSteeringController;
  9741. _this._registerListeners();
  9742. return _this;
  9743. }
  9744. var _proto = LevelController.prototype;
  9745. _proto._registerListeners = function _registerListeners() {
  9746. var hls = this.hls;
  9747. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  9748. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  9749. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  9750. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  9751. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  9752. hls.on(Events.ERROR, this.onError, this);
  9753. };
  9754. _proto._unregisterListeners = function _unregisterListeners() {
  9755. var hls = this.hls;
  9756. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  9757. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  9758. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  9759. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  9760. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  9761. hls.off(Events.ERROR, this.onError, this);
  9762. };
  9763. _proto.destroy = function destroy() {
  9764. this._unregisterListeners();
  9765. this.steering = null;
  9766. this.resetLevels();
  9767. _BasePlaylistControll.prototype.destroy.call(this);
  9768. };
  9769. _proto.stopLoad = function stopLoad() {
  9770. var levels = this._levels;
  9771. // clean up live level details to force reload them, and reset load errors
  9772. levels.forEach(function (level) {
  9773. level.loadError = 0;
  9774. level.fragmentError = 0;
  9775. });
  9776. _BasePlaylistControll.prototype.stopLoad.call(this);
  9777. };
  9778. _proto.resetLevels = function resetLevels() {
  9779. this._startLevel = undefined;
  9780. this.manualLevelIndex = -1;
  9781. this.currentLevelIndex = -1;
  9782. this.currentLevel = null;
  9783. this._levels = [];
  9784. this._maxAutoLevel = -1;
  9785. };
  9786. _proto.onManifestLoading = function onManifestLoading(event, data) {
  9787. this.resetLevels();
  9788. };
  9789. _proto.onManifestLoaded = function onManifestLoaded(event, data) {
  9790. var preferManagedMediaSource = this.hls.config.preferManagedMediaSource;
  9791. var levels = [];
  9792. var redundantSet = {};
  9793. var generatePathwaySet = {};
  9794. var resolutionFound = false;
  9795. var videoCodecFound = false;
  9796. var audioCodecFound = false;
  9797. data.levels.forEach(function (levelParsed) {
  9798. var _audioCodec, _videoCodec;
  9799. var attributes = levelParsed.attrs;
  9800. // erase audio codec info if browser does not support mp4a.40.34.
  9801. // demuxer will autodetect codec and fallback to mpeg/audio
  9802. var audioCodec = levelParsed.audioCodec,
  9803. videoCodec = levelParsed.videoCodec;
  9804. if (((_audioCodec = audioCodec) == null ? void 0 : _audioCodec.indexOf('mp4a.40.34')) !== -1) {
  9805. chromeOrFirefox || (chromeOrFirefox = /chrome|firefox/i.test(navigator.userAgent));
  9806. if (chromeOrFirefox) {
  9807. levelParsed.audioCodec = audioCodec = undefined;
  9808. }
  9809. }
  9810. if (audioCodec) {
  9811. levelParsed.audioCodec = audioCodec = getCodecCompatibleName(audioCodec, preferManagedMediaSource);
  9812. }
  9813. if (((_videoCodec = videoCodec) == null ? void 0 : _videoCodec.indexOf('avc1')) === 0) {
  9814. videoCodec = levelParsed.videoCodec = convertAVC1ToAVCOTI(videoCodec);
  9815. }
  9816. // only keep levels with supported audio/video codecs
  9817. var width = levelParsed.width,
  9818. height = levelParsed.height,
  9819. unknownCodecs = levelParsed.unknownCodecs;
  9820. resolutionFound || (resolutionFound = !!(width && height));
  9821. videoCodecFound || (videoCodecFound = !!videoCodec);
  9822. audioCodecFound || (audioCodecFound = !!audioCodec);
  9823. if (unknownCodecs != null && unknownCodecs.length || audioCodec && !areCodecsMediaSourceSupported(audioCodec, 'audio', preferManagedMediaSource) || videoCodec && !areCodecsMediaSourceSupported(videoCodec, 'video', preferManagedMediaSource)) {
  9824. return;
  9825. }
  9826. var CODECS = attributes.CODECS,
  9827. FRAMERATE = attributes['FRAME-RATE'],
  9828. HDCP = attributes['HDCP-LEVEL'],
  9829. PATHWAY = attributes['PATHWAY-ID'],
  9830. RESOLUTION = attributes.RESOLUTION,
  9831. VIDEO_RANGE = attributes['VIDEO-RANGE'];
  9832. var contentSteeringPrefix = (PATHWAY || '.') + "-";
  9833. var levelKey = "" + contentSteeringPrefix + levelParsed.bitrate + "-" + RESOLUTION + "-" + FRAMERATE + "-" + CODECS + "-" + VIDEO_RANGE + "-" + HDCP;
  9834. if (!redundantSet[levelKey]) {
  9835. var level = new Level(levelParsed);
  9836. redundantSet[levelKey] = level;
  9837. generatePathwaySet[levelKey] = 1;
  9838. levels.push(level);
  9839. } else if (redundantSet[levelKey].uri !== levelParsed.url && !levelParsed.attrs['PATHWAY-ID']) {
  9840. // Assign Pathway IDs to Redundant Streams (default Pathways is ".". Redundant Streams "..", "...", and so on.)
  9841. // Content Steering controller to handles Pathway fallback on error
  9842. var pathwayCount = generatePathwaySet[levelKey] += 1;
  9843. levelParsed.attrs['PATHWAY-ID'] = new Array(pathwayCount + 1).join('.');
  9844. var _level = new Level(levelParsed);
  9845. redundantSet[levelKey] = _level;
  9846. levels.push(_level);
  9847. } else {
  9848. redundantSet[levelKey].addGroupId('audio', attributes.AUDIO);
  9849. redundantSet[levelKey].addGroupId('text', attributes.SUBTITLES);
  9850. }
  9851. });
  9852. this.filterAndSortMediaOptions(levels, data, resolutionFound, videoCodecFound, audioCodecFound);
  9853. };
  9854. _proto.filterAndSortMediaOptions = function filterAndSortMediaOptions(filteredLevels, data, resolutionFound, videoCodecFound, audioCodecFound) {
  9855. var _this2 = this;
  9856. var audioTracks = [];
  9857. var subtitleTracks = [];
  9858. var levels = filteredLevels;
  9859. // remove audio-only and invalid video-range levels if we also have levels with video codecs or RESOLUTION signalled
  9860. if ((resolutionFound || videoCodecFound) && audioCodecFound) {
  9861. levels = levels.filter(function (_ref) {
  9862. var videoCodec = _ref.videoCodec,
  9863. videoRange = _ref.videoRange,
  9864. width = _ref.width,
  9865. height = _ref.height;
  9866. return (!!videoCodec || !!(width && height)) && isVideoRange(videoRange);
  9867. });
  9868. }
  9869. if (levels.length === 0) {
  9870. // Dispatch error after MANIFEST_LOADED is done propagating
  9871. Promise.resolve().then(function () {
  9872. if (_this2.hls) {
  9873. if (data.levels.length) {
  9874. _this2.warn("One or more CODECS in variant not supported: " + JSON.stringify(data.levels[0].attrs));
  9875. }
  9876. var error = new Error('no level with compatible codecs found in manifest');
  9877. _this2.hls.trigger(Events.ERROR, {
  9878. type: ErrorTypes.MEDIA_ERROR,
  9879. details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,
  9880. fatal: true,
  9881. url: data.url,
  9882. error: error,
  9883. reason: error.message
  9884. });
  9885. }
  9886. });
  9887. return;
  9888. }
  9889. if (data.audioTracks) {
  9890. var preferManagedMediaSource = this.hls.config.preferManagedMediaSource;
  9891. audioTracks = data.audioTracks.filter(function (track) {
  9892. return !track.audioCodec || areCodecsMediaSourceSupported(track.audioCodec, 'audio', preferManagedMediaSource);
  9893. });
  9894. // Assign ids after filtering as array indices by group-id
  9895. assignTrackIdsByGroup(audioTracks);
  9896. }
  9897. if (data.subtitles) {
  9898. subtitleTracks = data.subtitles;
  9899. assignTrackIdsByGroup(subtitleTracks);
  9900. }
  9901. // start bitrate is the first bitrate of the manifest
  9902. var unsortedLevels = levels.slice(0);
  9903. // sort levels from lowest to highest
  9904. levels.sort(function (a, b) {
  9905. if (a.attrs['HDCP-LEVEL'] !== b.attrs['HDCP-LEVEL']) {
  9906. return (a.attrs['HDCP-LEVEL'] || '') > (b.attrs['HDCP-LEVEL'] || '') ? 1 : -1;
  9907. }
  9908. // sort on height before bitrate for cap-level-controller
  9909. if (resolutionFound && a.height !== b.height) {
  9910. return a.height - b.height;
  9911. }
  9912. if (a.frameRate !== b.frameRate) {
  9913. return a.frameRate - b.frameRate;
  9914. }
  9915. if (a.videoRange !== b.videoRange) {
  9916. return VideoRangeValues.indexOf(a.videoRange) - VideoRangeValues.indexOf(b.videoRange);
  9917. }
  9918. if (a.videoCodec !== b.videoCodec) {
  9919. var valueA = videoCodecPreferenceValue(a.videoCodec);
  9920. var valueB = videoCodecPreferenceValue(b.videoCodec);
  9921. if (valueA !== valueB) {
  9922. return valueB - valueA;
  9923. }
  9924. }
  9925. if (a.uri === b.uri && a.codecSet !== b.codecSet) {
  9926. var _valueA = codecsSetSelectionPreferenceValue(a.codecSet);
  9927. var _valueB = codecsSetSelectionPreferenceValue(b.codecSet);
  9928. if (_valueA !== _valueB) {
  9929. return _valueB - _valueA;
  9930. }
  9931. }
  9932. if (a.averageBitrate !== b.averageBitrate) {
  9933. return a.averageBitrate - b.averageBitrate;
  9934. }
  9935. return 0;
  9936. });
  9937. var firstLevelInPlaylist = unsortedLevels[0];
  9938. if (this.steering) {
  9939. levels = this.steering.filterParsedLevels(levels);
  9940. if (levels.length !== unsortedLevels.length) {
  9941. for (var i = 0; i < unsortedLevels.length; i++) {
  9942. if (unsortedLevels[i].pathwayId === levels[0].pathwayId) {
  9943. firstLevelInPlaylist = unsortedLevels[i];
  9944. break;
  9945. }
  9946. }
  9947. }
  9948. }
  9949. this._levels = levels;
  9950. // find index of first level in sorted levels
  9951. for (var _i = 0; _i < levels.length; _i++) {
  9952. if (levels[_i] === firstLevelInPlaylist) {
  9953. var _this$hls$userConfig;
  9954. this._firstLevel = _i;
  9955. var firstLevelBitrate = firstLevelInPlaylist.bitrate;
  9956. var bandwidthEstimate = this.hls.bandwidthEstimate;
  9957. this.log("manifest loaded, " + levels.length + " level(s) found, first bitrate: " + firstLevelBitrate);
  9958. // Update default bwe to first variant bitrate as long it has not been configured or set
  9959. if (((_this$hls$userConfig = this.hls.userConfig) == null ? void 0 : _this$hls$userConfig.abrEwmaDefaultEstimate) === undefined) {
  9960. var startingBwEstimate = Math.min(firstLevelBitrate, this.hls.config.abrEwmaDefaultEstimateMax);
  9961. if (startingBwEstimate > bandwidthEstimate && bandwidthEstimate === hlsDefaultConfig.abrEwmaDefaultEstimate) {
  9962. this.hls.bandwidthEstimate = startingBwEstimate;
  9963. }
  9964. }
  9965. break;
  9966. }
  9967. }
  9968. // Audio is only alternate if manifest include a URI along with the audio group tag,
  9969. // and this is not an audio-only stream where levels contain audio-only
  9970. var audioOnly = audioCodecFound && !videoCodecFound;
  9971. var edata = {
  9972. levels: levels,
  9973. audioTracks: audioTracks,
  9974. subtitleTracks: subtitleTracks,
  9975. sessionData: data.sessionData,
  9976. sessionKeys: data.sessionKeys,
  9977. firstLevel: this._firstLevel,
  9978. stats: data.stats,
  9979. audio: audioCodecFound,
  9980. video: videoCodecFound,
  9981. altAudio: !audioOnly && audioTracks.some(function (t) {
  9982. return !!t.url;
  9983. })
  9984. };
  9985. this.hls.trigger(Events.MANIFEST_PARSED, edata);
  9986. // Initiate loading after all controllers have received MANIFEST_PARSED
  9987. if (this.hls.config.autoStartLoad || this.hls.forceStartLoad) {
  9988. this.hls.startLoad(this.hls.config.startPosition);
  9989. }
  9990. };
  9991. _proto.onError = function onError(event, data) {
  9992. if (data.fatal || !data.context) {
  9993. return;
  9994. }
  9995. if (data.context.type === PlaylistContextType.LEVEL && data.context.level === this.level) {
  9996. this.checkRetry(data);
  9997. }
  9998. }
  9999. // reset errors on the successful load of a fragment
  10000. ;
  10001. _proto.onFragBuffered = function onFragBuffered(event, _ref2) {
  10002. var frag = _ref2.frag;
  10003. if (frag !== undefined && frag.type === PlaylistLevelType.MAIN) {
  10004. var el = frag.elementaryStreams;
  10005. if (!Object.keys(el).some(function (type) {
  10006. return !!el[type];
  10007. })) {
  10008. return;
  10009. }
  10010. var level = this._levels[frag.level];
  10011. if (level != null && level.loadError) {
  10012. this.log("Resetting level error count of " + level.loadError + " on frag buffered");
  10013. level.loadError = 0;
  10014. }
  10015. }
  10016. };
  10017. _proto.onLevelLoaded = function onLevelLoaded(event, data) {
  10018. var _data$deliveryDirecti2;
  10019. var level = data.level,
  10020. details = data.details;
  10021. var curLevel = this._levels[level];
  10022. if (!curLevel) {
  10023. var _data$deliveryDirecti;
  10024. this.warn("Invalid level index " + level);
  10025. if ((_data$deliveryDirecti = data.deliveryDirectives) != null && _data$deliveryDirecti.skip) {
  10026. details.deltaUpdateFailed = true;
  10027. }
  10028. return;
  10029. }
  10030. // only process level loaded events matching with expected level
  10031. if (level === this.currentLevelIndex) {
  10032. // reset level load error counter on successful level loaded only if there is no issues with fragments
  10033. if (curLevel.fragmentError === 0) {
  10034. curLevel.loadError = 0;
  10035. }
  10036. this.playlistLoaded(level, data, curLevel.details);
  10037. } else if ((_data$deliveryDirecti2 = data.deliveryDirectives) != null && _data$deliveryDirecti2.skip) {
  10038. // received a delta playlist update that cannot be merged
  10039. details.deltaUpdateFailed = true;
  10040. }
  10041. };
  10042. _proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {
  10043. _BasePlaylistControll.prototype.loadPlaylist.call(this);
  10044. var currentLevelIndex = this.currentLevelIndex;
  10045. var currentLevel = this.currentLevel;
  10046. if (currentLevel && this.shouldLoadPlaylist(currentLevel)) {
  10047. var url = currentLevel.uri;
  10048. if (hlsUrlParameters) {
  10049. try {
  10050. url = hlsUrlParameters.addDirectives(url);
  10051. } catch (error) {
  10052. this.warn("Could not construct new URL with HLS Delivery Directives: " + error);
  10053. }
  10054. }
  10055. var pathwayId = currentLevel.attrs['PATHWAY-ID'];
  10056. this.log("Loading level index " + currentLevelIndex + ((hlsUrlParameters == null ? void 0 : hlsUrlParameters.msn) !== undefined ? ' at sn ' + hlsUrlParameters.msn + ' part ' + hlsUrlParameters.part : '') + " with" + (pathwayId ? ' Pathway ' + pathwayId : '') + " " + url);
  10057. // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
  10058. // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);
  10059. this.clearTimer();
  10060. this.hls.trigger(Events.LEVEL_LOADING, {
  10061. url: url,
  10062. level: currentLevelIndex,
  10063. pathwayId: currentLevel.attrs['PATHWAY-ID'],
  10064. id: 0,
  10065. // Deprecated Level urlId
  10066. deliveryDirectives: hlsUrlParameters || null
  10067. });
  10068. }
  10069. };
  10070. _proto.removeLevel = function removeLevel(levelIndex) {
  10071. var _this3 = this,
  10072. _this$currentLevel;
  10073. var levels = this._levels.filter(function (level, index) {
  10074. if (index !== levelIndex) {
  10075. return true;
  10076. }
  10077. if (_this3.steering) {
  10078. _this3.steering.removeLevel(level);
  10079. }
  10080. if (level === _this3.currentLevel) {
  10081. _this3.currentLevel = null;
  10082. _this3.currentLevelIndex = -1;
  10083. if (level.details) {
  10084. level.details.fragments.forEach(function (f) {
  10085. return f.level = -1;
  10086. });
  10087. }
  10088. }
  10089. return false;
  10090. });
  10091. reassignFragmentLevelIndexes(levels);
  10092. this._levels = levels;
  10093. if (this.currentLevelIndex > -1 && (_this$currentLevel = this.currentLevel) != null && _this$currentLevel.details) {
  10094. this.currentLevelIndex = this.currentLevel.details.fragments[0].level;
  10095. }
  10096. this.hls.trigger(Events.LEVELS_UPDATED, {
  10097. levels: levels
  10098. });
  10099. };
  10100. _proto.onLevelsUpdated = function onLevelsUpdated(event, _ref3) {
  10101. var levels = _ref3.levels;
  10102. this._levels = levels;
  10103. };
  10104. _proto.checkMaxAutoUpdated = function checkMaxAutoUpdated() {
  10105. var _this$hls = this.hls,
  10106. autoLevelCapping = _this$hls.autoLevelCapping,
  10107. maxAutoLevel = _this$hls.maxAutoLevel,
  10108. maxHdcpLevel = _this$hls.maxHdcpLevel;
  10109. if (this._maxAutoLevel !== maxAutoLevel) {
  10110. this._maxAutoLevel = maxAutoLevel;
  10111. this.hls.trigger(Events.MAX_AUTO_LEVEL_UPDATED, {
  10112. autoLevelCapping: autoLevelCapping,
  10113. levels: this.levels,
  10114. maxAutoLevel: maxAutoLevel,
  10115. minAutoLevel: this.hls.minAutoLevel,
  10116. maxHdcpLevel: maxHdcpLevel
  10117. });
  10118. }
  10119. };
  10120. _createClass(LevelController, [{
  10121. key: "levels",
  10122. get: function get() {
  10123. if (this._levels.length === 0) {
  10124. return null;
  10125. }
  10126. return this._levels;
  10127. }
  10128. }, {
  10129. key: "level",
  10130. get: function get() {
  10131. return this.currentLevelIndex;
  10132. },
  10133. set: function set(newLevel) {
  10134. var levels = this._levels;
  10135. if (levels.length === 0) {
  10136. return;
  10137. }
  10138. // check if level idx is valid
  10139. if (newLevel < 0 || newLevel >= levels.length) {
  10140. // invalid level id given, trigger error
  10141. var error = new Error('invalid level idx');
  10142. var fatal = newLevel < 0;
  10143. this.hls.trigger(Events.ERROR, {
  10144. type: ErrorTypes.OTHER_ERROR,
  10145. details: ErrorDetails.LEVEL_SWITCH_ERROR,
  10146. level: newLevel,
  10147. fatal: fatal,
  10148. error: error,
  10149. reason: error.message
  10150. });
  10151. if (fatal) {
  10152. return;
  10153. }
  10154. newLevel = Math.min(newLevel, levels.length - 1);
  10155. }
  10156. var lastLevelIndex = this.currentLevelIndex;
  10157. var lastLevel = this.currentLevel;
  10158. var lastPathwayId = lastLevel ? lastLevel.attrs['PATHWAY-ID'] : undefined;
  10159. var level = levels[newLevel];
  10160. var pathwayId = level.attrs['PATHWAY-ID'];
  10161. this.currentLevelIndex = newLevel;
  10162. this.currentLevel = level;
  10163. if (lastLevelIndex === newLevel && level.details && lastLevel && lastPathwayId === pathwayId) {
  10164. return;
  10165. }
  10166. 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 : ''));
  10167. var levelSwitchingData = {
  10168. level: newLevel,
  10169. attrs: level.attrs,
  10170. details: level.details,
  10171. bitrate: level.bitrate,
  10172. averageBitrate: level.averageBitrate,
  10173. maxBitrate: level.maxBitrate,
  10174. realBitrate: level.realBitrate,
  10175. width: level.width,
  10176. height: level.height,
  10177. codecSet: level.codecSet,
  10178. audioCodec: level.audioCodec,
  10179. videoCodec: level.videoCodec,
  10180. audioGroups: level.audioGroups,
  10181. subtitleGroups: level.subtitleGroups,
  10182. loaded: level.loaded,
  10183. loadError: level.loadError,
  10184. fragmentError: level.fragmentError,
  10185. name: level.name,
  10186. id: level.id,
  10187. uri: level.uri,
  10188. url: level.url,
  10189. urlId: 0,
  10190. audioGroupIds: level.audioGroupIds,
  10191. textGroupIds: level.textGroupIds
  10192. };
  10193. this.hls.trigger(Events.LEVEL_SWITCHING, levelSwitchingData);
  10194. // check if we need to load playlist for this level
  10195. var levelDetails = level.details;
  10196. if (!levelDetails || levelDetails.live) {
  10197. // level not retrieved yet, or live playlist we need to (re)load it
  10198. var hlsUrlParameters = this.switchParams(level.uri, lastLevel == null ? void 0 : lastLevel.details, levelDetails);
  10199. this.loadPlaylist(hlsUrlParameters);
  10200. }
  10201. }
  10202. }, {
  10203. key: "manualLevel",
  10204. get: function get() {
  10205. return this.manualLevelIndex;
  10206. },
  10207. set: function set(newLevel) {
  10208. this.manualLevelIndex = newLevel;
  10209. if (this._startLevel === undefined) {
  10210. this._startLevel = newLevel;
  10211. }
  10212. if (newLevel !== -1) {
  10213. this.level = newLevel;
  10214. }
  10215. }
  10216. }, {
  10217. key: "firstLevel",
  10218. get: function get() {
  10219. return this._firstLevel;
  10220. },
  10221. set: function set(newLevel) {
  10222. this._firstLevel = newLevel;
  10223. }
  10224. }, {
  10225. key: "startLevel",
  10226. get: function get() {
  10227. // Setting hls.startLevel (this._startLevel) overrides config.startLevel
  10228. if (this._startLevel === undefined) {
  10229. var configStartLevel = this.hls.config.startLevel;
  10230. if (configStartLevel !== undefined) {
  10231. return configStartLevel;
  10232. }
  10233. return this.hls.firstAutoLevel;
  10234. }
  10235. return this._startLevel;
  10236. },
  10237. set: function set(newLevel) {
  10238. this._startLevel = newLevel;
  10239. }
  10240. }, {
  10241. key: "nextLoadLevel",
  10242. get: function get() {
  10243. if (this.manualLevelIndex !== -1) {
  10244. return this.manualLevelIndex;
  10245. } else {
  10246. return this.hls.nextAutoLevel;
  10247. }
  10248. },
  10249. set: function set(nextLevel) {
  10250. this.level = nextLevel;
  10251. if (this.manualLevelIndex === -1) {
  10252. this.hls.nextAutoLevel = nextLevel;
  10253. }
  10254. }
  10255. }]);
  10256. return LevelController;
  10257. }(BasePlaylistController);
  10258. function assignTrackIdsByGroup(tracks) {
  10259. var groups = {};
  10260. tracks.forEach(function (track) {
  10261. var groupId = track.groupId || '';
  10262. track.id = groups[groupId] = groups[groupId] || 0;
  10263. groups[groupId]++;
  10264. });
  10265. }
  10266. var FragmentState = {
  10267. NOT_LOADED: "NOT_LOADED",
  10268. APPENDING: "APPENDING",
  10269. PARTIAL: "PARTIAL",
  10270. OK: "OK"
  10271. };
  10272. var FragmentTracker = /*#__PURE__*/function () {
  10273. function FragmentTracker(hls) {
  10274. this.activePartLists = Object.create(null);
  10275. this.endListFragments = Object.create(null);
  10276. this.fragments = Object.create(null);
  10277. this.timeRanges = Object.create(null);
  10278. this.bufferPadding = 0.2;
  10279. this.hls = void 0;
  10280. this.hasGaps = false;
  10281. this.hls = hls;
  10282. this._registerListeners();
  10283. }
  10284. var _proto = FragmentTracker.prototype;
  10285. _proto._registerListeners = function _registerListeners() {
  10286. var hls = this.hls;
  10287. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  10288. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  10289. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  10290. };
  10291. _proto._unregisterListeners = function _unregisterListeners() {
  10292. var hls = this.hls;
  10293. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  10294. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  10295. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  10296. };
  10297. _proto.destroy = function destroy() {
  10298. this._unregisterListeners();
  10299. // @ts-ignore
  10300. this.fragments =
  10301. // @ts-ignore
  10302. this.activePartLists =
  10303. // @ts-ignore
  10304. this.endListFragments = this.timeRanges = null;
  10305. }
  10306. /**
  10307. * Return a Fragment or Part with an appended range that matches the position and levelType
  10308. * Otherwise, return null
  10309. */;
  10310. _proto.getAppendedFrag = function getAppendedFrag(position, levelType) {
  10311. var activeParts = this.activePartLists[levelType];
  10312. if (activeParts) {
  10313. for (var i = activeParts.length; i--;) {
  10314. var activePart = activeParts[i];
  10315. if (!activePart) {
  10316. break;
  10317. }
  10318. var appendedPTS = activePart.end;
  10319. if (activePart.start <= position && appendedPTS !== null && position <= appendedPTS) {
  10320. return activePart;
  10321. }
  10322. }
  10323. }
  10324. return this.getBufferedFrag(position, levelType);
  10325. }
  10326. /**
  10327. * Return a buffered Fragment that matches the position and levelType.
  10328. * A buffered Fragment is one whose loading, parsing and appending is done (completed or "partial" meaning aborted).
  10329. * If not found any Fragment, return null
  10330. */;
  10331. _proto.getBufferedFrag = function getBufferedFrag(position, levelType) {
  10332. var fragments = this.fragments;
  10333. var keys = Object.keys(fragments);
  10334. for (var i = keys.length; i--;) {
  10335. var fragmentEntity = fragments[keys[i]];
  10336. if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === levelType && fragmentEntity.buffered) {
  10337. var frag = fragmentEntity.body;
  10338. if (frag.start <= position && position <= frag.end) {
  10339. return frag;
  10340. }
  10341. }
  10342. }
  10343. return null;
  10344. }
  10345. /**
  10346. * Partial fragments effected by coded frame eviction will be removed
  10347. * The browser will unload parts of the buffer to free up memory for new buffer data
  10348. * 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)
  10349. */;
  10350. _proto.detectEvictedFragments = function detectEvictedFragments(elementaryStream, timeRange, playlistType, appendedPart) {
  10351. var _this = this;
  10352. if (this.timeRanges) {
  10353. this.timeRanges[elementaryStream] = timeRange;
  10354. }
  10355. // Check if any flagged fragments have been unloaded
  10356. // excluding anything newer than appendedPartSn
  10357. var appendedPartSn = (appendedPart == null ? void 0 : appendedPart.fragment.sn) || -1;
  10358. Object.keys(this.fragments).forEach(function (key) {
  10359. var fragmentEntity = _this.fragments[key];
  10360. if (!fragmentEntity) {
  10361. return;
  10362. }
  10363. if (appendedPartSn >= fragmentEntity.body.sn) {
  10364. return;
  10365. }
  10366. if (!fragmentEntity.buffered && !fragmentEntity.loaded) {
  10367. if (fragmentEntity.body.type === playlistType) {
  10368. _this.removeFragment(fragmentEntity.body);
  10369. }
  10370. return;
  10371. }
  10372. var esData = fragmentEntity.range[elementaryStream];
  10373. if (!esData) {
  10374. return;
  10375. }
  10376. esData.time.some(function (time) {
  10377. var isNotBuffered = !_this.isTimeBuffered(time.startPTS, time.endPTS, timeRange);
  10378. if (isNotBuffered) {
  10379. // Unregister partial fragment as it needs to load again to be reused
  10380. _this.removeFragment(fragmentEntity.body);
  10381. }
  10382. return isNotBuffered;
  10383. });
  10384. });
  10385. }
  10386. /**
  10387. * Checks if the fragment passed in is loaded in the buffer properly
  10388. * Partially loaded fragments will be registered as a partial fragment
  10389. */;
  10390. _proto.detectPartialFragments = function detectPartialFragments(data) {
  10391. var _this2 = this;
  10392. var timeRanges = this.timeRanges;
  10393. var frag = data.frag,
  10394. part = data.part;
  10395. if (!timeRanges || frag.sn === 'initSegment') {
  10396. return;
  10397. }
  10398. var fragKey = getFragmentKey(frag);
  10399. var fragmentEntity = this.fragments[fragKey];
  10400. if (!fragmentEntity || fragmentEntity.buffered && frag.gap) {
  10401. return;
  10402. }
  10403. var isFragHint = !frag.relurl;
  10404. Object.keys(timeRanges).forEach(function (elementaryStream) {
  10405. var streamInfo = frag.elementaryStreams[elementaryStream];
  10406. if (!streamInfo) {
  10407. return;
  10408. }
  10409. var timeRange = timeRanges[elementaryStream];
  10410. var partial = isFragHint || streamInfo.partial === true;
  10411. fragmentEntity.range[elementaryStream] = _this2.getBufferedTimes(frag, part, partial, timeRange);
  10412. });
  10413. fragmentEntity.loaded = null;
  10414. if (Object.keys(fragmentEntity.range).length) {
  10415. fragmentEntity.buffered = true;
  10416. var endList = fragmentEntity.body.endList = frag.endList || fragmentEntity.body.endList;
  10417. if (endList) {
  10418. this.endListFragments[fragmentEntity.body.type] = fragmentEntity;
  10419. }
  10420. if (!isPartial(fragmentEntity)) {
  10421. // Remove older fragment parts from lookup after frag is tracked as buffered
  10422. this.removeParts(frag.sn - 1, frag.type);
  10423. }
  10424. } else {
  10425. // remove fragment if nothing was appended
  10426. this.removeFragment(fragmentEntity.body);
  10427. }
  10428. };
  10429. _proto.removeParts = function removeParts(snToKeep, levelType) {
  10430. var activeParts = this.activePartLists[levelType];
  10431. if (!activeParts) {
  10432. return;
  10433. }
  10434. this.activePartLists[levelType] = activeParts.filter(function (part) {
  10435. return part.fragment.sn >= snToKeep;
  10436. });
  10437. };
  10438. _proto.fragBuffered = function fragBuffered(frag, force) {
  10439. var fragKey = getFragmentKey(frag);
  10440. var fragmentEntity = this.fragments[fragKey];
  10441. if (!fragmentEntity && force) {
  10442. fragmentEntity = this.fragments[fragKey] = {
  10443. body: frag,
  10444. appendedPTS: null,
  10445. loaded: null,
  10446. buffered: false,
  10447. range: Object.create(null)
  10448. };
  10449. if (frag.gap) {
  10450. this.hasGaps = true;
  10451. }
  10452. }
  10453. if (fragmentEntity) {
  10454. fragmentEntity.loaded = null;
  10455. fragmentEntity.buffered = true;
  10456. }
  10457. };
  10458. _proto.getBufferedTimes = function getBufferedTimes(fragment, part, partial, timeRange) {
  10459. var buffered = {
  10460. time: [],
  10461. partial: partial
  10462. };
  10463. var startPTS = fragment.start;
  10464. var endPTS = fragment.end;
  10465. var minEndPTS = fragment.minEndPTS || endPTS;
  10466. var maxStartPTS = fragment.maxStartPTS || startPTS;
  10467. for (var i = 0; i < timeRange.length; i++) {
  10468. var startTime = timeRange.start(i) - this.bufferPadding;
  10469. var endTime = timeRange.end(i) + this.bufferPadding;
  10470. if (maxStartPTS >= startTime && minEndPTS <= endTime) {
  10471. // Fragment is entirely contained in buffer
  10472. // No need to check the other timeRange times since it's completely playable
  10473. buffered.time.push({
  10474. startPTS: Math.max(startPTS, timeRange.start(i)),
  10475. endPTS: Math.min(endPTS, timeRange.end(i))
  10476. });
  10477. break;
  10478. } else if (startPTS < endTime && endPTS > startTime) {
  10479. var start = Math.max(startPTS, timeRange.start(i));
  10480. var end = Math.min(endPTS, timeRange.end(i));
  10481. if (end > start) {
  10482. buffered.partial = true;
  10483. // Check for intersection with buffer
  10484. // Get playable sections of the fragment
  10485. buffered.time.push({
  10486. startPTS: start,
  10487. endPTS: end
  10488. });
  10489. }
  10490. } else if (endPTS <= startTime) {
  10491. // No need to check the rest of the timeRange as it is in order
  10492. break;
  10493. }
  10494. }
  10495. return buffered;
  10496. }
  10497. /**
  10498. * Gets the partial fragment for a certain time
  10499. */;
  10500. _proto.getPartialFragment = function getPartialFragment(time) {
  10501. var bestFragment = null;
  10502. var timePadding;
  10503. var startTime;
  10504. var endTime;
  10505. var bestOverlap = 0;
  10506. var bufferPadding = this.bufferPadding,
  10507. fragments = this.fragments;
  10508. Object.keys(fragments).forEach(function (key) {
  10509. var fragmentEntity = fragments[key];
  10510. if (!fragmentEntity) {
  10511. return;
  10512. }
  10513. if (isPartial(fragmentEntity)) {
  10514. startTime = fragmentEntity.body.start - bufferPadding;
  10515. endTime = fragmentEntity.body.end + bufferPadding;
  10516. if (time >= startTime && time <= endTime) {
  10517. // Use the fragment that has the most padding from start and end time
  10518. timePadding = Math.min(time - startTime, endTime - time);
  10519. if (bestOverlap <= timePadding) {
  10520. bestFragment = fragmentEntity.body;
  10521. bestOverlap = timePadding;
  10522. }
  10523. }
  10524. }
  10525. });
  10526. return bestFragment;
  10527. };
  10528. _proto.isEndListAppended = function isEndListAppended(type) {
  10529. var lastFragmentEntity = this.endListFragments[type];
  10530. return lastFragmentEntity !== undefined && (lastFragmentEntity.buffered || isPartial(lastFragmentEntity));
  10531. };
  10532. _proto.getState = function getState(fragment) {
  10533. var fragKey = getFragmentKey(fragment);
  10534. var fragmentEntity = this.fragments[fragKey];
  10535. if (fragmentEntity) {
  10536. if (!fragmentEntity.buffered) {
  10537. return FragmentState.APPENDING;
  10538. } else if (isPartial(fragmentEntity)) {
  10539. return FragmentState.PARTIAL;
  10540. } else {
  10541. return FragmentState.OK;
  10542. }
  10543. }
  10544. return FragmentState.NOT_LOADED;
  10545. };
  10546. _proto.isTimeBuffered = function isTimeBuffered(startPTS, endPTS, timeRange) {
  10547. var startTime;
  10548. var endTime;
  10549. for (var i = 0; i < timeRange.length; i++) {
  10550. startTime = timeRange.start(i) - this.bufferPadding;
  10551. endTime = timeRange.end(i) + this.bufferPadding;
  10552. if (startPTS >= startTime && endPTS <= endTime) {
  10553. return true;
  10554. }
  10555. if (endPTS <= startTime) {
  10556. // No need to check the rest of the timeRange as it is in order
  10557. return false;
  10558. }
  10559. }
  10560. return false;
  10561. };
  10562. _proto.onFragLoaded = function onFragLoaded(event, data) {
  10563. var frag = data.frag,
  10564. part = data.part;
  10565. // don't track initsegment (for which sn is not a number)
  10566. // don't track frags used for bitrateTest, they're irrelevant.
  10567. if (frag.sn === 'initSegment' || frag.bitrateTest) {
  10568. return;
  10569. }
  10570. // Fragment entity `loaded` FragLoadedData is null when loading parts
  10571. var loaded = part ? null : data;
  10572. var fragKey = getFragmentKey(frag);
  10573. this.fragments[fragKey] = {
  10574. body: frag,
  10575. appendedPTS: null,
  10576. loaded: loaded,
  10577. buffered: false,
  10578. range: Object.create(null)
  10579. };
  10580. };
  10581. _proto.onBufferAppended = function onBufferAppended(event, data) {
  10582. var _this3 = this;
  10583. var frag = data.frag,
  10584. part = data.part,
  10585. timeRanges = data.timeRanges;
  10586. if (frag.sn === 'initSegment') {
  10587. return;
  10588. }
  10589. var playlistType = frag.type;
  10590. if (part) {
  10591. var activeParts = this.activePartLists[playlistType];
  10592. if (!activeParts) {
  10593. this.activePartLists[playlistType] = activeParts = [];
  10594. }
  10595. activeParts.push(part);
  10596. }
  10597. // Store the latest timeRanges loaded in the buffer
  10598. this.timeRanges = timeRanges;
  10599. Object.keys(timeRanges).forEach(function (elementaryStream) {
  10600. var timeRange = timeRanges[elementaryStream];
  10601. _this3.detectEvictedFragments(elementaryStream, timeRange, playlistType, part);
  10602. });
  10603. };
  10604. _proto.onFragBuffered = function onFragBuffered(event, data) {
  10605. this.detectPartialFragments(data);
  10606. };
  10607. _proto.hasFragment = function hasFragment(fragment) {
  10608. var fragKey = getFragmentKey(fragment);
  10609. return !!this.fragments[fragKey];
  10610. };
  10611. _proto.hasParts = function hasParts(type) {
  10612. var _this$activePartLists;
  10613. return !!((_this$activePartLists = this.activePartLists[type]) != null && _this$activePartLists.length);
  10614. };
  10615. _proto.removeFragmentsInRange = function removeFragmentsInRange(start, end, playlistType, withGapOnly, unbufferedOnly) {
  10616. var _this4 = this;
  10617. if (withGapOnly && !this.hasGaps) {
  10618. return;
  10619. }
  10620. Object.keys(this.fragments).forEach(function (key) {
  10621. var fragmentEntity = _this4.fragments[key];
  10622. if (!fragmentEntity) {
  10623. return;
  10624. }
  10625. var frag = fragmentEntity.body;
  10626. if (frag.type !== playlistType || withGapOnly && !frag.gap) {
  10627. return;
  10628. }
  10629. if (frag.start < end && frag.end > start && (fragmentEntity.buffered || unbufferedOnly)) {
  10630. _this4.removeFragment(frag);
  10631. }
  10632. });
  10633. };
  10634. _proto.removeFragment = function removeFragment(fragment) {
  10635. var fragKey = getFragmentKey(fragment);
  10636. fragment.stats.loaded = 0;
  10637. fragment.clearElementaryStreamInfo();
  10638. var activeParts = this.activePartLists[fragment.type];
  10639. if (activeParts) {
  10640. var snToRemove = fragment.sn;
  10641. this.activePartLists[fragment.type] = activeParts.filter(function (part) {
  10642. return part.fragment.sn !== snToRemove;
  10643. });
  10644. }
  10645. delete this.fragments[fragKey];
  10646. if (fragment.endList) {
  10647. delete this.endListFragments[fragment.type];
  10648. }
  10649. };
  10650. _proto.removeAllFragments = function removeAllFragments() {
  10651. this.fragments = Object.create(null);
  10652. this.endListFragments = Object.create(null);
  10653. this.activePartLists = Object.create(null);
  10654. this.hasGaps = false;
  10655. };
  10656. return FragmentTracker;
  10657. }();
  10658. function isPartial(fragmentEntity) {
  10659. var _fragmentEntity$range, _fragmentEntity$range2, _fragmentEntity$range3;
  10660. 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));
  10661. }
  10662. function getFragmentKey(fragment) {
  10663. return fragment.type + "_" + fragment.level + "_" + fragment.sn;
  10664. }
  10665. var MIN_CHUNK_SIZE = Math.pow(2, 17); // 128kb
  10666. var FragmentLoader = /*#__PURE__*/function () {
  10667. function FragmentLoader(config) {
  10668. this.config = void 0;
  10669. this.loader = null;
  10670. this.partLoadTimeout = -1;
  10671. this.config = config;
  10672. }
  10673. var _proto = FragmentLoader.prototype;
  10674. _proto.destroy = function destroy() {
  10675. if (this.loader) {
  10676. this.loader.destroy();
  10677. this.loader = null;
  10678. }
  10679. };
  10680. _proto.abort = function abort() {
  10681. if (this.loader) {
  10682. // Abort the loader for current fragment. Only one may load at any given time
  10683. this.loader.abort();
  10684. }
  10685. };
  10686. _proto.load = function load(frag, _onProgress) {
  10687. var _this = this;
  10688. var url = frag.url;
  10689. if (!url) {
  10690. return Promise.reject(new LoadError({
  10691. type: ErrorTypes.NETWORK_ERROR,
  10692. details: ErrorDetails.FRAG_LOAD_ERROR,
  10693. fatal: false,
  10694. frag: frag,
  10695. error: new Error("Fragment does not have a " + (url ? 'part list' : 'url')),
  10696. networkDetails: null
  10697. }));
  10698. }
  10699. this.abort();
  10700. var config = this.config;
  10701. var FragmentILoader = config.fLoader;
  10702. var DefaultILoader = config.loader;
  10703. return new Promise(function (resolve, reject) {
  10704. if (_this.loader) {
  10705. _this.loader.destroy();
  10706. }
  10707. if (frag.gap) {
  10708. if (frag.tagList.some(function (tags) {
  10709. return tags[0] === 'GAP';
  10710. })) {
  10711. reject(createGapLoadError(frag));
  10712. return;
  10713. } else {
  10714. // Reset temporary treatment as GAP tag
  10715. frag.gap = false;
  10716. }
  10717. }
  10718. var loader = _this.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  10719. var loaderContext = createLoaderContext(frag);
  10720. var loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
  10721. var loaderConfig = {
  10722. loadPolicy: loadPolicy,
  10723. timeout: loadPolicy.maxLoadTimeMs,
  10724. maxRetry: 0,
  10725. retryDelay: 0,
  10726. maxRetryDelay: 0,
  10727. highWaterMark: frag.sn === 'initSegment' ? Infinity : MIN_CHUNK_SIZE
  10728. };
  10729. // Assign frag stats to the loader's stats reference
  10730. frag.stats = loader.stats;
  10731. loader.load(loaderContext, loaderConfig, {
  10732. onSuccess: function onSuccess(response, stats, context, networkDetails) {
  10733. _this.resetLoader(frag, loader);
  10734. var payload = response.data;
  10735. if (context.resetIV && frag.decryptdata) {
  10736. frag.decryptdata.iv = new Uint8Array(payload.slice(0, 16));
  10737. payload = payload.slice(16);
  10738. }
  10739. resolve({
  10740. frag: frag,
  10741. part: null,
  10742. payload: payload,
  10743. networkDetails: networkDetails
  10744. });
  10745. },
  10746. onError: function onError(response, context, networkDetails, stats) {
  10747. _this.resetLoader(frag, loader);
  10748. reject(new LoadError({
  10749. type: ErrorTypes.NETWORK_ERROR,
  10750. details: ErrorDetails.FRAG_LOAD_ERROR,
  10751. fatal: false,
  10752. frag: frag,
  10753. response: _objectSpread2({
  10754. url: url,
  10755. data: undefined
  10756. }, response),
  10757. error: new Error("HTTP Error " + response.code + " " + response.text),
  10758. networkDetails: networkDetails,
  10759. stats: stats
  10760. }));
  10761. },
  10762. onAbort: function onAbort(stats, context, networkDetails) {
  10763. _this.resetLoader(frag, loader);
  10764. reject(new LoadError({
  10765. type: ErrorTypes.NETWORK_ERROR,
  10766. details: ErrorDetails.INTERNAL_ABORTED,
  10767. fatal: false,
  10768. frag: frag,
  10769. error: new Error('Aborted'),
  10770. networkDetails: networkDetails,
  10771. stats: stats
  10772. }));
  10773. },
  10774. onTimeout: function onTimeout(stats, context, networkDetails) {
  10775. _this.resetLoader(frag, loader);
  10776. reject(new LoadError({
  10777. type: ErrorTypes.NETWORK_ERROR,
  10778. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  10779. fatal: false,
  10780. frag: frag,
  10781. error: new Error("Timeout after " + loaderConfig.timeout + "ms"),
  10782. networkDetails: networkDetails,
  10783. stats: stats
  10784. }));
  10785. },
  10786. onProgress: function onProgress(stats, context, data, networkDetails) {
  10787. if (_onProgress) {
  10788. _onProgress({
  10789. frag: frag,
  10790. part: null,
  10791. payload: data,
  10792. networkDetails: networkDetails
  10793. });
  10794. }
  10795. }
  10796. });
  10797. });
  10798. };
  10799. _proto.loadPart = function loadPart(frag, part, onProgress) {
  10800. var _this2 = this;
  10801. this.abort();
  10802. var config = this.config;
  10803. var FragmentILoader = config.fLoader;
  10804. var DefaultILoader = config.loader;
  10805. return new Promise(function (resolve, reject) {
  10806. if (_this2.loader) {
  10807. _this2.loader.destroy();
  10808. }
  10809. if (frag.gap || part.gap) {
  10810. reject(createGapLoadError(frag, part));
  10811. return;
  10812. }
  10813. var loader = _this2.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  10814. var loaderContext = createLoaderContext(frag, part);
  10815. // Should we define another load policy for parts?
  10816. var loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
  10817. var loaderConfig = {
  10818. loadPolicy: loadPolicy,
  10819. timeout: loadPolicy.maxLoadTimeMs,
  10820. maxRetry: 0,
  10821. retryDelay: 0,
  10822. maxRetryDelay: 0,
  10823. highWaterMark: MIN_CHUNK_SIZE
  10824. };
  10825. // Assign part stats to the loader's stats reference
  10826. part.stats = loader.stats;
  10827. loader.load(loaderContext, loaderConfig, {
  10828. onSuccess: function onSuccess(response, stats, context, networkDetails) {
  10829. _this2.resetLoader(frag, loader);
  10830. _this2.updateStatsFromPart(frag, part);
  10831. var partLoadedData = {
  10832. frag: frag,
  10833. part: part,
  10834. payload: response.data,
  10835. networkDetails: networkDetails
  10836. };
  10837. onProgress(partLoadedData);
  10838. resolve(partLoadedData);
  10839. },
  10840. onError: function onError(response, context, networkDetails, stats) {
  10841. _this2.resetLoader(frag, loader);
  10842. reject(new LoadError({
  10843. type: ErrorTypes.NETWORK_ERROR,
  10844. details: ErrorDetails.FRAG_LOAD_ERROR,
  10845. fatal: false,
  10846. frag: frag,
  10847. part: part,
  10848. response: _objectSpread2({
  10849. url: loaderContext.url,
  10850. data: undefined
  10851. }, response),
  10852. error: new Error("HTTP Error " + response.code + " " + response.text),
  10853. networkDetails: networkDetails,
  10854. stats: stats
  10855. }));
  10856. },
  10857. onAbort: function onAbort(stats, context, networkDetails) {
  10858. frag.stats.aborted = part.stats.aborted;
  10859. _this2.resetLoader(frag, loader);
  10860. reject(new LoadError({
  10861. type: ErrorTypes.NETWORK_ERROR,
  10862. details: ErrorDetails.INTERNAL_ABORTED,
  10863. fatal: false,
  10864. frag: frag,
  10865. part: part,
  10866. error: new Error('Aborted'),
  10867. networkDetails: networkDetails,
  10868. stats: stats
  10869. }));
  10870. },
  10871. onTimeout: function onTimeout(stats, context, networkDetails) {
  10872. _this2.resetLoader(frag, loader);
  10873. reject(new LoadError({
  10874. type: ErrorTypes.NETWORK_ERROR,
  10875. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  10876. fatal: false,
  10877. frag: frag,
  10878. part: part,
  10879. error: new Error("Timeout after " + loaderConfig.timeout + "ms"),
  10880. networkDetails: networkDetails,
  10881. stats: stats
  10882. }));
  10883. }
  10884. });
  10885. });
  10886. };
  10887. _proto.updateStatsFromPart = function updateStatsFromPart(frag, part) {
  10888. var fragStats = frag.stats;
  10889. var partStats = part.stats;
  10890. var partTotal = partStats.total;
  10891. fragStats.loaded += partStats.loaded;
  10892. if (partTotal) {
  10893. var estTotalParts = Math.round(frag.duration / part.duration);
  10894. var estLoadedParts = Math.min(Math.round(fragStats.loaded / partTotal), estTotalParts);
  10895. var estRemainingParts = estTotalParts - estLoadedParts;
  10896. var estRemainingBytes = estRemainingParts * Math.round(fragStats.loaded / estLoadedParts);
  10897. fragStats.total = fragStats.loaded + estRemainingBytes;
  10898. } else {
  10899. fragStats.total = Math.max(fragStats.loaded, fragStats.total);
  10900. }
  10901. var fragLoading = fragStats.loading;
  10902. var partLoading = partStats.loading;
  10903. if (fragLoading.start) {
  10904. // add to fragment loader latency
  10905. fragLoading.first += partLoading.first - partLoading.start;
  10906. } else {
  10907. fragLoading.start = partLoading.start;
  10908. fragLoading.first = partLoading.first;
  10909. }
  10910. fragLoading.end = partLoading.end;
  10911. };
  10912. _proto.resetLoader = function resetLoader(frag, loader) {
  10913. frag.loader = null;
  10914. if (this.loader === loader) {
  10915. self.clearTimeout(this.partLoadTimeout);
  10916. this.loader = null;
  10917. }
  10918. loader.destroy();
  10919. };
  10920. return FragmentLoader;
  10921. }();
  10922. function createLoaderContext(frag, part) {
  10923. if (part === void 0) {
  10924. part = null;
  10925. }
  10926. var segment = part || frag;
  10927. var loaderContext = {
  10928. frag: frag,
  10929. part: part,
  10930. responseType: 'arraybuffer',
  10931. url: segment.url,
  10932. headers: {},
  10933. rangeStart: 0,
  10934. rangeEnd: 0
  10935. };
  10936. var start = segment.byteRangeStartOffset;
  10937. var end = segment.byteRangeEndOffset;
  10938. if (isFiniteNumber(start) && isFiniteNumber(end)) {
  10939. var _frag$decryptdata;
  10940. var byteRangeStart = start;
  10941. var byteRangeEnd = end;
  10942. if (frag.sn === 'initSegment' && ((_frag$decryptdata = frag.decryptdata) == null ? void 0 : _frag$decryptdata.method) === 'AES-128') {
  10943. // MAP segment encrypted with method 'AES-128', when served with HTTP Range,
  10944. // has the unencrypted size specified in the range.
  10945. // Ref: https://tools.ietf.org/html/draft-pantos-hls-rfc8216bis-08#section-6.3.6
  10946. var fragmentLen = end - start;
  10947. if (fragmentLen % 16) {
  10948. byteRangeEnd = end + (16 - fragmentLen % 16);
  10949. }
  10950. if (start !== 0) {
  10951. loaderContext.resetIV = true;
  10952. byteRangeStart = start - 16;
  10953. }
  10954. }
  10955. loaderContext.rangeStart = byteRangeStart;
  10956. loaderContext.rangeEnd = byteRangeEnd;
  10957. }
  10958. return loaderContext;
  10959. }
  10960. function createGapLoadError(frag, part) {
  10961. var error = new Error("GAP " + (frag.gap ? 'tag' : 'attribute') + " found");
  10962. var errorData = {
  10963. type: ErrorTypes.MEDIA_ERROR,
  10964. details: ErrorDetails.FRAG_GAP,
  10965. fatal: false,
  10966. frag: frag,
  10967. error: error,
  10968. networkDetails: null
  10969. };
  10970. if (part) {
  10971. errorData.part = part;
  10972. }
  10973. (part ? part : frag).stats.aborted = true;
  10974. return new LoadError(errorData);
  10975. }
  10976. var LoadError = /*#__PURE__*/function (_Error) {
  10977. _inheritsLoose(LoadError, _Error);
  10978. function LoadError(data) {
  10979. var _this3;
  10980. _this3 = _Error.call(this, data.error.message) || this;
  10981. _this3.data = void 0;
  10982. _this3.data = data;
  10983. return _this3;
  10984. }
  10985. return LoadError;
  10986. }( /*#__PURE__*/_wrapNativeSuper(Error));
  10987. var KeyLoader = /*#__PURE__*/function () {
  10988. function KeyLoader(config) {
  10989. this.config = void 0;
  10990. this.keyUriToKeyInfo = {};
  10991. this.emeController = null;
  10992. this.config = config;
  10993. }
  10994. var _proto = KeyLoader.prototype;
  10995. _proto.abort = function abort(type) {
  10996. for (var uri in this.keyUriToKeyInfo) {
  10997. var loader = this.keyUriToKeyInfo[uri].loader;
  10998. if (loader) {
  10999. var _loader$context;
  11000. if (type && type !== ((_loader$context = loader.context) == null ? void 0 : _loader$context.frag.type)) {
  11001. return;
  11002. }
  11003. loader.abort();
  11004. }
  11005. }
  11006. };
  11007. _proto.detach = function detach() {
  11008. for (var uri in this.keyUriToKeyInfo) {
  11009. var keyInfo = this.keyUriToKeyInfo[uri];
  11010. // Remove cached EME keys on detach
  11011. if (keyInfo.mediaKeySessionContext || keyInfo.decryptdata.isCommonEncryption) {
  11012. delete this.keyUriToKeyInfo[uri];
  11013. }
  11014. }
  11015. };
  11016. _proto.destroy = function destroy() {
  11017. this.detach();
  11018. for (var uri in this.keyUriToKeyInfo) {
  11019. var loader = this.keyUriToKeyInfo[uri].loader;
  11020. if (loader) {
  11021. loader.destroy();
  11022. }
  11023. }
  11024. this.keyUriToKeyInfo = {};
  11025. };
  11026. _proto.createKeyLoadError = function createKeyLoadError(frag, details, error, networkDetails, response) {
  11027. if (details === void 0) {
  11028. details = ErrorDetails.KEY_LOAD_ERROR;
  11029. }
  11030. return new LoadError({
  11031. type: ErrorTypes.NETWORK_ERROR,
  11032. details: details,
  11033. fatal: false,
  11034. frag: frag,
  11035. response: response,
  11036. error: error,
  11037. networkDetails: networkDetails
  11038. });
  11039. };
  11040. _proto.loadClear = function loadClear(loadingFrag, encryptedFragments) {
  11041. var _this = this;
  11042. if (this.emeController && this.config.emeEnabled) {
  11043. // access key-system with nearest key on start (loaidng frag is unencrypted)
  11044. var sn = loadingFrag.sn,
  11045. cc = loadingFrag.cc;
  11046. var _loop = function _loop() {
  11047. var frag = encryptedFragments[i];
  11048. if (cc <= frag.cc && (sn === 'initSegment' || frag.sn === 'initSegment' || sn < frag.sn)) {
  11049. _this.emeController.selectKeySystemFormat(frag).then(function (keySystemFormat) {
  11050. frag.setKeyFormat(keySystemFormat);
  11051. });
  11052. return 1; // break
  11053. }
  11054. };
  11055. for (var i = 0; i < encryptedFragments.length; i++) {
  11056. if (_loop()) break;
  11057. }
  11058. }
  11059. };
  11060. _proto.load = function load(frag) {
  11061. var _this2 = this;
  11062. if (!frag.decryptdata && frag.encrypted && this.emeController) {
  11063. // Multiple keys, but none selected, resolve in eme-controller
  11064. return this.emeController.selectKeySystemFormat(frag).then(function (keySystemFormat) {
  11065. return _this2.loadInternal(frag, keySystemFormat);
  11066. });
  11067. }
  11068. return this.loadInternal(frag);
  11069. };
  11070. _proto.loadInternal = function loadInternal(frag, keySystemFormat) {
  11071. var _keyInfo, _keyInfo2;
  11072. if (keySystemFormat) {
  11073. frag.setKeyFormat(keySystemFormat);
  11074. }
  11075. var decryptdata = frag.decryptdata;
  11076. if (!decryptdata) {
  11077. var error = new Error(keySystemFormat ? "Expected frag.decryptdata to be defined after setting format " + keySystemFormat : 'Missing decryption data on fragment in onKeyLoading');
  11078. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, error));
  11079. }
  11080. var uri = decryptdata.uri;
  11081. if (!uri) {
  11082. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error("Invalid key URI: \"" + uri + "\"")));
  11083. }
  11084. var keyInfo = this.keyUriToKeyInfo[uri];
  11085. if ((_keyInfo = keyInfo) != null && _keyInfo.decryptdata.key) {
  11086. decryptdata.key = keyInfo.decryptdata.key;
  11087. return Promise.resolve({
  11088. frag: frag,
  11089. keyInfo: keyInfo
  11090. });
  11091. }
  11092. // Return key load promise as long as it does not have a mediakey session with an unusable key status
  11093. if ((_keyInfo2 = keyInfo) != null && _keyInfo2.keyLoadPromise) {
  11094. var _keyInfo$mediaKeySess;
  11095. switch ((_keyInfo$mediaKeySess = keyInfo.mediaKeySessionContext) == null ? void 0 : _keyInfo$mediaKeySess.keyStatus) {
  11096. case undefined:
  11097. case 'status-pending':
  11098. case 'usable':
  11099. case 'usable-in-future':
  11100. return keyInfo.keyLoadPromise.then(function (keyLoadedData) {
  11101. // Return the correct fragment with updated decryptdata key and loaded keyInfo
  11102. decryptdata.key = keyLoadedData.keyInfo.decryptdata.key;
  11103. return {
  11104. frag: frag,
  11105. keyInfo: keyInfo
  11106. };
  11107. });
  11108. }
  11109. // If we have a key session and status and it is not pending or usable, continue
  11110. // This will go back to the eme-controller for expired keys to get a new keyLoadPromise
  11111. }
  11112. // Load the key or return the loading promise
  11113. keyInfo = this.keyUriToKeyInfo[uri] = {
  11114. decryptdata: decryptdata,
  11115. keyLoadPromise: null,
  11116. loader: null,
  11117. mediaKeySessionContext: null
  11118. };
  11119. switch (decryptdata.method) {
  11120. case 'ISO-23001-7':
  11121. case 'SAMPLE-AES':
  11122. case 'SAMPLE-AES-CENC':
  11123. case 'SAMPLE-AES-CTR':
  11124. if (decryptdata.keyFormat === 'identity') {
  11125. // loadKeyHTTP handles http(s) and data URLs
  11126. return this.loadKeyHTTP(keyInfo, frag);
  11127. }
  11128. return this.loadKeyEME(keyInfo, frag);
  11129. case 'AES-128':
  11130. return this.loadKeyHTTP(keyInfo, frag);
  11131. default:
  11132. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error("Key supplied with unsupported METHOD: \"" + decryptdata.method + "\"")));
  11133. }
  11134. };
  11135. _proto.loadKeyEME = function loadKeyEME(keyInfo, frag) {
  11136. var keyLoadedData = {
  11137. frag: frag,
  11138. keyInfo: keyInfo
  11139. };
  11140. if (this.emeController && this.config.emeEnabled) {
  11141. var keySessionContextPromise = this.emeController.loadKey(keyLoadedData);
  11142. if (keySessionContextPromise) {
  11143. return (keyInfo.keyLoadPromise = keySessionContextPromise.then(function (keySessionContext) {
  11144. keyInfo.mediaKeySessionContext = keySessionContext;
  11145. return keyLoadedData;
  11146. })).catch(function (error) {
  11147. // Remove promise for license renewal or retry
  11148. keyInfo.keyLoadPromise = null;
  11149. throw error;
  11150. });
  11151. }
  11152. }
  11153. return Promise.resolve(keyLoadedData);
  11154. };
  11155. _proto.loadKeyHTTP = function loadKeyHTTP(keyInfo, frag) {
  11156. var _this3 = this;
  11157. var config = this.config;
  11158. var Loader = config.loader;
  11159. var keyLoader = new Loader(config);
  11160. frag.keyLoader = keyInfo.loader = keyLoader;
  11161. return keyInfo.keyLoadPromise = new Promise(function (resolve, reject) {
  11162. var loaderContext = {
  11163. keyInfo: keyInfo,
  11164. frag: frag,
  11165. responseType: 'arraybuffer',
  11166. url: keyInfo.decryptdata.uri
  11167. };
  11168. // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,
  11169. // key-loader will trigger an error and rely on stream-controller to handle retry logic.
  11170. // this will also align retry logic with fragment-loader
  11171. var loadPolicy = config.keyLoadPolicy.default;
  11172. var loaderConfig = {
  11173. loadPolicy: loadPolicy,
  11174. timeout: loadPolicy.maxLoadTimeMs,
  11175. maxRetry: 0,
  11176. retryDelay: 0,
  11177. maxRetryDelay: 0
  11178. };
  11179. var loaderCallbacks = {
  11180. onSuccess: function onSuccess(response, stats, context, networkDetails) {
  11181. var frag = context.frag,
  11182. keyInfo = context.keyInfo,
  11183. uri = context.url;
  11184. if (!frag.decryptdata || keyInfo !== _this3.keyUriToKeyInfo[uri]) {
  11185. return reject(_this3.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error('after key load, decryptdata unset or changed'), networkDetails));
  11186. }
  11187. keyInfo.decryptdata.key = frag.decryptdata.key = new Uint8Array(response.data);
  11188. // detach fragment key loader on load success
  11189. frag.keyLoader = null;
  11190. keyInfo.loader = null;
  11191. resolve({
  11192. frag: frag,
  11193. keyInfo: keyInfo
  11194. });
  11195. },
  11196. onError: function onError(response, context, networkDetails, stats) {
  11197. _this3.resetLoader(context);
  11198. reject(_this3.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error("HTTP Error " + response.code + " loading key " + response.text), networkDetails, _objectSpread2({
  11199. url: loaderContext.url,
  11200. data: undefined
  11201. }, response)));
  11202. },
  11203. onTimeout: function onTimeout(stats, context, networkDetails) {
  11204. _this3.resetLoader(context);
  11205. reject(_this3.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_TIMEOUT, new Error('key loading timed out'), networkDetails));
  11206. },
  11207. onAbort: function onAbort(stats, context, networkDetails) {
  11208. _this3.resetLoader(context);
  11209. reject(_this3.createKeyLoadError(frag, ErrorDetails.INTERNAL_ABORTED, new Error('key loading aborted'), networkDetails));
  11210. }
  11211. };
  11212. keyLoader.load(loaderContext, loaderConfig, loaderCallbacks);
  11213. });
  11214. };
  11215. _proto.resetLoader = function resetLoader(context) {
  11216. var frag = context.frag,
  11217. keyInfo = context.keyInfo,
  11218. uri = context.url;
  11219. var loader = keyInfo.loader;
  11220. if (frag.keyLoader === loader) {
  11221. frag.keyLoader = null;
  11222. keyInfo.loader = null;
  11223. }
  11224. delete this.keyUriToKeyInfo[uri];
  11225. if (loader) {
  11226. loader.destroy();
  11227. }
  11228. };
  11229. return KeyLoader;
  11230. }();
  11231. /**
  11232. * @ignore
  11233. * Sub-class specialization of EventHandler base class.
  11234. *
  11235. * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,
  11236. * scheduled asynchroneously, avoiding recursive calls in the same tick.
  11237. *
  11238. * The task itself is implemented in `doTick`. It can be requested and called for single execution
  11239. * using the `tick` method.
  11240. *
  11241. * It will be assured that the task execution method (`tick`) only gets called once per main loop "tick",
  11242. * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.
  11243. *
  11244. * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,
  11245. * and cancelled with `clearNextTick`.
  11246. *
  11247. * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).
  11248. *
  11249. * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.
  11250. *
  11251. * Further explanations:
  11252. *
  11253. * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously
  11254. * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.
  11255. *
  11256. * When the task execution (`tick` method) is called in re-entrant way this is detected and
  11257. * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further
  11258. * task processing on the next main loop iteration (also known as "next tick" in the Node/JS runtime lingo).
  11259. */
  11260. var TaskLoop = /*#__PURE__*/function () {
  11261. function TaskLoop() {
  11262. this._boundTick = void 0;
  11263. this._tickTimer = null;
  11264. this._tickInterval = null;
  11265. this._tickCallCount = 0;
  11266. this._boundTick = this.tick.bind(this);
  11267. }
  11268. var _proto = TaskLoop.prototype;
  11269. _proto.destroy = function destroy() {
  11270. this.onHandlerDestroying();
  11271. this.onHandlerDestroyed();
  11272. };
  11273. _proto.onHandlerDestroying = function onHandlerDestroying() {
  11274. // clear all timers before unregistering from event bus
  11275. this.clearNextTick();
  11276. this.clearInterval();
  11277. };
  11278. _proto.onHandlerDestroyed = function onHandlerDestroyed() {};
  11279. _proto.hasInterval = function hasInterval() {
  11280. return !!this._tickInterval;
  11281. };
  11282. _proto.hasNextTick = function hasNextTick() {
  11283. return !!this._tickTimer;
  11284. }
  11285. /**
  11286. * @param millis - Interval time (ms)
  11287. * @eturns True when interval has been scheduled, false when already scheduled (no effect)
  11288. */;
  11289. _proto.setInterval = function setInterval(millis) {
  11290. if (!this._tickInterval) {
  11291. this._tickCallCount = 0;
  11292. this._tickInterval = self.setInterval(this._boundTick, millis);
  11293. return true;
  11294. }
  11295. return false;
  11296. }
  11297. /**
  11298. * @returns True when interval was cleared, false when none was set (no effect)
  11299. */;
  11300. _proto.clearInterval = function clearInterval() {
  11301. if (this._tickInterval) {
  11302. self.clearInterval(this._tickInterval);
  11303. this._tickInterval = null;
  11304. return true;
  11305. }
  11306. return false;
  11307. }
  11308. /**
  11309. * @returns True when timeout was cleared, false when none was set (no effect)
  11310. */;
  11311. _proto.clearNextTick = function clearNextTick() {
  11312. if (this._tickTimer) {
  11313. self.clearTimeout(this._tickTimer);
  11314. this._tickTimer = null;
  11315. return true;
  11316. }
  11317. return false;
  11318. }
  11319. /**
  11320. * Will call the subclass doTick implementation in this main loop tick
  11321. * or in the next one (via setTimeout(,0)) in case it has already been called
  11322. * in this tick (in case this is a re-entrant call).
  11323. */;
  11324. _proto.tick = function tick() {
  11325. this._tickCallCount++;
  11326. if (this._tickCallCount === 1) {
  11327. this.doTick();
  11328. // re-entrant call to tick from previous doTick call stack
  11329. // -> schedule a call on the next main loop iteration to process this task processing request
  11330. if (this._tickCallCount > 1) {
  11331. // make sure only one timer exists at any time at max
  11332. this.tickImmediate();
  11333. }
  11334. this._tickCallCount = 0;
  11335. }
  11336. };
  11337. _proto.tickImmediate = function tickImmediate() {
  11338. this.clearNextTick();
  11339. this._tickTimer = self.setTimeout(this._boundTick, 0);
  11340. }
  11341. /**
  11342. * For subclass to implement task logic
  11343. * @abstract
  11344. */;
  11345. _proto.doTick = function doTick() {};
  11346. return TaskLoop;
  11347. }();
  11348. var ChunkMetadata = function ChunkMetadata(level, sn, id, size, part, partial) {
  11349. if (size === void 0) {
  11350. size = 0;
  11351. }
  11352. if (part === void 0) {
  11353. part = -1;
  11354. }
  11355. if (partial === void 0) {
  11356. partial = false;
  11357. }
  11358. this.level = void 0;
  11359. this.sn = void 0;
  11360. this.part = void 0;
  11361. this.id = void 0;
  11362. this.size = void 0;
  11363. this.partial = void 0;
  11364. this.transmuxing = getNewPerformanceTiming();
  11365. this.buffering = {
  11366. audio: getNewPerformanceTiming(),
  11367. video: getNewPerformanceTiming(),
  11368. audiovideo: getNewPerformanceTiming()
  11369. };
  11370. this.level = level;
  11371. this.sn = sn;
  11372. this.id = id;
  11373. this.size = size;
  11374. this.part = part;
  11375. this.partial = partial;
  11376. };
  11377. function getNewPerformanceTiming() {
  11378. return {
  11379. start: 0,
  11380. executeStart: 0,
  11381. executeEnd: 0,
  11382. end: 0
  11383. };
  11384. }
  11385. function findFirstFragWithCC(fragments, cc) {
  11386. for (var i = 0, len = fragments.length; i < len; i++) {
  11387. var _fragments$i;
  11388. if (((_fragments$i = fragments[i]) == null ? void 0 : _fragments$i.cc) === cc) {
  11389. return fragments[i];
  11390. }
  11391. }
  11392. return null;
  11393. }
  11394. function shouldAlignOnDiscontinuities(lastFrag, switchDetails, details) {
  11395. if (switchDetails) {
  11396. if (details.endCC > details.startCC || lastFrag && lastFrag.cc < details.startCC) {
  11397. return true;
  11398. }
  11399. }
  11400. return false;
  11401. }
  11402. // Find the first frag in the previous level which matches the CC of the first frag of the new level
  11403. function findDiscontinuousReferenceFrag(prevDetails, curDetails) {
  11404. var prevFrags = prevDetails.fragments;
  11405. var curFrags = curDetails.fragments;
  11406. if (!curFrags.length || !prevFrags.length) {
  11407. logger.log('No fragments to align');
  11408. return;
  11409. }
  11410. var prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);
  11411. if (!prevStartFrag || prevStartFrag && !prevStartFrag.startPTS) {
  11412. logger.log('No frag in previous level to align on');
  11413. return;
  11414. }
  11415. return prevStartFrag;
  11416. }
  11417. function adjustFragmentStart(frag, sliding) {
  11418. if (frag) {
  11419. var start = frag.start + sliding;
  11420. frag.start = frag.startPTS = start;
  11421. frag.endPTS = start + frag.duration;
  11422. }
  11423. }
  11424. function adjustSlidingStart(sliding, details) {
  11425. // Update segments
  11426. var fragments = details.fragments;
  11427. for (var i = 0, len = fragments.length; i < len; i++) {
  11428. adjustFragmentStart(fragments[i], sliding);
  11429. }
  11430. // Update LL-HLS parts at the end of the playlist
  11431. if (details.fragmentHint) {
  11432. adjustFragmentStart(details.fragmentHint, sliding);
  11433. }
  11434. details.alignedSliding = true;
  11435. }
  11436. /**
  11437. * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a
  11438. * contiguous stream with the last fragments.
  11439. * The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to
  11440. * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time
  11441. * and an extra download.
  11442. * @param lastFrag
  11443. * @param lastLevel
  11444. * @param details
  11445. */
  11446. function alignStream(lastFrag, switchDetails, details) {
  11447. if (!switchDetails) {
  11448. return;
  11449. }
  11450. alignDiscontinuities(lastFrag, details, switchDetails);
  11451. if (!details.alignedSliding && switchDetails) {
  11452. // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.
  11453. // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same
  11454. // discontinuity sequence.
  11455. alignMediaPlaylistByPDT(details, switchDetails);
  11456. }
  11457. if (!details.alignedSliding && switchDetails && !details.skippedSegments) {
  11458. // Try to align on sn so that we pick a better start fragment.
  11459. // Do not perform this on playlists with delta updates as this is only to align levels on switch
  11460. // and adjustSliding only adjusts fragments after skippedSegments.
  11461. adjustSliding(switchDetails, details);
  11462. }
  11463. }
  11464. /**
  11465. * Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same
  11466. * discontinuity sequence.
  11467. * @param lastFrag - The last Fragment which shares the same discontinuity sequence
  11468. * @param lastLevel - The details of the last loaded level
  11469. * @param details - The details of the new level
  11470. */
  11471. function alignDiscontinuities(lastFrag, details, switchDetails) {
  11472. if (shouldAlignOnDiscontinuities(lastFrag, switchDetails, details)) {
  11473. var referenceFrag = findDiscontinuousReferenceFrag(switchDetails, details);
  11474. if (referenceFrag && isFiniteNumber(referenceFrag.start)) {
  11475. logger.log("Adjusting PTS using last level due to CC increase within current level " + details.url);
  11476. adjustSlidingStart(referenceFrag.start, details);
  11477. }
  11478. }
  11479. }
  11480. /**
  11481. * Ensures appropriate time-alignment between renditions based on PDT.
  11482. * This function assumes the timelines represented in `refDetails` are accurate, including the PDTs
  11483. * for the last discontinuity sequence number shared by both playlists when present,
  11484. * and uses the "wallclock"/PDT timeline as a cross-reference to `details`, adjusting the presentation
  11485. * times/timelines of `details` accordingly.
  11486. * Given the asynchronous nature of fetches and initial loads of live `main` and audio/subtitle tracks,
  11487. * the primary purpose of this function is to ensure the "local timelines" of audio/subtitle tracks
  11488. * are aligned to the main/video timeline, using PDT as the cross-reference/"anchor" that should
  11489. * be consistent across playlists, per the HLS spec.
  11490. * @param details - The details of the rendition you'd like to time-align (e.g. an audio rendition).
  11491. * @param refDetails - The details of the reference rendition with start and PDT times for alignment.
  11492. */
  11493. function alignMediaPlaylistByPDT(details, refDetails) {
  11494. if (!details.hasProgramDateTime || !refDetails.hasProgramDateTime) {
  11495. return;
  11496. }
  11497. var fragments = details.fragments;
  11498. var refFragments = refDetails.fragments;
  11499. if (!fragments.length || !refFragments.length) {
  11500. return;
  11501. }
  11502. // Calculate a delta to apply to all fragments according to the delta in PDT times and start times
  11503. // of a fragment in the reference details, and a fragment in the target details of the same discontinuity.
  11504. // If a fragment of the same discontinuity was not found use the middle fragment of both.
  11505. var refFrag;
  11506. var frag;
  11507. var targetCC = Math.min(refDetails.endCC, details.endCC);
  11508. if (refDetails.startCC < targetCC && details.startCC < targetCC) {
  11509. refFrag = findFirstFragWithCC(refFragments, targetCC);
  11510. frag = findFirstFragWithCC(fragments, targetCC);
  11511. }
  11512. if (!refFrag || !frag) {
  11513. refFrag = refFragments[Math.floor(refFragments.length / 2)];
  11514. frag = findFirstFragWithCC(fragments, refFrag.cc) || fragments[Math.floor(fragments.length / 2)];
  11515. }
  11516. var refPDT = refFrag.programDateTime;
  11517. var targetPDT = frag.programDateTime;
  11518. if (!refPDT || !targetPDT) {
  11519. return;
  11520. }
  11521. var delta = (targetPDT - refPDT) / 1000 - (frag.start - refFrag.start);
  11522. adjustSlidingStart(delta, details);
  11523. }
  11524. var AESCrypto = /*#__PURE__*/function () {
  11525. function AESCrypto(subtle, iv) {
  11526. this.subtle = void 0;
  11527. this.aesIV = void 0;
  11528. this.subtle = subtle;
  11529. this.aesIV = iv;
  11530. }
  11531. var _proto = AESCrypto.prototype;
  11532. _proto.decrypt = function decrypt(data, key) {
  11533. return this.subtle.decrypt({
  11534. name: 'AES-CBC',
  11535. iv: this.aesIV
  11536. }, key, data);
  11537. };
  11538. return AESCrypto;
  11539. }();
  11540. var FastAESKey = /*#__PURE__*/function () {
  11541. function FastAESKey(subtle, key) {
  11542. this.subtle = void 0;
  11543. this.key = void 0;
  11544. this.subtle = subtle;
  11545. this.key = key;
  11546. }
  11547. var _proto = FastAESKey.prototype;
  11548. _proto.expandKey = function expandKey() {
  11549. return this.subtle.importKey('raw', this.key, {
  11550. name: 'AES-CBC'
  11551. }, false, ['encrypt', 'decrypt']);
  11552. };
  11553. return FastAESKey;
  11554. }();
  11555. // PKCS7
  11556. function removePadding(array) {
  11557. var outputBytes = array.byteLength;
  11558. var paddingBytes = outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1);
  11559. if (paddingBytes) {
  11560. return sliceUint8(array, 0, outputBytes - paddingBytes);
  11561. }
  11562. return array;
  11563. }
  11564. var AESDecryptor = /*#__PURE__*/function () {
  11565. function AESDecryptor() {
  11566. this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
  11567. this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  11568. this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  11569. this.sBox = new Uint32Array(256);
  11570. this.invSBox = new Uint32Array(256);
  11571. this.key = new Uint32Array(0);
  11572. this.ksRows = 0;
  11573. this.keySize = 0;
  11574. this.keySchedule = void 0;
  11575. this.invKeySchedule = void 0;
  11576. this.initTable();
  11577. }
  11578. // Using view.getUint32() also swaps the byte order.
  11579. var _proto = AESDecryptor.prototype;
  11580. _proto.uint8ArrayToUint32Array_ = function uint8ArrayToUint32Array_(arrayBuffer) {
  11581. var view = new DataView(arrayBuffer);
  11582. var newArray = new Uint32Array(4);
  11583. for (var i = 0; i < 4; i++) {
  11584. newArray[i] = view.getUint32(i * 4);
  11585. }
  11586. return newArray;
  11587. };
  11588. _proto.initTable = function initTable() {
  11589. var sBox = this.sBox;
  11590. var invSBox = this.invSBox;
  11591. var subMix = this.subMix;
  11592. var subMix0 = subMix[0];
  11593. var subMix1 = subMix[1];
  11594. var subMix2 = subMix[2];
  11595. var subMix3 = subMix[3];
  11596. var invSubMix = this.invSubMix;
  11597. var invSubMix0 = invSubMix[0];
  11598. var invSubMix1 = invSubMix[1];
  11599. var invSubMix2 = invSubMix[2];
  11600. var invSubMix3 = invSubMix[3];
  11601. var d = new Uint32Array(256);
  11602. var x = 0;
  11603. var xi = 0;
  11604. var i = 0;
  11605. for (i = 0; i < 256; i++) {
  11606. if (i < 128) {
  11607. d[i] = i << 1;
  11608. } else {
  11609. d[i] = i << 1 ^ 0x11b;
  11610. }
  11611. }
  11612. for (i = 0; i < 256; i++) {
  11613. var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
  11614. sx = sx >>> 8 ^ sx & 0xff ^ 0x63;
  11615. sBox[x] = sx;
  11616. invSBox[sx] = x;
  11617. // Compute multiplication
  11618. var x2 = d[x];
  11619. var x4 = d[x2];
  11620. var x8 = d[x4];
  11621. // Compute sub/invSub bytes, mix columns tables
  11622. var t = d[sx] * 0x101 ^ sx * 0x1010100;
  11623. subMix0[x] = t << 24 | t >>> 8;
  11624. subMix1[x] = t << 16 | t >>> 16;
  11625. subMix2[x] = t << 8 | t >>> 24;
  11626. subMix3[x] = t;
  11627. // Compute inv sub bytes, inv mix columns tables
  11628. t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  11629. invSubMix0[sx] = t << 24 | t >>> 8;
  11630. invSubMix1[sx] = t << 16 | t >>> 16;
  11631. invSubMix2[sx] = t << 8 | t >>> 24;
  11632. invSubMix3[sx] = t;
  11633. // Compute next counter
  11634. if (!x) {
  11635. x = xi = 1;
  11636. } else {
  11637. x = x2 ^ d[d[d[x8 ^ x2]]];
  11638. xi ^= d[d[xi]];
  11639. }
  11640. }
  11641. };
  11642. _proto.expandKey = function expandKey(keyBuffer) {
  11643. // convert keyBuffer to Uint32Array
  11644. var key = this.uint8ArrayToUint32Array_(keyBuffer);
  11645. var sameKey = true;
  11646. var offset = 0;
  11647. while (offset < key.length && sameKey) {
  11648. sameKey = key[offset] === this.key[offset];
  11649. offset++;
  11650. }
  11651. if (sameKey) {
  11652. return;
  11653. }
  11654. this.key = key;
  11655. var keySize = this.keySize = key.length;
  11656. if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
  11657. throw new Error('Invalid aes key size=' + keySize);
  11658. }
  11659. var ksRows = this.ksRows = (keySize + 6 + 1) * 4;
  11660. var ksRow;
  11661. var invKsRow;
  11662. var keySchedule = this.keySchedule = new Uint32Array(ksRows);
  11663. var invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
  11664. var sbox = this.sBox;
  11665. var rcon = this.rcon;
  11666. var invSubMix = this.invSubMix;
  11667. var invSubMix0 = invSubMix[0];
  11668. var invSubMix1 = invSubMix[1];
  11669. var invSubMix2 = invSubMix[2];
  11670. var invSubMix3 = invSubMix[3];
  11671. var prev;
  11672. var t;
  11673. for (ksRow = 0; ksRow < ksRows; ksRow++) {
  11674. if (ksRow < keySize) {
  11675. prev = keySchedule[ksRow] = key[ksRow];
  11676. continue;
  11677. }
  11678. t = prev;
  11679. if (ksRow % keySize === 0) {
  11680. // Rot word
  11681. t = t << 8 | t >>> 24;
  11682. // Sub word
  11683. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  11684. // Mix Rcon
  11685. t ^= rcon[ksRow / keySize | 0] << 24;
  11686. } else if (keySize > 6 && ksRow % keySize === 4) {
  11687. // Sub word
  11688. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  11689. }
  11690. keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
  11691. }
  11692. for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
  11693. ksRow = ksRows - invKsRow;
  11694. if (invKsRow & 3) {
  11695. t = keySchedule[ksRow];
  11696. } else {
  11697. t = keySchedule[ksRow - 4];
  11698. }
  11699. if (invKsRow < 4 || ksRow <= 4) {
  11700. invKeySchedule[invKsRow] = t;
  11701. } else {
  11702. invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]];
  11703. }
  11704. invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
  11705. }
  11706. }
  11707. // Adding this as a method greatly improves performance.
  11708. ;
  11709. _proto.networkToHostOrderSwap = function networkToHostOrderSwap(word) {
  11710. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  11711. };
  11712. _proto.decrypt = function decrypt(inputArrayBuffer, offset, aesIV) {
  11713. var nRounds = this.keySize + 6;
  11714. var invKeySchedule = this.invKeySchedule;
  11715. var invSBOX = this.invSBox;
  11716. var invSubMix = this.invSubMix;
  11717. var invSubMix0 = invSubMix[0];
  11718. var invSubMix1 = invSubMix[1];
  11719. var invSubMix2 = invSubMix[2];
  11720. var invSubMix3 = invSubMix[3];
  11721. var initVector = this.uint8ArrayToUint32Array_(aesIV);
  11722. var initVector0 = initVector[0];
  11723. var initVector1 = initVector[1];
  11724. var initVector2 = initVector[2];
  11725. var initVector3 = initVector[3];
  11726. var inputInt32 = new Int32Array(inputArrayBuffer);
  11727. var outputInt32 = new Int32Array(inputInt32.length);
  11728. var t0, t1, t2, t3;
  11729. var s0, s1, s2, s3;
  11730. var inputWords0, inputWords1, inputWords2, inputWords3;
  11731. var ksRow, i;
  11732. var swapWord = this.networkToHostOrderSwap;
  11733. while (offset < inputInt32.length) {
  11734. inputWords0 = swapWord(inputInt32[offset]);
  11735. inputWords1 = swapWord(inputInt32[offset + 1]);
  11736. inputWords2 = swapWord(inputInt32[offset + 2]);
  11737. inputWords3 = swapWord(inputInt32[offset + 3]);
  11738. s0 = inputWords0 ^ invKeySchedule[0];
  11739. s1 = inputWords3 ^ invKeySchedule[1];
  11740. s2 = inputWords2 ^ invKeySchedule[2];
  11741. s3 = inputWords1 ^ invKeySchedule[3];
  11742. ksRow = 4;
  11743. // Iterate through the rounds of decryption
  11744. for (i = 1; i < nRounds; i++) {
  11745. t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];
  11746. t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  11747. t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  11748. t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  11749. // Update state
  11750. s0 = t0;
  11751. s1 = t1;
  11752. s2 = t2;
  11753. s3 = t3;
  11754. ksRow = ksRow + 4;
  11755. }
  11756. // Shift rows, sub bytes, add round key
  11757. t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow];
  11758. t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  11759. t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  11760. t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  11761. // Write
  11762. outputInt32[offset] = swapWord(t0 ^ initVector0);
  11763. outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
  11764. outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
  11765. outputInt32[offset + 3] = swapWord(t1 ^ initVector3);
  11766. // reset initVector to last 4 unsigned int
  11767. initVector0 = inputWords0;
  11768. initVector1 = inputWords1;
  11769. initVector2 = inputWords2;
  11770. initVector3 = inputWords3;
  11771. offset = offset + 4;
  11772. }
  11773. return outputInt32.buffer;
  11774. };
  11775. return AESDecryptor;
  11776. }();
  11777. var CHUNK_SIZE = 16; // 16 bytes, 128 bits
  11778. var Decrypter = /*#__PURE__*/function () {
  11779. function Decrypter(config, _temp) {
  11780. var _ref = _temp === void 0 ? {} : _temp,
  11781. _ref$removePKCS7Paddi = _ref.removePKCS7Padding,
  11782. removePKCS7Padding = _ref$removePKCS7Paddi === void 0 ? true : _ref$removePKCS7Paddi;
  11783. this.logEnabled = true;
  11784. this.removePKCS7Padding = void 0;
  11785. this.subtle = null;
  11786. this.softwareDecrypter = null;
  11787. this.key = null;
  11788. this.fastAesKey = null;
  11789. this.remainderData = null;
  11790. this.currentIV = null;
  11791. this.currentResult = null;
  11792. this.useSoftware = void 0;
  11793. this.useSoftware = config.enableSoftwareAES;
  11794. this.removePKCS7Padding = removePKCS7Padding;
  11795. // built in decryptor expects PKCS7 padding
  11796. if (removePKCS7Padding) {
  11797. try {
  11798. var browserCrypto = self.crypto;
  11799. if (browserCrypto) {
  11800. this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
  11801. }
  11802. } catch (e) {
  11803. /* no-op */
  11804. }
  11805. }
  11806. this.useSoftware = !this.subtle;
  11807. }
  11808. var _proto = Decrypter.prototype;
  11809. _proto.destroy = function destroy() {
  11810. this.subtle = null;
  11811. this.softwareDecrypter = null;
  11812. this.key = null;
  11813. this.fastAesKey = null;
  11814. this.remainderData = null;
  11815. this.currentIV = null;
  11816. this.currentResult = null;
  11817. };
  11818. _proto.isSync = function isSync() {
  11819. return this.useSoftware;
  11820. };
  11821. _proto.flush = function flush() {
  11822. var currentResult = this.currentResult,
  11823. remainderData = this.remainderData;
  11824. if (!currentResult || remainderData) {
  11825. this.reset();
  11826. return null;
  11827. }
  11828. var data = new Uint8Array(currentResult);
  11829. this.reset();
  11830. if (this.removePKCS7Padding) {
  11831. return removePadding(data);
  11832. }
  11833. return data;
  11834. };
  11835. _proto.reset = function reset() {
  11836. this.currentResult = null;
  11837. this.currentIV = null;
  11838. this.remainderData = null;
  11839. if (this.softwareDecrypter) {
  11840. this.softwareDecrypter = null;
  11841. }
  11842. };
  11843. _proto.decrypt = function decrypt(data, key, iv) {
  11844. var _this = this;
  11845. if (this.useSoftware) {
  11846. return new Promise(function (resolve, reject) {
  11847. _this.softwareDecrypt(new Uint8Array(data), key, iv);
  11848. var decryptResult = _this.flush();
  11849. if (decryptResult) {
  11850. resolve(decryptResult.buffer);
  11851. } else {
  11852. reject(new Error('[softwareDecrypt] Failed to decrypt data'));
  11853. }
  11854. });
  11855. }
  11856. return this.webCryptoDecrypt(new Uint8Array(data), key, iv);
  11857. }
  11858. // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
  11859. // data is handled in the flush() call
  11860. ;
  11861. _proto.softwareDecrypt = function softwareDecrypt(data, key, iv) {
  11862. var currentIV = this.currentIV,
  11863. currentResult = this.currentResult,
  11864. remainderData = this.remainderData;
  11865. this.logOnce('JS AES decrypt');
  11866. // The output is staggered during progressive parsing - the current result is cached, and emitted on the next call
  11867. // This is done in order to strip PKCS7 padding, which is found at the end of each segment. We only know we've reached
  11868. // the end on flush(), but by that time we have already received all bytes for the segment.
  11869. // Progressive decryption does not work with WebCrypto
  11870. if (remainderData) {
  11871. data = appendUint8Array(remainderData, data);
  11872. this.remainderData = null;
  11873. }
  11874. // Byte length must be a multiple of 16 (AES-128 = 128 bit blocks = 16 bytes)
  11875. var currentChunk = this.getValidChunk(data);
  11876. if (!currentChunk.length) {
  11877. return null;
  11878. }
  11879. if (currentIV) {
  11880. iv = currentIV;
  11881. }
  11882. var softwareDecrypter = this.softwareDecrypter;
  11883. if (!softwareDecrypter) {
  11884. softwareDecrypter = this.softwareDecrypter = new AESDecryptor();
  11885. }
  11886. softwareDecrypter.expandKey(key);
  11887. var result = currentResult;
  11888. this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv);
  11889. this.currentIV = sliceUint8(currentChunk, -16).buffer;
  11890. if (!result) {
  11891. return null;
  11892. }
  11893. return result;
  11894. };
  11895. _proto.webCryptoDecrypt = function webCryptoDecrypt(data, key, iv) {
  11896. var _this2 = this;
  11897. if (this.key !== key || !this.fastAesKey) {
  11898. if (!this.subtle) {
  11899. return Promise.resolve(this.onWebCryptoError(data, key, iv));
  11900. }
  11901. this.key = key;
  11902. this.fastAesKey = new FastAESKey(this.subtle, key);
  11903. }
  11904. return this.fastAesKey.expandKey().then(function (aesKey) {
  11905. // decrypt using web crypto
  11906. if (!_this2.subtle) {
  11907. return Promise.reject(new Error('web crypto not initialized'));
  11908. }
  11909. _this2.logOnce('WebCrypto AES decrypt');
  11910. var crypto = new AESCrypto(_this2.subtle, new Uint8Array(iv));
  11911. return crypto.decrypt(data.buffer, aesKey);
  11912. }).catch(function (err) {
  11913. logger.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, " + err.name + ": " + err.message);
  11914. return _this2.onWebCryptoError(data, key, iv);
  11915. });
  11916. };
  11917. _proto.onWebCryptoError = function onWebCryptoError(data, key, iv) {
  11918. this.useSoftware = true;
  11919. this.logEnabled = true;
  11920. this.softwareDecrypt(data, key, iv);
  11921. var decryptResult = this.flush();
  11922. if (decryptResult) {
  11923. return decryptResult.buffer;
  11924. }
  11925. throw new Error('WebCrypto and softwareDecrypt: failed to decrypt data');
  11926. };
  11927. _proto.getValidChunk = function getValidChunk(data) {
  11928. var currentChunk = data;
  11929. var splitPoint = data.length - data.length % CHUNK_SIZE;
  11930. if (splitPoint !== data.length) {
  11931. currentChunk = sliceUint8(data, 0, splitPoint);
  11932. this.remainderData = sliceUint8(data, splitPoint);
  11933. }
  11934. return currentChunk;
  11935. };
  11936. _proto.logOnce = function logOnce(msg) {
  11937. if (!this.logEnabled) {
  11938. return;
  11939. }
  11940. logger.log("[decrypter]: " + msg);
  11941. this.logEnabled = false;
  11942. };
  11943. return Decrypter;
  11944. }();
  11945. /**
  11946. * TimeRanges to string helper
  11947. */
  11948. var TimeRanges = {
  11949. toString: function toString(r) {
  11950. var log = '';
  11951. var len = r.length;
  11952. for (var i = 0; i < len; i++) {
  11953. log += "[" + r.start(i).toFixed(3) + "-" + r.end(i).toFixed(3) + "]";
  11954. }
  11955. return log;
  11956. }
  11957. };
  11958. var State = {
  11959. STOPPED: 'STOPPED',
  11960. IDLE: 'IDLE',
  11961. KEY_LOADING: 'KEY_LOADING',
  11962. FRAG_LOADING: 'FRAG_LOADING',
  11963. FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
  11964. WAITING_TRACK: 'WAITING_TRACK',
  11965. PARSING: 'PARSING',
  11966. PARSED: 'PARSED',
  11967. ENDED: 'ENDED',
  11968. ERROR: 'ERROR',
  11969. WAITING_INIT_PTS: 'WAITING_INIT_PTS',
  11970. WAITING_LEVEL: 'WAITING_LEVEL'
  11971. };
  11972. var BaseStreamController = /*#__PURE__*/function (_TaskLoop) {
  11973. _inheritsLoose(BaseStreamController, _TaskLoop);
  11974. function BaseStreamController(hls, fragmentTracker, keyLoader, logPrefix, playlistType) {
  11975. var _this;
  11976. _this = _TaskLoop.call(this) || this;
  11977. _this.hls = void 0;
  11978. _this.fragPrevious = null;
  11979. _this.fragCurrent = null;
  11980. _this.fragmentTracker = void 0;
  11981. _this.transmuxer = null;
  11982. _this._state = State.STOPPED;
  11983. _this.playlistType = void 0;
  11984. _this.media = null;
  11985. _this.mediaBuffer = null;
  11986. _this.config = void 0;
  11987. _this.bitrateTest = false;
  11988. _this.lastCurrentTime = 0;
  11989. _this.nextLoadPosition = 0;
  11990. _this.startPosition = 0;
  11991. _this.startTimeOffset = null;
  11992. _this.loadedmetadata = false;
  11993. _this.retryDate = 0;
  11994. _this.levels = null;
  11995. _this.fragmentLoader = void 0;
  11996. _this.keyLoader = void 0;
  11997. _this.levelLastLoaded = null;
  11998. _this.startFragRequested = false;
  11999. _this.decrypter = void 0;
  12000. _this.initPTS = [];
  12001. _this.onvseeking = null;
  12002. _this.onvended = null;
  12003. _this.logPrefix = '';
  12004. _this.log = void 0;
  12005. _this.warn = void 0;
  12006. _this.playlistType = playlistType;
  12007. _this.logPrefix = logPrefix;
  12008. _this.log = logger.log.bind(logger, logPrefix + ":");
  12009. _this.warn = logger.warn.bind(logger, logPrefix + ":");
  12010. _this.hls = hls;
  12011. _this.fragmentLoader = new FragmentLoader(hls.config);
  12012. _this.keyLoader = keyLoader;
  12013. _this.fragmentTracker = fragmentTracker;
  12014. _this.config = hls.config;
  12015. _this.decrypter = new Decrypter(hls.config);
  12016. hls.on(Events.MANIFEST_LOADED, _this.onManifestLoaded, _assertThisInitialized(_this));
  12017. return _this;
  12018. }
  12019. var _proto = BaseStreamController.prototype;
  12020. _proto.doTick = function doTick() {
  12021. this.onTickEnd();
  12022. };
  12023. _proto.onTickEnd = function onTickEnd() {}
  12024. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  12025. ;
  12026. _proto.startLoad = function startLoad(startPosition) {};
  12027. _proto.stopLoad = function stopLoad() {
  12028. this.fragmentLoader.abort();
  12029. this.keyLoader.abort(this.playlistType);
  12030. var frag = this.fragCurrent;
  12031. if (frag != null && frag.loader) {
  12032. frag.abortRequests();
  12033. this.fragmentTracker.removeFragment(frag);
  12034. }
  12035. this.resetTransmuxer();
  12036. this.fragCurrent = null;
  12037. this.fragPrevious = null;
  12038. this.clearInterval();
  12039. this.clearNextTick();
  12040. this.state = State.STOPPED;
  12041. };
  12042. _proto._streamEnded = function _streamEnded(bufferInfo, levelDetails) {
  12043. // If playlist is live, there is another buffered range after the current range, nothing buffered, media is detached,
  12044. // of nothing loading/loaded return false
  12045. if (levelDetails.live || bufferInfo.nextStart || !bufferInfo.end || !this.media) {
  12046. return false;
  12047. }
  12048. var partList = levelDetails.partList;
  12049. // Since the last part isn't guaranteed to correspond to the last playlist segment for Low-Latency HLS,
  12050. // check instead if the last part is buffered.
  12051. if (partList != null && partList.length) {
  12052. var lastPart = partList[partList.length - 1];
  12053. // Checking the midpoint of the part for potential margin of error and related issues.
  12054. // NOTE: Technically I believe parts could yield content that is < the computed duration (including potential a duration of 0)
  12055. // and still be spec-compliant, so there may still be edge cases here. Likewise, there could be issues in end of stream
  12056. // part mismatches for independent audio and video playlists/segments.
  12057. var lastPartBuffered = BufferHelper.isBuffered(this.media, lastPart.start + lastPart.duration / 2);
  12058. return lastPartBuffered;
  12059. }
  12060. var playlistType = levelDetails.fragments[levelDetails.fragments.length - 1].type;
  12061. return this.fragmentTracker.isEndListAppended(playlistType);
  12062. };
  12063. _proto.getLevelDetails = function getLevelDetails() {
  12064. if (this.levels && this.levelLastLoaded !== null) {
  12065. var _this$levelLastLoaded;
  12066. return (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details;
  12067. }
  12068. };
  12069. _proto.onMediaAttached = function onMediaAttached(event, data) {
  12070. var media = this.media = this.mediaBuffer = data.media;
  12071. this.onvseeking = this.onMediaSeeking.bind(this);
  12072. this.onvended = this.onMediaEnded.bind(this);
  12073. media.addEventListener('seeking', this.onvseeking);
  12074. media.addEventListener('ended', this.onvended);
  12075. var config = this.config;
  12076. if (this.levels && config.autoStartLoad && this.state === State.STOPPED) {
  12077. this.startLoad(config.startPosition);
  12078. }
  12079. };
  12080. _proto.onMediaDetaching = function onMediaDetaching() {
  12081. var media = this.media;
  12082. if (media != null && media.ended) {
  12083. this.log('MSE detaching and video ended, reset startPosition');
  12084. this.startPosition = this.lastCurrentTime = 0;
  12085. }
  12086. // remove video listeners
  12087. if (media && this.onvseeking && this.onvended) {
  12088. media.removeEventListener('seeking', this.onvseeking);
  12089. media.removeEventListener('ended', this.onvended);
  12090. this.onvseeking = this.onvended = null;
  12091. }
  12092. if (this.keyLoader) {
  12093. this.keyLoader.detach();
  12094. }
  12095. this.media = this.mediaBuffer = null;
  12096. this.loadedmetadata = false;
  12097. this.fragmentTracker.removeAllFragments();
  12098. this.stopLoad();
  12099. };
  12100. _proto.onMediaSeeking = function onMediaSeeking() {
  12101. var config = this.config,
  12102. fragCurrent = this.fragCurrent,
  12103. media = this.media,
  12104. mediaBuffer = this.mediaBuffer,
  12105. state = this.state;
  12106. var currentTime = media ? media.currentTime : 0;
  12107. var bufferInfo = BufferHelper.bufferInfo(mediaBuffer ? mediaBuffer : media, currentTime, config.maxBufferHole);
  12108. this.log("media seeking to " + (isFiniteNumber(currentTime) ? currentTime.toFixed(3) : currentTime) + ", state: " + state);
  12109. if (this.state === State.ENDED) {
  12110. this.resetLoadingState();
  12111. } else if (fragCurrent) {
  12112. // Seeking while frag load is in progress
  12113. var tolerance = config.maxFragLookUpTolerance;
  12114. var fragStartOffset = fragCurrent.start - tolerance;
  12115. var fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;
  12116. // if seeking out of buffered range or into new one
  12117. if (!bufferInfo.len || fragEndOffset < bufferInfo.start || fragStartOffset > bufferInfo.end) {
  12118. var pastFragment = currentTime > fragEndOffset;
  12119. // if the seek position is outside the current fragment range
  12120. if (currentTime < fragStartOffset || pastFragment) {
  12121. if (pastFragment && fragCurrent.loader) {
  12122. this.log('seeking outside of buffer while fragment load in progress, cancel fragment load');
  12123. fragCurrent.abortRequests();
  12124. this.resetLoadingState();
  12125. }
  12126. this.fragPrevious = null;
  12127. }
  12128. }
  12129. }
  12130. if (media) {
  12131. // Remove gap fragments
  12132. this.fragmentTracker.removeFragmentsInRange(currentTime, Infinity, this.playlistType, true);
  12133. this.lastCurrentTime = currentTime;
  12134. }
  12135. // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
  12136. if (!this.loadedmetadata && !bufferInfo.len) {
  12137. this.nextLoadPosition = this.startPosition = currentTime;
  12138. }
  12139. // Async tick to speed up processing
  12140. this.tickImmediate();
  12141. };
  12142. _proto.onMediaEnded = function onMediaEnded() {
  12143. // reset startPosition and lastCurrentTime to restart playback @ stream beginning
  12144. this.startPosition = this.lastCurrentTime = 0;
  12145. };
  12146. _proto.onManifestLoaded = function onManifestLoaded(event, data) {
  12147. this.startTimeOffset = data.startTimeOffset;
  12148. this.initPTS = [];
  12149. };
  12150. _proto.onHandlerDestroying = function onHandlerDestroying() {
  12151. this.hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  12152. this.stopLoad();
  12153. _TaskLoop.prototype.onHandlerDestroying.call(this);
  12154. // @ts-ignore
  12155. this.hls = null;
  12156. };
  12157. _proto.onHandlerDestroyed = function onHandlerDestroyed() {
  12158. this.state = State.STOPPED;
  12159. if (this.fragmentLoader) {
  12160. this.fragmentLoader.destroy();
  12161. }
  12162. if (this.keyLoader) {
  12163. this.keyLoader.destroy();
  12164. }
  12165. if (this.decrypter) {
  12166. this.decrypter.destroy();
  12167. }
  12168. this.hls = this.log = this.warn = this.decrypter = this.keyLoader = this.fragmentLoader = this.fragmentTracker = null;
  12169. _TaskLoop.prototype.onHandlerDestroyed.call(this);
  12170. };
  12171. _proto.loadFragment = function loadFragment(frag, level, targetBufferTime) {
  12172. this._loadFragForPlayback(frag, level, targetBufferTime);
  12173. };
  12174. _proto._loadFragForPlayback = function _loadFragForPlayback(frag, level, targetBufferTime) {
  12175. var _this2 = this;
  12176. var progressCallback = function progressCallback(data) {
  12177. if (_this2.fragContextChanged(frag)) {
  12178. _this2.warn("Fragment " + frag.sn + (data.part ? ' p: ' + data.part.index : '') + " of level " + frag.level + " was dropped during download.");
  12179. _this2.fragmentTracker.removeFragment(frag);
  12180. return;
  12181. }
  12182. frag.stats.chunkCount++;
  12183. _this2._handleFragmentLoadProgress(data);
  12184. };
  12185. this._doFragLoad(frag, level, targetBufferTime, progressCallback).then(function (data) {
  12186. if (!data) {
  12187. // if we're here we probably needed to backtrack or are waiting for more parts
  12188. return;
  12189. }
  12190. var state = _this2.state;
  12191. if (_this2.fragContextChanged(frag)) {
  12192. if (state === State.FRAG_LOADING || !_this2.fragCurrent && state === State.PARSING) {
  12193. _this2.fragmentTracker.removeFragment(frag);
  12194. _this2.state = State.IDLE;
  12195. }
  12196. return;
  12197. }
  12198. if ('payload' in data) {
  12199. _this2.log("Loaded fragment " + frag.sn + " of level " + frag.level);
  12200. _this2.hls.trigger(Events.FRAG_LOADED, data);
  12201. }
  12202. // Pass through the whole payload; controllers not implementing progressive loading receive data from this callback
  12203. _this2._handleFragmentLoadComplete(data);
  12204. }).catch(function (reason) {
  12205. if (_this2.state === State.STOPPED || _this2.state === State.ERROR) {
  12206. return;
  12207. }
  12208. _this2.warn("Frag error: " + ((reason == null ? void 0 : reason.message) || reason));
  12209. _this2.resetFragmentLoading(frag);
  12210. });
  12211. };
  12212. _proto.clearTrackerIfNeeded = function clearTrackerIfNeeded(frag) {
  12213. var _this$mediaBuffer;
  12214. var fragmentTracker = this.fragmentTracker;
  12215. var fragState = fragmentTracker.getState(frag);
  12216. if (fragState === FragmentState.APPENDING) {
  12217. // Lower the max buffer length and try again
  12218. var playlistType = frag.type;
  12219. var bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  12220. var minForwardBufferLength = Math.max(frag.duration, bufferedInfo ? bufferedInfo.len : this.config.maxBufferLength);
  12221. // If backtracking, always remove from the tracker without reducing max buffer length
  12222. var backtrackFragment = this.backtrackFragment;
  12223. var backtracked = backtrackFragment ? frag.sn - backtrackFragment.sn : 0;
  12224. if (backtracked === 1 || this.reduceMaxBufferLength(minForwardBufferLength, frag.duration)) {
  12225. fragmentTracker.removeFragment(frag);
  12226. }
  12227. } else if (((_this$mediaBuffer = this.mediaBuffer) == null ? void 0 : _this$mediaBuffer.buffered.length) === 0) {
  12228. // Stop gap for bad tracker / buffer flush behavior
  12229. fragmentTracker.removeAllFragments();
  12230. } else if (fragmentTracker.hasParts(frag.type)) {
  12231. // In low latency mode, remove fragments for which only some parts were buffered
  12232. fragmentTracker.detectPartialFragments({
  12233. frag: frag,
  12234. part: null,
  12235. stats: frag.stats,
  12236. id: frag.type
  12237. });
  12238. if (fragmentTracker.getState(frag) === FragmentState.PARTIAL) {
  12239. fragmentTracker.removeFragment(frag);
  12240. }
  12241. }
  12242. };
  12243. _proto.checkLiveUpdate = function checkLiveUpdate(details) {
  12244. if (details.updated && !details.live) {
  12245. // Live stream ended, update fragment tracker
  12246. var lastFragment = details.fragments[details.fragments.length - 1];
  12247. this.fragmentTracker.detectPartialFragments({
  12248. frag: lastFragment,
  12249. part: null,
  12250. stats: lastFragment.stats,
  12251. id: lastFragment.type
  12252. });
  12253. }
  12254. if (!details.fragments[0]) {
  12255. details.deltaUpdateFailed = true;
  12256. }
  12257. };
  12258. _proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset, type) {
  12259. if (type === void 0) {
  12260. type = null;
  12261. }
  12262. if (!(startOffset - endOffset)) {
  12263. return;
  12264. }
  12265. // When alternate audio is playing, the audio-stream-controller is responsible for the audio buffer. Otherwise,
  12266. // passing a null type flushes both buffers
  12267. var flushScope = {
  12268. startOffset: startOffset,
  12269. endOffset: endOffset,
  12270. type: type
  12271. };
  12272. this.hls.trigger(Events.BUFFER_FLUSHING, flushScope);
  12273. };
  12274. _proto._loadInitSegment = function _loadInitSegment(frag, level) {
  12275. var _this3 = this;
  12276. this._doFragLoad(frag, level).then(function (data) {
  12277. if (!data || _this3.fragContextChanged(frag) || !_this3.levels) {
  12278. throw new Error('init load aborted');
  12279. }
  12280. return data;
  12281. }).then(function (data) {
  12282. var hls = _this3.hls;
  12283. var payload = data.payload;
  12284. var decryptData = frag.decryptdata;
  12285. // check to see if the payload needs to be decrypted
  12286. if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && decryptData.method === 'AES-128') {
  12287. var startTime = self.performance.now();
  12288. // decrypt init segment data
  12289. return _this3.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer).catch(function (err) {
  12290. hls.trigger(Events.ERROR, {
  12291. type: ErrorTypes.MEDIA_ERROR,
  12292. details: ErrorDetails.FRAG_DECRYPT_ERROR,
  12293. fatal: false,
  12294. error: err,
  12295. reason: err.message,
  12296. frag: frag
  12297. });
  12298. throw err;
  12299. }).then(function (decryptedData) {
  12300. var endTime = self.performance.now();
  12301. hls.trigger(Events.FRAG_DECRYPTED, {
  12302. frag: frag,
  12303. payload: decryptedData,
  12304. stats: {
  12305. tstart: startTime,
  12306. tdecrypt: endTime
  12307. }
  12308. });
  12309. data.payload = decryptedData;
  12310. return _this3.completeInitSegmentLoad(data);
  12311. });
  12312. }
  12313. return _this3.completeInitSegmentLoad(data);
  12314. }).catch(function (reason) {
  12315. if (_this3.state === State.STOPPED || _this3.state === State.ERROR) {
  12316. return;
  12317. }
  12318. _this3.warn(reason);
  12319. _this3.resetFragmentLoading(frag);
  12320. });
  12321. };
  12322. _proto.completeInitSegmentLoad = function completeInitSegmentLoad(data) {
  12323. var levels = this.levels;
  12324. if (!levels) {
  12325. throw new Error('init load aborted, missing levels');
  12326. }
  12327. var stats = data.frag.stats;
  12328. this.state = State.IDLE;
  12329. data.frag.data = new Uint8Array(data.payload);
  12330. stats.parsing.start = stats.buffering.start = self.performance.now();
  12331. stats.parsing.end = stats.buffering.end = self.performance.now();
  12332. this.tick();
  12333. };
  12334. _proto.fragContextChanged = function fragContextChanged(frag) {
  12335. var fragCurrent = this.fragCurrent;
  12336. return !frag || !fragCurrent || frag.sn !== fragCurrent.sn || frag.level !== fragCurrent.level;
  12337. };
  12338. _proto.fragBufferedComplete = function fragBufferedComplete(frag, part) {
  12339. var _frag$startPTS, _frag$endPTS, _this$fragCurrent, _this$fragPrevious;
  12340. var media = this.mediaBuffer ? this.mediaBuffer : this.media;
  12341. this.log("Buffered " + frag.type + " sn: " + frag.sn + (part ? ' part: ' + part.index : '') + " of " + (this.playlistType === PlaylistLevelType.MAIN ? 'level' : 'track') + " " + frag.level + " (frag:[" + ((_frag$startPTS = frag.startPTS) != null ? _frag$startPTS : NaN).toFixed(3) + "-" + ((_frag$endPTS = frag.endPTS) != null ? _frag$endPTS : NaN).toFixed(3) + "] > buffer:" + (media ? TimeRanges.toString(BufferHelper.getBuffered(media)) : '(detached)') + ")");
  12342. if (frag.sn !== 'initSegment') {
  12343. var _this$levels;
  12344. if (frag.type !== PlaylistLevelType.SUBTITLE) {
  12345. var el = frag.elementaryStreams;
  12346. if (!Object.keys(el).some(function (type) {
  12347. return !!el[type];
  12348. })) {
  12349. // empty segment
  12350. this.state = State.IDLE;
  12351. return;
  12352. }
  12353. }
  12354. var level = (_this$levels = this.levels) == null ? void 0 : _this$levels[frag.level];
  12355. if (level != null && level.fragmentError) {
  12356. this.log("Resetting level fragment error count of " + level.fragmentError + " on frag buffered");
  12357. level.fragmentError = 0;
  12358. }
  12359. }
  12360. this.state = State.IDLE;
  12361. if (!media) {
  12362. return;
  12363. }
  12364. if (!this.loadedmetadata && frag.type == PlaylistLevelType.MAIN && media.buffered.length && ((_this$fragCurrent = this.fragCurrent) == null ? void 0 : _this$fragCurrent.sn) === ((_this$fragPrevious = this.fragPrevious) == null ? void 0 : _this$fragPrevious.sn)) {
  12365. this.loadedmetadata = true;
  12366. this.seekToStartPos();
  12367. }
  12368. this.tick();
  12369. };
  12370. _proto.seekToStartPos = function seekToStartPos() {};
  12371. _proto._handleFragmentLoadComplete = function _handleFragmentLoadComplete(fragLoadedEndData) {
  12372. var transmuxer = this.transmuxer;
  12373. if (!transmuxer) {
  12374. return;
  12375. }
  12376. var frag = fragLoadedEndData.frag,
  12377. part = fragLoadedEndData.part,
  12378. partsLoaded = fragLoadedEndData.partsLoaded;
  12379. // If we did not load parts, or loaded all parts, we have complete (not partial) fragment data
  12380. var complete = !partsLoaded || partsLoaded.length === 0 || partsLoaded.some(function (fragLoaded) {
  12381. return !fragLoaded;
  12382. });
  12383. var chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount + 1, 0, part ? part.index : -1, !complete);
  12384. transmuxer.flush(chunkMeta);
  12385. }
  12386. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  12387. ;
  12388. _proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(frag) {};
  12389. _proto._doFragLoad = function _doFragLoad(frag, level, targetBufferTime, progressCallback) {
  12390. var _frag$decryptdata,
  12391. _this4 = this;
  12392. if (targetBufferTime === void 0) {
  12393. targetBufferTime = null;
  12394. }
  12395. var details = level == null ? void 0 : level.details;
  12396. if (!this.levels || !details) {
  12397. throw new Error("frag load aborted, missing level" + (details ? '' : ' detail') + "s");
  12398. }
  12399. var keyLoadingPromise = null;
  12400. if (frag.encrypted && !((_frag$decryptdata = frag.decryptdata) != null && _frag$decryptdata.key)) {
  12401. this.log("Loading key for " + frag.sn + " of [" + details.startSN + "-" + details.endSN + "], " + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + " " + frag.level);
  12402. this.state = State.KEY_LOADING;
  12403. this.fragCurrent = frag;
  12404. keyLoadingPromise = this.keyLoader.load(frag).then(function (keyLoadedData) {
  12405. if (!_this4.fragContextChanged(keyLoadedData.frag)) {
  12406. _this4.hls.trigger(Events.KEY_LOADED, keyLoadedData);
  12407. if (_this4.state === State.KEY_LOADING) {
  12408. _this4.state = State.IDLE;
  12409. }
  12410. return keyLoadedData;
  12411. }
  12412. });
  12413. this.hls.trigger(Events.KEY_LOADING, {
  12414. frag: frag
  12415. });
  12416. if (this.fragCurrent === null) {
  12417. keyLoadingPromise = Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING"));
  12418. }
  12419. } else if (!frag.encrypted && details.encryptedFragments.length) {
  12420. this.keyLoader.loadClear(frag, details.encryptedFragments);
  12421. }
  12422. targetBufferTime = Math.max(frag.start, targetBufferTime || 0);
  12423. if (this.config.lowLatencyMode && frag.sn !== 'initSegment') {
  12424. var partList = details.partList;
  12425. if (partList && progressCallback) {
  12426. if (targetBufferTime > frag.end && details.fragmentHint) {
  12427. frag = details.fragmentHint;
  12428. }
  12429. var partIndex = this.getNextPart(partList, frag, targetBufferTime);
  12430. if (partIndex > -1) {
  12431. var part = partList[partIndex];
  12432. this.log("Loading part sn: " + frag.sn + " p: " + part.index + " cc: " + frag.cc + " of playlist [" + details.startSN + "-" + details.endSN + "] parts [0-" + partIndex + "-" + (partList.length - 1) + "] " + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + ": " + frag.level + ", target: " + parseFloat(targetBufferTime.toFixed(3)));
  12433. this.nextLoadPosition = part.start + part.duration;
  12434. this.state = State.FRAG_LOADING;
  12435. var _result;
  12436. if (keyLoadingPromise) {
  12437. _result = keyLoadingPromise.then(function (keyLoadedData) {
  12438. if (!keyLoadedData || _this4.fragContextChanged(keyLoadedData.frag)) {
  12439. return null;
  12440. }
  12441. return _this4.doFragPartsLoad(frag, part, level, progressCallback);
  12442. }).catch(function (error) {
  12443. return _this4.handleFragLoadError(error);
  12444. });
  12445. } else {
  12446. _result = this.doFragPartsLoad(frag, part, level, progressCallback).catch(function (error) {
  12447. return _this4.handleFragLoadError(error);
  12448. });
  12449. }
  12450. this.hls.trigger(Events.FRAG_LOADING, {
  12451. frag: frag,
  12452. part: part,
  12453. targetBufferTime: targetBufferTime
  12454. });
  12455. if (this.fragCurrent === null) {
  12456. return Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts"));
  12457. }
  12458. return _result;
  12459. } else if (!frag.url || this.loadedEndOfParts(partList, targetBufferTime)) {
  12460. // Fragment hint has no parts
  12461. return Promise.resolve(null);
  12462. }
  12463. }
  12464. }
  12465. this.log("Loading fragment " + frag.sn + " cc: " + frag.cc + " " + (details ? 'of [' + details.startSN + '-' + details.endSN + '] ' : '') + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + ": " + frag.level + ", target: " + parseFloat(targetBufferTime.toFixed(3)));
  12466. // Don't update nextLoadPosition for fragments which are not buffered
  12467. if (isFiniteNumber(frag.sn) && !this.bitrateTest) {
  12468. this.nextLoadPosition = frag.start + frag.duration;
  12469. }
  12470. this.state = State.FRAG_LOADING;
  12471. // Load key before streaming fragment data
  12472. var dataOnProgress = this.config.progressive;
  12473. var result;
  12474. if (dataOnProgress && keyLoadingPromise) {
  12475. result = keyLoadingPromise.then(function (keyLoadedData) {
  12476. if (!keyLoadedData || _this4.fragContextChanged(keyLoadedData == null ? void 0 : keyLoadedData.frag)) {
  12477. return null;
  12478. }
  12479. return _this4.fragmentLoader.load(frag, progressCallback);
  12480. }).catch(function (error) {
  12481. return _this4.handleFragLoadError(error);
  12482. });
  12483. } else {
  12484. // load unencrypted fragment data with progress event,
  12485. // or handle fragment result after key and fragment are finished loading
  12486. result = Promise.all([this.fragmentLoader.load(frag, dataOnProgress ? progressCallback : undefined), keyLoadingPromise]).then(function (_ref) {
  12487. var fragLoadedData = _ref[0];
  12488. if (!dataOnProgress && fragLoadedData && progressCallback) {
  12489. progressCallback(fragLoadedData);
  12490. }
  12491. return fragLoadedData;
  12492. }).catch(function (error) {
  12493. return _this4.handleFragLoadError(error);
  12494. });
  12495. }
  12496. this.hls.trigger(Events.FRAG_LOADING, {
  12497. frag: frag,
  12498. targetBufferTime: targetBufferTime
  12499. });
  12500. if (this.fragCurrent === null) {
  12501. return Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING"));
  12502. }
  12503. return result;
  12504. };
  12505. _proto.doFragPartsLoad = function doFragPartsLoad(frag, fromPart, level, progressCallback) {
  12506. var _this5 = this;
  12507. return new Promise(function (resolve, reject) {
  12508. var _level$details;
  12509. var partsLoaded = [];
  12510. var initialPartList = (_level$details = level.details) == null ? void 0 : _level$details.partList;
  12511. var loadPart = function loadPart(part) {
  12512. _this5.fragmentLoader.loadPart(frag, part, progressCallback).then(function (partLoadedData) {
  12513. partsLoaded[part.index] = partLoadedData;
  12514. var loadedPart = partLoadedData.part;
  12515. _this5.hls.trigger(Events.FRAG_LOADED, partLoadedData);
  12516. var nextPart = getPartWith(level, frag.sn, part.index + 1) || findPart(initialPartList, frag.sn, part.index + 1);
  12517. if (nextPart) {
  12518. loadPart(nextPart);
  12519. } else {
  12520. return resolve({
  12521. frag: frag,
  12522. part: loadedPart,
  12523. partsLoaded: partsLoaded
  12524. });
  12525. }
  12526. }).catch(reject);
  12527. };
  12528. loadPart(fromPart);
  12529. });
  12530. };
  12531. _proto.handleFragLoadError = function handleFragLoadError(error) {
  12532. if ('data' in error) {
  12533. var data = error.data;
  12534. if (error.data && data.details === ErrorDetails.INTERNAL_ABORTED) {
  12535. this.handleFragLoadAborted(data.frag, data.part);
  12536. } else {
  12537. this.hls.trigger(Events.ERROR, data);
  12538. }
  12539. } else {
  12540. this.hls.trigger(Events.ERROR, {
  12541. type: ErrorTypes.OTHER_ERROR,
  12542. details: ErrorDetails.INTERNAL_EXCEPTION,
  12543. err: error,
  12544. error: error,
  12545. fatal: true
  12546. });
  12547. }
  12548. return null;
  12549. };
  12550. _proto._handleTransmuxerFlush = function _handleTransmuxerFlush(chunkMeta) {
  12551. var context = this.getCurrentContext(chunkMeta);
  12552. if (!context || this.state !== State.PARSING) {
  12553. if (!this.fragCurrent && this.state !== State.STOPPED && this.state !== State.ERROR) {
  12554. this.state = State.IDLE;
  12555. }
  12556. return;
  12557. }
  12558. var frag = context.frag,
  12559. part = context.part,
  12560. level = context.level;
  12561. var now = self.performance.now();
  12562. frag.stats.parsing.end = now;
  12563. if (part) {
  12564. part.stats.parsing.end = now;
  12565. }
  12566. this.updateLevelTiming(frag, part, level, chunkMeta.partial);
  12567. };
  12568. _proto.getCurrentContext = function getCurrentContext(chunkMeta) {
  12569. var levels = this.levels,
  12570. fragCurrent = this.fragCurrent;
  12571. var levelIndex = chunkMeta.level,
  12572. sn = chunkMeta.sn,
  12573. partIndex = chunkMeta.part;
  12574. if (!(levels != null && levels[levelIndex])) {
  12575. this.warn("Levels object was unset while buffering fragment " + sn + " of level " + levelIndex + ". The current chunk will not be buffered.");
  12576. return null;
  12577. }
  12578. var level = levels[levelIndex];
  12579. var part = partIndex > -1 ? getPartWith(level, sn, partIndex) : null;
  12580. var frag = part ? part.fragment : getFragmentWithSN(level, sn, fragCurrent);
  12581. if (!frag) {
  12582. return null;
  12583. }
  12584. if (fragCurrent && fragCurrent !== frag) {
  12585. frag.stats = fragCurrent.stats;
  12586. }
  12587. return {
  12588. frag: frag,
  12589. part: part,
  12590. level: level
  12591. };
  12592. };
  12593. _proto.bufferFragmentData = function bufferFragmentData(data, frag, part, chunkMeta, noBacktracking) {
  12594. var _buffer;
  12595. if (!data || this.state !== State.PARSING) {
  12596. return;
  12597. }
  12598. var data1 = data.data1,
  12599. data2 = data.data2;
  12600. var buffer = data1;
  12601. if (data1 && data2) {
  12602. // Combine the moof + mdat so that we buffer with a single append
  12603. buffer = appendUint8Array(data1, data2);
  12604. }
  12605. if (!((_buffer = buffer) != null && _buffer.length)) {
  12606. return;
  12607. }
  12608. var segment = {
  12609. type: data.type,
  12610. frag: frag,
  12611. part: part,
  12612. chunkMeta: chunkMeta,
  12613. parent: frag.type,
  12614. data: buffer
  12615. };
  12616. this.hls.trigger(Events.BUFFER_APPENDING, segment);
  12617. if (data.dropped && data.independent && !part) {
  12618. if (noBacktracking) {
  12619. return;
  12620. }
  12621. // Clear buffer so that we reload previous segments sequentially if required
  12622. this.flushBufferGap(frag);
  12623. }
  12624. };
  12625. _proto.flushBufferGap = function flushBufferGap(frag) {
  12626. var media = this.media;
  12627. if (!media) {
  12628. return;
  12629. }
  12630. // If currentTime is not buffered, clear the back buffer so that we can backtrack as much as needed
  12631. if (!BufferHelper.isBuffered(media, media.currentTime)) {
  12632. this.flushMainBuffer(0, frag.start);
  12633. return;
  12634. }
  12635. // Remove back-buffer without interrupting playback to allow back tracking
  12636. var currentTime = media.currentTime;
  12637. var bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  12638. var fragDuration = frag.duration;
  12639. var segmentFraction = Math.min(this.config.maxFragLookUpTolerance * 2, fragDuration * 0.25);
  12640. var start = Math.max(Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction), currentTime + segmentFraction);
  12641. if (frag.start - start > segmentFraction) {
  12642. this.flushMainBuffer(start, frag.start);
  12643. }
  12644. };
  12645. _proto.getFwdBufferInfo = function getFwdBufferInfo(bufferable, type) {
  12646. var pos = this.getLoadPosition();
  12647. if (!isFiniteNumber(pos)) {
  12648. return null;
  12649. }
  12650. return this.getFwdBufferInfoAtPos(bufferable, pos, type);
  12651. };
  12652. _proto.getFwdBufferInfoAtPos = function getFwdBufferInfoAtPos(bufferable, pos, type) {
  12653. var maxBufferHole = this.config.maxBufferHole;
  12654. var bufferInfo = BufferHelper.bufferInfo(bufferable, pos, maxBufferHole);
  12655. // Workaround flaw in getting forward buffer when maxBufferHole is smaller than gap at current pos
  12656. if (bufferInfo.len === 0 && bufferInfo.nextStart !== undefined) {
  12657. var bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type);
  12658. if (bufferedFragAtPos && bufferInfo.nextStart < bufferedFragAtPos.end) {
  12659. return BufferHelper.bufferInfo(bufferable, pos, Math.max(bufferInfo.nextStart, maxBufferHole));
  12660. }
  12661. }
  12662. return bufferInfo;
  12663. };
  12664. _proto.getMaxBufferLength = function getMaxBufferLength(levelBitrate) {
  12665. var config = this.config;
  12666. var maxBufLen;
  12667. if (levelBitrate) {
  12668. maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
  12669. } else {
  12670. maxBufLen = config.maxBufferLength;
  12671. }
  12672. return Math.min(maxBufLen, config.maxMaxBufferLength);
  12673. };
  12674. _proto.reduceMaxBufferLength = function reduceMaxBufferLength(threshold, fragDuration) {
  12675. var config = this.config;
  12676. var minLength = Math.max(Math.min(threshold - fragDuration, config.maxBufferLength), fragDuration);
  12677. var reducedLength = Math.max(threshold - fragDuration * 3, config.maxMaxBufferLength / 2, minLength);
  12678. if (reducedLength >= minLength) {
  12679. // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
  12680. config.maxMaxBufferLength = reducedLength;
  12681. this.warn("Reduce max buffer length to " + reducedLength + "s");
  12682. return true;
  12683. }
  12684. return false;
  12685. };
  12686. _proto.getAppendedFrag = function getAppendedFrag(position, playlistType) {
  12687. var fragOrPart = this.fragmentTracker.getAppendedFrag(position, PlaylistLevelType.MAIN);
  12688. if (fragOrPart && 'fragment' in fragOrPart) {
  12689. return fragOrPart.fragment;
  12690. }
  12691. return fragOrPart;
  12692. };
  12693. _proto.getNextFragment = function getNextFragment(pos, levelDetails) {
  12694. var fragments = levelDetails.fragments;
  12695. var fragLen = fragments.length;
  12696. if (!fragLen) {
  12697. return null;
  12698. }
  12699. // find fragment index, contiguous with end of buffer position
  12700. var config = this.config;
  12701. var start = fragments[0].start;
  12702. var frag;
  12703. if (levelDetails.live) {
  12704. var initialLiveManifestSize = config.initialLiveManifestSize;
  12705. if (fragLen < initialLiveManifestSize) {
  12706. this.warn("Not enough fragments to start playback (have: " + fragLen + ", need: " + initialLiveManifestSize + ")");
  12707. return null;
  12708. }
  12709. // The real fragment start times for a live stream are only known after the PTS range for that level is known.
  12710. // In order to discover the range, we load the best matching fragment for that level and demux it.
  12711. // Do not load using live logic if the starting frag is requested - we want to use getFragmentAtPosition() so that
  12712. // we get the fragment matching that start time
  12713. if (!levelDetails.PTSKnown && !this.startFragRequested && this.startPosition === -1 || pos < start) {
  12714. frag = this.getInitialLiveFragment(levelDetails, fragments);
  12715. this.startPosition = this.nextLoadPosition = frag ? this.hls.liveSyncPosition || frag.start : pos;
  12716. }
  12717. } else if (pos <= start) {
  12718. // VoD playlist: if loadPosition before start of playlist, load first fragment
  12719. frag = fragments[0];
  12720. }
  12721. // If we haven't run into any special cases already, just load the fragment most closely matching the requested position
  12722. if (!frag) {
  12723. var end = config.lowLatencyMode ? levelDetails.partEnd : levelDetails.fragmentEnd;
  12724. frag = this.getFragmentAtPosition(pos, end, levelDetails);
  12725. }
  12726. return this.mapToInitFragWhenRequired(frag);
  12727. };
  12728. _proto.isLoopLoading = function isLoopLoading(frag, targetBufferTime) {
  12729. var trackerState = this.fragmentTracker.getState(frag);
  12730. return (trackerState === FragmentState.OK || trackerState === FragmentState.PARTIAL && !!frag.gap) && this.nextLoadPosition > targetBufferTime;
  12731. };
  12732. _proto.getNextFragmentLoopLoading = function getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, playlistType, maxBufLen) {
  12733. var gapStart = frag.gap;
  12734. var nextFragment = this.getNextFragment(this.nextLoadPosition, levelDetails);
  12735. if (nextFragment === null) {
  12736. return nextFragment;
  12737. }
  12738. frag = nextFragment;
  12739. if (gapStart && frag && !frag.gap && bufferInfo.nextStart) {
  12740. // Media buffered after GAP tags should not make the next buffer timerange exceed forward buffer length
  12741. var nextbufferInfo = this.getFwdBufferInfoAtPos(this.mediaBuffer ? this.mediaBuffer : this.media, bufferInfo.nextStart, playlistType);
  12742. if (nextbufferInfo !== null && bufferInfo.len + nextbufferInfo.len >= maxBufLen) {
  12743. // Returning here might result in not finding an audio and video candiate to skip to
  12744. this.log("buffer full after gaps in \"" + playlistType + "\" playlist starting at sn: " + frag.sn);
  12745. return null;
  12746. }
  12747. }
  12748. return frag;
  12749. };
  12750. _proto.mapToInitFragWhenRequired = function mapToInitFragWhenRequired(frag) {
  12751. // If an initSegment is present, it must be buffered first
  12752. if (frag != null && frag.initSegment && !(frag != null && frag.initSegment.data) && !this.bitrateTest) {
  12753. return frag.initSegment;
  12754. }
  12755. return frag;
  12756. };
  12757. _proto.getNextPart = function getNextPart(partList, frag, targetBufferTime) {
  12758. var nextPart = -1;
  12759. var contiguous = false;
  12760. var independentAttrOmitted = true;
  12761. for (var i = 0, len = partList.length; i < len; i++) {
  12762. var part = partList[i];
  12763. independentAttrOmitted = independentAttrOmitted && !part.independent;
  12764. if (nextPart > -1 && targetBufferTime < part.start) {
  12765. break;
  12766. }
  12767. var loaded = part.loaded;
  12768. if (loaded) {
  12769. nextPart = -1;
  12770. } else if ((contiguous || part.independent || independentAttrOmitted) && part.fragment === frag) {
  12771. nextPart = i;
  12772. }
  12773. contiguous = loaded;
  12774. }
  12775. return nextPart;
  12776. };
  12777. _proto.loadedEndOfParts = function loadedEndOfParts(partList, targetBufferTime) {
  12778. var lastPart = partList[partList.length - 1];
  12779. return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;
  12780. }
  12781. /*
  12782. This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the
  12783. "sliding" of the playlist, which is its offset from the start of playback. After sliding we can compute the real
  12784. start and end times for each fragment in the playlist (after which this method will not need to be called).
  12785. */;
  12786. _proto.getInitialLiveFragment = function getInitialLiveFragment(levelDetails, fragments) {
  12787. var fragPrevious = this.fragPrevious;
  12788. var frag = null;
  12789. if (fragPrevious) {
  12790. if (levelDetails.hasProgramDateTime) {
  12791. // Prefer using PDT, because it can be accurate enough to choose the correct fragment without knowing the level sliding
  12792. this.log("Live playlist, switching playlist, load frag with same PDT: " + fragPrevious.programDateTime);
  12793. frag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, this.config.maxFragLookUpTolerance);
  12794. }
  12795. if (!frag) {
  12796. // SN does not need to be accurate between renditions, but depending on the packaging it may be so.
  12797. var targetSN = fragPrevious.sn + 1;
  12798. if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
  12799. var fragNext = fragments[targetSN - levelDetails.startSN];
  12800. // Ensure that we're staying within the continuity range, since PTS resets upon a new range
  12801. if (fragPrevious.cc === fragNext.cc) {
  12802. frag = fragNext;
  12803. this.log("Live playlist, switching playlist, load frag with next SN: " + frag.sn);
  12804. }
  12805. }
  12806. // It's important to stay within the continuity range if available; otherwise the fragments in the playlist
  12807. // will have the wrong start times
  12808. if (!frag) {
  12809. frag = findFragWithCC(fragments, fragPrevious.cc);
  12810. if (frag) {
  12811. this.log("Live playlist, switching playlist, load frag with same CC: " + frag.sn);
  12812. }
  12813. }
  12814. }
  12815. } else {
  12816. // Find a new start fragment when fragPrevious is null
  12817. var liveStart = this.hls.liveSyncPosition;
  12818. if (liveStart !== null) {
  12819. frag = this.getFragmentAtPosition(liveStart, this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge, levelDetails);
  12820. }
  12821. }
  12822. return frag;
  12823. }
  12824. /*
  12825. This method finds the best matching fragment given the provided position.
  12826. */;
  12827. _proto.getFragmentAtPosition = function getFragmentAtPosition(bufferEnd, end, levelDetails) {
  12828. var config = this.config;
  12829. var fragPrevious = this.fragPrevious;
  12830. var fragments = levelDetails.fragments,
  12831. endSN = levelDetails.endSN;
  12832. var fragmentHint = levelDetails.fragmentHint;
  12833. var maxFragLookUpTolerance = config.maxFragLookUpTolerance;
  12834. var partList = levelDetails.partList;
  12835. var loadingParts = !!(config.lowLatencyMode && partList != null && partList.length && fragmentHint);
  12836. if (loadingParts && fragmentHint && !this.bitrateTest) {
  12837. // Include incomplete fragment with parts at end
  12838. fragments = fragments.concat(fragmentHint);
  12839. endSN = fragmentHint.sn;
  12840. }
  12841. var frag;
  12842. if (bufferEnd < end) {
  12843. var lookupTolerance = bufferEnd > end - maxFragLookUpTolerance ? 0 : maxFragLookUpTolerance;
  12844. // Remove the tolerance if it would put the bufferEnd past the actual end of stream
  12845. // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
  12846. frag = findFragmentByPTS(fragPrevious, fragments, bufferEnd, lookupTolerance);
  12847. } else {
  12848. // reach end of playlist
  12849. frag = fragments[fragments.length - 1];
  12850. }
  12851. if (frag) {
  12852. var curSNIdx = frag.sn - levelDetails.startSN;
  12853. // Move fragPrevious forward to support forcing the next fragment to load
  12854. // when the buffer catches up to a previously buffered range.
  12855. var fragState = this.fragmentTracker.getState(frag);
  12856. if (fragState === FragmentState.OK || fragState === FragmentState.PARTIAL && frag.gap) {
  12857. fragPrevious = frag;
  12858. }
  12859. if (fragPrevious && frag.sn === fragPrevious.sn && (!loadingParts || partList[0].fragment.sn > frag.sn)) {
  12860. // Force the next fragment to load if the previous one was already selected. This can occasionally happen with
  12861. // non-uniform fragment durations
  12862. var sameLevel = fragPrevious && frag.level === fragPrevious.level;
  12863. if (sameLevel) {
  12864. var nextFrag = fragments[curSNIdx + 1];
  12865. if (frag.sn < endSN && this.fragmentTracker.getState(nextFrag) !== FragmentState.OK) {
  12866. frag = nextFrag;
  12867. } else {
  12868. frag = null;
  12869. }
  12870. }
  12871. }
  12872. }
  12873. return frag;
  12874. };
  12875. _proto.synchronizeToLiveEdge = function synchronizeToLiveEdge(levelDetails) {
  12876. var config = this.config,
  12877. media = this.media;
  12878. if (!media) {
  12879. return;
  12880. }
  12881. var liveSyncPosition = this.hls.liveSyncPosition;
  12882. var currentTime = media.currentTime;
  12883. var start = levelDetails.fragments[0].start;
  12884. var end = levelDetails.edge;
  12885. var withinSlidingWindow = currentTime >= start - config.maxFragLookUpTolerance && currentTime <= end;
  12886. // Continue if we can seek forward to sync position or if current time is outside of sliding window
  12887. if (liveSyncPosition !== null && media.duration > liveSyncPosition && (currentTime < liveSyncPosition || !withinSlidingWindow)) {
  12888. // Continue if buffer is starving or if current time is behind max latency
  12889. var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
  12890. if (!withinSlidingWindow && media.readyState < 4 || currentTime < end - maxLatency) {
  12891. if (!this.loadedmetadata) {
  12892. this.nextLoadPosition = liveSyncPosition;
  12893. }
  12894. // Only seek if ready and there is not a significant forward buffer available for playback
  12895. if (media.readyState) {
  12896. this.warn("Playback: " + currentTime.toFixed(3) + " is located too far from the end of live sliding playlist: " + end + ", reset currentTime to : " + liveSyncPosition.toFixed(3));
  12897. media.currentTime = liveSyncPosition;
  12898. }
  12899. }
  12900. }
  12901. };
  12902. _proto.alignPlaylists = function alignPlaylists(details, previousDetails, switchDetails) {
  12903. // FIXME: If not for `shouldAlignOnDiscontinuities` requiring fragPrevious.cc,
  12904. // this could all go in level-helper mergeDetails()
  12905. var length = details.fragments.length;
  12906. if (!length) {
  12907. this.warn("No fragments in live playlist");
  12908. return 0;
  12909. }
  12910. var slidingStart = details.fragments[0].start;
  12911. var firstLevelLoad = !previousDetails;
  12912. var aligned = details.alignedSliding && isFiniteNumber(slidingStart);
  12913. if (firstLevelLoad || !aligned && !slidingStart) {
  12914. var fragPrevious = this.fragPrevious;
  12915. alignStream(fragPrevious, switchDetails, details);
  12916. var alignedSlidingStart = details.fragments[0].start;
  12917. this.log("Live playlist sliding: " + alignedSlidingStart.toFixed(2) + " start-sn: " + (previousDetails ? previousDetails.startSN : 'na') + "->" + details.startSN + " prev-sn: " + (fragPrevious ? fragPrevious.sn : 'na') + " fragments: " + length);
  12918. return alignedSlidingStart;
  12919. }
  12920. return slidingStart;
  12921. };
  12922. _proto.waitForCdnTuneIn = function waitForCdnTuneIn(details) {
  12923. // Wait for Low-Latency CDN Tune-in to get an updated playlist
  12924. var advancePartLimit = 3;
  12925. return details.live && details.canBlockReload && details.partTarget && details.tuneInGoal > Math.max(details.partHoldBack, details.partTarget * advancePartLimit);
  12926. };
  12927. _proto.setStartPosition = function setStartPosition(details, sliding) {
  12928. // compute start position if set to -1. use it straight away if value is defined
  12929. var startPosition = this.startPosition;
  12930. if (startPosition < sliding) {
  12931. startPosition = -1;
  12932. }
  12933. if (startPosition === -1 || this.lastCurrentTime === -1) {
  12934. // Use Playlist EXT-X-START:TIME-OFFSET when set
  12935. // Prioritize Multivariant Playlist offset so that main, audio, and subtitle stream-controller start times match
  12936. var offsetInMultivariantPlaylist = this.startTimeOffset !== null;
  12937. var startTimeOffset = offsetInMultivariantPlaylist ? this.startTimeOffset : details.startTimeOffset;
  12938. if (startTimeOffset !== null && isFiniteNumber(startTimeOffset)) {
  12939. startPosition = sliding + startTimeOffset;
  12940. if (startTimeOffset < 0) {
  12941. startPosition += details.totalduration;
  12942. }
  12943. startPosition = Math.min(Math.max(sliding, startPosition), sliding + details.totalduration);
  12944. this.log("Start time offset " + startTimeOffset + " found in " + (offsetInMultivariantPlaylist ? 'multivariant' : 'media') + " playlist, adjust startPosition to " + startPosition);
  12945. this.startPosition = startPosition;
  12946. } else if (details.live) {
  12947. // Leave this.startPosition at -1, so that we can use `getInitialLiveFragment` logic when startPosition has
  12948. // not been specified via the config or an as an argument to startLoad (#3736).
  12949. startPosition = this.hls.liveSyncPosition || sliding;
  12950. } else {
  12951. this.startPosition = startPosition = 0;
  12952. }
  12953. this.lastCurrentTime = startPosition;
  12954. }
  12955. this.nextLoadPosition = startPosition;
  12956. };
  12957. _proto.getLoadPosition = function getLoadPosition() {
  12958. var media = this.media;
  12959. // if we have not yet loaded any fragment, start loading from start position
  12960. var pos = 0;
  12961. if (this.loadedmetadata && media) {
  12962. pos = media.currentTime;
  12963. } else if (this.nextLoadPosition) {
  12964. pos = this.nextLoadPosition;
  12965. }
  12966. return pos;
  12967. };
  12968. _proto.handleFragLoadAborted = function handleFragLoadAborted(frag, part) {
  12969. if (this.transmuxer && frag.sn !== 'initSegment' && frag.stats.aborted) {
  12970. this.warn("Fragment " + frag.sn + (part ? ' part ' + part.index : '') + " of level " + frag.level + " was aborted");
  12971. this.resetFragmentLoading(frag);
  12972. }
  12973. };
  12974. _proto.resetFragmentLoading = function resetFragmentLoading(frag) {
  12975. if (!this.fragCurrent || !this.fragContextChanged(frag) && this.state !== State.FRAG_LOADING_WAITING_RETRY) {
  12976. this.state = State.IDLE;
  12977. }
  12978. };
  12979. _proto.onFragmentOrKeyLoadError = function onFragmentOrKeyLoadError(filterType, data) {
  12980. if (data.chunkMeta && !data.frag) {
  12981. var context = this.getCurrentContext(data.chunkMeta);
  12982. if (context) {
  12983. data.frag = context.frag;
  12984. }
  12985. }
  12986. var frag = data.frag;
  12987. // Handle frag error related to caller's filterType
  12988. if (!frag || frag.type !== filterType || !this.levels) {
  12989. return;
  12990. }
  12991. if (this.fragContextChanged(frag)) {
  12992. var _this$fragCurrent2;
  12993. this.warn("Frag load error must match current frag to retry " + frag.url + " > " + ((_this$fragCurrent2 = this.fragCurrent) == null ? void 0 : _this$fragCurrent2.url));
  12994. return;
  12995. }
  12996. var gapTagEncountered = data.details === ErrorDetails.FRAG_GAP;
  12997. if (gapTagEncountered) {
  12998. this.fragmentTracker.fragBuffered(frag, true);
  12999. }
  13000. // keep retrying until the limit will be reached
  13001. var errorAction = data.errorAction;
  13002. var _ref2 = errorAction || {},
  13003. action = _ref2.action,
  13004. _ref2$retryCount = _ref2.retryCount,
  13005. retryCount = _ref2$retryCount === void 0 ? 0 : _ref2$retryCount,
  13006. retryConfig = _ref2.retryConfig;
  13007. if (errorAction && action === NetworkErrorAction.RetryRequest && retryConfig) {
  13008. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  13009. var delay = getRetryDelay(retryConfig, retryCount);
  13010. this.warn("Fragment " + frag.sn + " of " + filterType + " " + frag.level + " errored with " + data.details + ", retrying loading " + (retryCount + 1) + "/" + retryConfig.maxNumRetry + " in " + delay + "ms");
  13011. errorAction.resolved = true;
  13012. this.retryDate = self.performance.now() + delay;
  13013. this.state = State.FRAG_LOADING_WAITING_RETRY;
  13014. } else if (retryConfig && errorAction) {
  13015. this.resetFragmentErrors(filterType);
  13016. if (retryCount < retryConfig.maxNumRetry) {
  13017. // Network retry is skipped when level switch is preferred
  13018. if (!gapTagEncountered && action !== NetworkErrorAction.RemoveAlternatePermanently) {
  13019. errorAction.resolved = true;
  13020. }
  13021. } else {
  13022. logger.warn(data.details + " reached or exceeded max retry (" + retryCount + ")");
  13023. return;
  13024. }
  13025. } else if ((errorAction == null ? void 0 : errorAction.action) === NetworkErrorAction.SendAlternateToPenaltyBox) {
  13026. this.state = State.WAITING_LEVEL;
  13027. } else {
  13028. this.state = State.ERROR;
  13029. }
  13030. // Perform next async tick sooner to speed up error action resolution
  13031. this.tickImmediate();
  13032. };
  13033. _proto.reduceLengthAndFlushBuffer = function reduceLengthAndFlushBuffer(data) {
  13034. // if in appending state
  13035. if (this.state === State.PARSING || this.state === State.PARSED) {
  13036. var frag = data.frag;
  13037. var playlistType = data.parent;
  13038. var bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  13039. // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
  13040. // reduce max buf len if current position is buffered
  13041. var buffered = bufferedInfo && bufferedInfo.len > 0.5;
  13042. if (buffered) {
  13043. this.reduceMaxBufferLength(bufferedInfo.len, (frag == null ? void 0 : frag.duration) || 10);
  13044. }
  13045. var flushBuffer = !buffered;
  13046. if (flushBuffer) {
  13047. // current position is not buffered, but browser is still complaining about buffer full error
  13048. // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
  13049. // in that case flush the whole audio buffer to recover
  13050. this.warn("Buffer full error while media.currentTime is not buffered, flush " + playlistType + " buffer");
  13051. }
  13052. if (frag) {
  13053. this.fragmentTracker.removeFragment(frag);
  13054. this.nextLoadPosition = frag.start;
  13055. }
  13056. this.resetLoadingState();
  13057. return flushBuffer;
  13058. }
  13059. return false;
  13060. };
  13061. _proto.resetFragmentErrors = function resetFragmentErrors(filterType) {
  13062. if (filterType === PlaylistLevelType.AUDIO) {
  13063. // Reset current fragment since audio track audio is essential and may not have a fail-over track
  13064. this.fragCurrent = null;
  13065. }
  13066. // Fragment errors that result in a level switch or redundant fail-over
  13067. // should reset the stream controller state to idle
  13068. if (!this.loadedmetadata) {
  13069. this.startFragRequested = false;
  13070. }
  13071. if (this.state !== State.STOPPED) {
  13072. this.state = State.IDLE;
  13073. }
  13074. };
  13075. _proto.afterBufferFlushed = function afterBufferFlushed(media, bufferType, playlistType) {
  13076. if (!media) {
  13077. return;
  13078. }
  13079. // After successful buffer flushing, filter flushed fragments from bufferedFrags use mediaBuffered instead of media
  13080. // (so that we will check against video.buffered ranges in case of alt audio track)
  13081. var bufferedTimeRanges = BufferHelper.getBuffered(media);
  13082. this.fragmentTracker.detectEvictedFragments(bufferType, bufferedTimeRanges, playlistType);
  13083. if (this.state === State.ENDED) {
  13084. this.resetLoadingState();
  13085. }
  13086. };
  13087. _proto.resetLoadingState = function resetLoadingState() {
  13088. this.log('Reset loading state');
  13089. this.fragCurrent = null;
  13090. this.fragPrevious = null;
  13091. this.state = State.IDLE;
  13092. };
  13093. _proto.resetStartWhenNotLoaded = function resetStartWhenNotLoaded(level) {
  13094. // if loadedmetadata is not set, it means that first frag request failed
  13095. // in that case, reset startFragRequested flag
  13096. if (!this.loadedmetadata) {
  13097. this.startFragRequested = false;
  13098. var details = level ? level.details : null;
  13099. if (details != null && details.live) {
  13100. // Update the start position and return to IDLE to recover live start
  13101. this.startPosition = -1;
  13102. this.setStartPosition(details, 0);
  13103. this.resetLoadingState();
  13104. } else {
  13105. this.nextLoadPosition = this.startPosition;
  13106. }
  13107. }
  13108. };
  13109. _proto.resetWhenMissingContext = function resetWhenMissingContext(chunkMeta) {
  13110. this.warn("The loading context changed while buffering fragment " + chunkMeta.sn + " of level " + chunkMeta.level + ". This chunk will not be buffered.");
  13111. this.removeUnbufferedFrags();
  13112. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  13113. this.resetLoadingState();
  13114. };
  13115. _proto.removeUnbufferedFrags = function removeUnbufferedFrags(start) {
  13116. if (start === void 0) {
  13117. start = 0;
  13118. }
  13119. this.fragmentTracker.removeFragmentsInRange(start, Infinity, this.playlistType, false, true);
  13120. };
  13121. _proto.updateLevelTiming = function updateLevelTiming(frag, part, level, partial) {
  13122. var _this6 = this,
  13123. _this$transmuxer;
  13124. var details = level.details;
  13125. if (!details) {
  13126. this.warn('level.details undefined');
  13127. return;
  13128. }
  13129. var parsed = Object.keys(frag.elementaryStreams).reduce(function (result, type) {
  13130. var info = frag.elementaryStreams[type];
  13131. if (info) {
  13132. var parsedDuration = info.endPTS - info.startPTS;
  13133. if (parsedDuration <= 0) {
  13134. // Destroy the transmuxer after it's next time offset failed to advance because duration was <= 0.
  13135. // The new transmuxer will be configured with a time offset matching the next fragment start,
  13136. // preventing the timeline from shifting.
  13137. _this6.warn("Could not parse fragment " + frag.sn + " " + type + " duration reliably (" + parsedDuration + ")");
  13138. return result || false;
  13139. }
  13140. var drift = partial ? 0 : updateFragPTSDTS(details, frag, info.startPTS, info.endPTS, info.startDTS, info.endDTS);
  13141. _this6.hls.trigger(Events.LEVEL_PTS_UPDATED, {
  13142. details: details,
  13143. level: level,
  13144. drift: drift,
  13145. type: type,
  13146. frag: frag,
  13147. start: info.startPTS,
  13148. end: info.endPTS
  13149. });
  13150. return true;
  13151. }
  13152. return result;
  13153. }, false);
  13154. if (!parsed && ((_this$transmuxer = this.transmuxer) == null ? void 0 : _this$transmuxer.error) === null) {
  13155. var error = new Error("Found no media in fragment " + frag.sn + " of level " + frag.level + " resetting transmuxer to fallback to playlist timing");
  13156. if (level.fragmentError === 0) {
  13157. // Mark and track the odd empty segment as a gap to avoid reloading
  13158. level.fragmentError++;
  13159. frag.gap = true;
  13160. this.fragmentTracker.removeFragment(frag);
  13161. this.fragmentTracker.fragBuffered(frag, true);
  13162. }
  13163. this.warn(error.message);
  13164. this.hls.trigger(Events.ERROR, {
  13165. type: ErrorTypes.MEDIA_ERROR,
  13166. details: ErrorDetails.FRAG_PARSING_ERROR,
  13167. fatal: false,
  13168. error: error,
  13169. frag: frag,
  13170. reason: "Found no media in msn " + frag.sn + " of level \"" + level.url + "\""
  13171. });
  13172. if (!this.hls) {
  13173. return;
  13174. }
  13175. this.resetTransmuxer();
  13176. // For this error fallthrough. Marking parsed will allow advancing to next fragment.
  13177. }
  13178. this.state = State.PARSED;
  13179. this.hls.trigger(Events.FRAG_PARSED, {
  13180. frag: frag,
  13181. part: part
  13182. });
  13183. };
  13184. _proto.resetTransmuxer = function resetTransmuxer() {
  13185. if (this.transmuxer) {
  13186. this.transmuxer.destroy();
  13187. this.transmuxer = null;
  13188. }
  13189. };
  13190. _proto.recoverWorkerError = function recoverWorkerError(data) {
  13191. if (data.event === 'demuxerWorker') {
  13192. this.fragmentTracker.removeAllFragments();
  13193. this.resetTransmuxer();
  13194. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  13195. this.resetLoadingState();
  13196. }
  13197. };
  13198. _createClass(BaseStreamController, [{
  13199. key: "state",
  13200. get: function get() {
  13201. return this._state;
  13202. },
  13203. set: function set(nextState) {
  13204. var previousState = this._state;
  13205. if (previousState !== nextState) {
  13206. this._state = nextState;
  13207. this.log(previousState + "->" + nextState);
  13208. }
  13209. }
  13210. }]);
  13211. return BaseStreamController;
  13212. }(TaskLoop);
  13213. function getSourceBuffer() {
  13214. return self.SourceBuffer || self.WebKitSourceBuffer;
  13215. }
  13216. function isMSESupported() {
  13217. var mediaSource = getMediaSource();
  13218. if (!mediaSource) {
  13219. return false;
  13220. }
  13221. // if SourceBuffer is exposed ensure its API is valid
  13222. // Older browsers do not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible
  13223. var sourceBuffer = getSourceBuffer();
  13224. return !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function';
  13225. }
  13226. function isSupported() {
  13227. if (!isMSESupported()) {
  13228. return false;
  13229. }
  13230. var mediaSource = getMediaSource();
  13231. 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) {
  13232. return mediaSource.isTypeSupported(mimeTypeForCodec(codecsForVideoContainer, 'video'));
  13233. }) || ['mp4a.40.2', 'fLaC'].some(function (codecForAudioContainer) {
  13234. return mediaSource.isTypeSupported(mimeTypeForCodec(codecForAudioContainer, 'audio'));
  13235. }));
  13236. }
  13237. function changeTypeSupported() {
  13238. var _sourceBuffer$prototy;
  13239. var sourceBuffer = getSourceBuffer();
  13240. return typeof (sourceBuffer == null ? void 0 : (_sourceBuffer$prototy = sourceBuffer.prototype) == null ? void 0 : _sourceBuffer$prototy.changeType) === 'function';
  13241. }
  13242. function dummyTrack(type, inputTimeScale) {
  13243. if (type === void 0) {
  13244. type = '';
  13245. }
  13246. if (inputTimeScale === void 0) {
  13247. inputTimeScale = 90000;
  13248. }
  13249. return {
  13250. type: type,
  13251. id: -1,
  13252. pid: -1,
  13253. inputTimeScale: inputTimeScale,
  13254. sequenceNumber: -1,
  13255. samples: [],
  13256. dropped: 0
  13257. };
  13258. }
  13259. var BaseAudioDemuxer = /*#__PURE__*/function () {
  13260. function BaseAudioDemuxer() {
  13261. this._audioTrack = void 0;
  13262. this._id3Track = void 0;
  13263. this.frameIndex = 0;
  13264. this.cachedData = null;
  13265. this.basePTS = null;
  13266. this.initPTS = null;
  13267. this.lastPTS = null;
  13268. }
  13269. var _proto = BaseAudioDemuxer.prototype;
  13270. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  13271. this._id3Track = {
  13272. type: 'id3',
  13273. id: 3,
  13274. pid: -1,
  13275. inputTimeScale: 90000,
  13276. sequenceNumber: 0,
  13277. samples: [],
  13278. dropped: 0
  13279. };
  13280. };
  13281. _proto.resetTimeStamp = function resetTimeStamp(deaultTimestamp) {
  13282. this.initPTS = deaultTimestamp;
  13283. this.resetContiguity();
  13284. };
  13285. _proto.resetContiguity = function resetContiguity() {
  13286. this.basePTS = null;
  13287. this.lastPTS = null;
  13288. this.frameIndex = 0;
  13289. };
  13290. _proto.canParse = function canParse(data, offset) {
  13291. return false;
  13292. };
  13293. _proto.appendFrame = function appendFrame(track, data, offset) {}
  13294. // feed incoming data to the front of the parsing pipeline
  13295. ;
  13296. _proto.demux = function demux(data, timeOffset) {
  13297. if (this.cachedData) {
  13298. data = appendUint8Array(this.cachedData, data);
  13299. this.cachedData = null;
  13300. }
  13301. var id3Data = getID3Data(data, 0);
  13302. var offset = id3Data ? id3Data.length : 0;
  13303. var lastDataIndex;
  13304. var track = this._audioTrack;
  13305. var id3Track = this._id3Track;
  13306. var timestamp = id3Data ? getTimeStamp(id3Data) : undefined;
  13307. var length = data.length;
  13308. if (this.basePTS === null || this.frameIndex === 0 && isFiniteNumber(timestamp)) {
  13309. this.basePTS = initPTSFn(timestamp, timeOffset, this.initPTS);
  13310. this.lastPTS = this.basePTS;
  13311. }
  13312. if (this.lastPTS === null) {
  13313. this.lastPTS = this.basePTS;
  13314. }
  13315. // more expressive than alternative: id3Data?.length
  13316. if (id3Data && id3Data.length > 0) {
  13317. id3Track.samples.push({
  13318. pts: this.lastPTS,
  13319. dts: this.lastPTS,
  13320. data: id3Data,
  13321. type: MetadataSchema.audioId3,
  13322. duration: Number.POSITIVE_INFINITY
  13323. });
  13324. }
  13325. while (offset < length) {
  13326. if (this.canParse(data, offset)) {
  13327. var frame = this.appendFrame(track, data, offset);
  13328. if (frame) {
  13329. this.frameIndex++;
  13330. this.lastPTS = frame.sample.pts;
  13331. offset += frame.length;
  13332. lastDataIndex = offset;
  13333. } else {
  13334. offset = length;
  13335. }
  13336. } else if (canParse$2(data, offset)) {
  13337. // after a ID3.canParse, a call to ID3.getID3Data *should* always returns some data
  13338. id3Data = getID3Data(data, offset);
  13339. id3Track.samples.push({
  13340. pts: this.lastPTS,
  13341. dts: this.lastPTS,
  13342. data: id3Data,
  13343. type: MetadataSchema.audioId3,
  13344. duration: Number.POSITIVE_INFINITY
  13345. });
  13346. offset += id3Data.length;
  13347. lastDataIndex = offset;
  13348. } else {
  13349. offset++;
  13350. }
  13351. if (offset === length && lastDataIndex !== length) {
  13352. var partialData = sliceUint8(data, lastDataIndex);
  13353. if (this.cachedData) {
  13354. this.cachedData = appendUint8Array(this.cachedData, partialData);
  13355. } else {
  13356. this.cachedData = partialData;
  13357. }
  13358. }
  13359. }
  13360. return {
  13361. audioTrack: track,
  13362. videoTrack: dummyTrack(),
  13363. id3Track: id3Track,
  13364. textTrack: dummyTrack()
  13365. };
  13366. };
  13367. _proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
  13368. return Promise.reject(new Error("[" + this + "] This demuxer does not support Sample-AES decryption"));
  13369. };
  13370. _proto.flush = function flush(timeOffset) {
  13371. // Parse cache in case of remaining frames.
  13372. var cachedData = this.cachedData;
  13373. if (cachedData) {
  13374. this.cachedData = null;
  13375. this.demux(cachedData, 0);
  13376. }
  13377. return {
  13378. audioTrack: this._audioTrack,
  13379. videoTrack: dummyTrack(),
  13380. id3Track: this._id3Track,
  13381. textTrack: dummyTrack()
  13382. };
  13383. };
  13384. _proto.destroy = function destroy() {};
  13385. return BaseAudioDemuxer;
  13386. }();
  13387. /**
  13388. * Initialize PTS
  13389. * <p>
  13390. * use timestamp unless it is undefined, NaN or Infinity
  13391. * </p>
  13392. */
  13393. var initPTSFn = function initPTSFn(timestamp, timeOffset, initPTS) {
  13394. if (isFiniteNumber(timestamp)) {
  13395. return timestamp * 90;
  13396. }
  13397. var init90kHz = initPTS ? initPTS.baseTime * 90000 / initPTS.timescale : 0;
  13398. return timeOffset * 90000 + init90kHz;
  13399. };
  13400. /**
  13401. * ADTS parser helper
  13402. * @link https://wiki.multimedia.cx/index.php?title=ADTS
  13403. */
  13404. function getAudioConfig(observer, data, offset, audioCodec) {
  13405. var adtsObjectType;
  13406. var adtsExtensionSamplingIndex;
  13407. var adtsChannelConfig;
  13408. var config;
  13409. var userAgent = navigator.userAgent.toLowerCase();
  13410. var manifestCodec = audioCodec;
  13411. var adtsSamplingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  13412. // byte 2
  13413. adtsObjectType = ((data[offset + 2] & 0xc0) >>> 6) + 1;
  13414. var adtsSamplingIndex = (data[offset + 2] & 0x3c) >>> 2;
  13415. if (adtsSamplingIndex > adtsSamplingRates.length - 1) {
  13416. var error = new Error("invalid ADTS sampling index:" + adtsSamplingIndex);
  13417. observer.emit(Events.ERROR, Events.ERROR, {
  13418. type: ErrorTypes.MEDIA_ERROR,
  13419. details: ErrorDetails.FRAG_PARSING_ERROR,
  13420. fatal: true,
  13421. error: error,
  13422. reason: error.message
  13423. });
  13424. return;
  13425. }
  13426. adtsChannelConfig = (data[offset + 2] & 0x01) << 2;
  13427. // byte 3
  13428. adtsChannelConfig |= (data[offset + 3] & 0xc0) >>> 6;
  13429. logger.log("manifest codec:" + audioCodec + ", ADTS type:" + adtsObjectType + ", samplingIndex:" + adtsSamplingIndex);
  13430. // firefox: freq less than 24kHz = AAC SBR (HE-AAC)
  13431. if (/firefox/i.test(userAgent)) {
  13432. if (adtsSamplingIndex >= 6) {
  13433. adtsObjectType = 5;
  13434. config = new Array(4);
  13435. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  13436. // there is a factor 2 between frame sample rate and output sample rate
  13437. // multiply frequency by 2 (see table below, equivalent to substract 3)
  13438. adtsExtensionSamplingIndex = adtsSamplingIndex - 3;
  13439. } else {
  13440. adtsObjectType = 2;
  13441. config = new Array(2);
  13442. adtsExtensionSamplingIndex = adtsSamplingIndex;
  13443. }
  13444. // Android : always use AAC
  13445. } else if (userAgent.indexOf('android') !== -1) {
  13446. adtsObjectType = 2;
  13447. config = new Array(2);
  13448. adtsExtensionSamplingIndex = adtsSamplingIndex;
  13449. } else {
  13450. /* for other browsers (Chrome/Vivaldi/Opera ...)
  13451. always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)
  13452. */
  13453. adtsObjectType = 5;
  13454. config = new Array(4);
  13455. // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)
  13456. if (audioCodec && (audioCodec.indexOf('mp4a.40.29') !== -1 || audioCodec.indexOf('mp4a.40.5') !== -1) || !audioCodec && adtsSamplingIndex >= 6) {
  13457. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  13458. // there is a factor 2 between frame sample rate and output sample rate
  13459. // multiply frequency by 2 (see table below, equivalent to substract 3)
  13460. adtsExtensionSamplingIndex = adtsSamplingIndex - 3;
  13461. } else {
  13462. // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)
  13463. // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.
  13464. if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && (adtsSamplingIndex >= 6 && adtsChannelConfig === 1 || /vivaldi/i.test(userAgent)) || !audioCodec && adtsChannelConfig === 1) {
  13465. adtsObjectType = 2;
  13466. config = new Array(2);
  13467. }
  13468. adtsExtensionSamplingIndex = adtsSamplingIndex;
  13469. }
  13470. }
  13471. /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config
  13472. ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()
  13473. Audio Profile / Audio Object Type
  13474. 0: Null
  13475. 1: AAC Main
  13476. 2: AAC LC (Low Complexity)
  13477. 3: AAC SSR (Scalable Sample Rate)
  13478. 4: AAC LTP (Long Term Prediction)
  13479. 5: SBR (Spectral Band Replication)
  13480. 6: AAC Scalable
  13481. sampling freq
  13482. 0: 96000 Hz
  13483. 1: 88200 Hz
  13484. 2: 64000 Hz
  13485. 3: 48000 Hz
  13486. 4: 44100 Hz
  13487. 5: 32000 Hz
  13488. 6: 24000 Hz
  13489. 7: 22050 Hz
  13490. 8: 16000 Hz
  13491. 9: 12000 Hz
  13492. 10: 11025 Hz
  13493. 11: 8000 Hz
  13494. 12: 7350 Hz
  13495. 13: Reserved
  13496. 14: Reserved
  13497. 15: frequency is written explictly
  13498. Channel Configurations
  13499. These are the channel configurations:
  13500. 0: Defined in AOT Specifc Config
  13501. 1: 1 channel: front-center
  13502. 2: 2 channels: front-left, front-right
  13503. */
  13504. // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1
  13505. config[0] = adtsObjectType << 3;
  13506. // samplingFrequencyIndex
  13507. config[0] |= (adtsSamplingIndex & 0x0e) >> 1;
  13508. config[1] |= (adtsSamplingIndex & 0x01) << 7;
  13509. // channelConfiguration
  13510. config[1] |= adtsChannelConfig << 3;
  13511. if (adtsObjectType === 5) {
  13512. // adtsExtensionSamplingIndex
  13513. config[1] |= (adtsExtensionSamplingIndex & 0x0e) >> 1;
  13514. config[2] = (adtsExtensionSamplingIndex & 0x01) << 7;
  13515. // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???
  13516. // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc
  13517. config[2] |= 2 << 2;
  13518. config[3] = 0;
  13519. }
  13520. return {
  13521. config: config,
  13522. samplerate: adtsSamplingRates[adtsSamplingIndex],
  13523. channelCount: adtsChannelConfig,
  13524. codec: 'mp4a.40.' + adtsObjectType,
  13525. manifestCodec: manifestCodec
  13526. };
  13527. }
  13528. function isHeaderPattern$1(data, offset) {
  13529. return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;
  13530. }
  13531. function getHeaderLength(data, offset) {
  13532. return data[offset + 1] & 0x01 ? 7 : 9;
  13533. }
  13534. function getFullFrameLength(data, offset) {
  13535. return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xe0) >>> 5;
  13536. }
  13537. function canGetFrameLength(data, offset) {
  13538. return offset + 5 < data.length;
  13539. }
  13540. function isHeader$1(data, offset) {
  13541. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  13542. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  13543. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  13544. return offset + 1 < data.length && isHeaderPattern$1(data, offset);
  13545. }
  13546. function canParse$1(data, offset) {
  13547. return canGetFrameLength(data, offset) && isHeaderPattern$1(data, offset) && getFullFrameLength(data, offset) <= data.length - offset;
  13548. }
  13549. function probe$1(data, offset) {
  13550. // same as isHeader but we also check that ADTS frame follows last ADTS frame
  13551. // or end of data is reached
  13552. if (isHeader$1(data, offset)) {
  13553. // ADTS header Length
  13554. var headerLength = getHeaderLength(data, offset);
  13555. if (offset + headerLength >= data.length) {
  13556. return false;
  13557. }
  13558. // ADTS frame Length
  13559. var frameLength = getFullFrameLength(data, offset);
  13560. if (frameLength <= headerLength) {
  13561. return false;
  13562. }
  13563. var newOffset = offset + frameLength;
  13564. return newOffset === data.length || isHeader$1(data, newOffset);
  13565. }
  13566. return false;
  13567. }
  13568. function initTrackConfig(track, observer, data, offset, audioCodec) {
  13569. if (!track.samplerate) {
  13570. var config = getAudioConfig(observer, data, offset, audioCodec);
  13571. if (!config) {
  13572. return;
  13573. }
  13574. track.config = config.config;
  13575. track.samplerate = config.samplerate;
  13576. track.channelCount = config.channelCount;
  13577. track.codec = config.codec;
  13578. track.manifestCodec = config.manifestCodec;
  13579. logger.log("parsed codec:" + track.codec + ", rate:" + config.samplerate + ", channels:" + config.channelCount);
  13580. }
  13581. }
  13582. function getFrameDuration(samplerate) {
  13583. return 1024 * 90000 / samplerate;
  13584. }
  13585. function parseFrameHeader(data, offset) {
  13586. // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
  13587. var headerLength = getHeaderLength(data, offset);
  13588. if (offset + headerLength <= data.length) {
  13589. // retrieve frame size
  13590. var frameLength = getFullFrameLength(data, offset) - headerLength;
  13591. if (frameLength > 0) {
  13592. // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}`);
  13593. return {
  13594. headerLength: headerLength,
  13595. frameLength: frameLength
  13596. };
  13597. }
  13598. }
  13599. }
  13600. function appendFrame$1(track, data, offset, pts, frameIndex) {
  13601. var frameDuration = getFrameDuration(track.samplerate);
  13602. var stamp = pts + frameIndex * frameDuration;
  13603. var header = parseFrameHeader(data, offset);
  13604. var unit;
  13605. if (header) {
  13606. var frameLength = header.frameLength,
  13607. headerLength = header.headerLength;
  13608. var _length = headerLength + frameLength;
  13609. var missing = Math.max(0, offset + _length - data.length);
  13610. // logger.log(`AAC frame ${frameIndex}, pts:${stamp} length@offset/total: ${frameLength}@${offset+headerLength}/${data.byteLength} missing: ${missing}`);
  13611. if (missing) {
  13612. unit = new Uint8Array(_length - headerLength);
  13613. unit.set(data.subarray(offset + headerLength, data.length), 0);
  13614. } else {
  13615. unit = data.subarray(offset + headerLength, offset + _length);
  13616. }
  13617. var _sample = {
  13618. unit: unit,
  13619. pts: stamp
  13620. };
  13621. if (!missing) {
  13622. track.samples.push(_sample);
  13623. }
  13624. return {
  13625. sample: _sample,
  13626. length: _length,
  13627. missing: missing
  13628. };
  13629. }
  13630. // overflow incomplete header
  13631. var length = data.length - offset;
  13632. unit = new Uint8Array(length);
  13633. unit.set(data.subarray(offset, data.length), 0);
  13634. var sample = {
  13635. unit: unit,
  13636. pts: stamp
  13637. };
  13638. return {
  13639. sample: sample,
  13640. length: length,
  13641. missing: -1
  13642. };
  13643. }
  13644. /**
  13645. * MPEG parser helper
  13646. */
  13647. var chromeVersion$1 = null;
  13648. 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];
  13649. var SamplingRateMap = [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000];
  13650. var SamplesCoefficients = [
  13651. // MPEG 2.5
  13652. [0,
  13653. // Reserved
  13654. 72,
  13655. // Layer3
  13656. 144,
  13657. // Layer2
  13658. 12 // Layer1
  13659. ],
  13660. // Reserved
  13661. [0,
  13662. // Reserved
  13663. 0,
  13664. // Layer3
  13665. 0,
  13666. // Layer2
  13667. 0 // Layer1
  13668. ],
  13669. // MPEG 2
  13670. [0,
  13671. // Reserved
  13672. 72,
  13673. // Layer3
  13674. 144,
  13675. // Layer2
  13676. 12 // Layer1
  13677. ],
  13678. // MPEG 1
  13679. [0,
  13680. // Reserved
  13681. 144,
  13682. // Layer3
  13683. 144,
  13684. // Layer2
  13685. 12 // Layer1
  13686. ]];
  13687. var BytesInSlot = [0,
  13688. // Reserved
  13689. 1,
  13690. // Layer3
  13691. 1,
  13692. // Layer2
  13693. 4 // Layer1
  13694. ];
  13695. function appendFrame(track, data, offset, pts, frameIndex) {
  13696. // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference
  13697. if (offset + 24 > data.length) {
  13698. return;
  13699. }
  13700. var header = parseHeader(data, offset);
  13701. if (header && offset + header.frameLength <= data.length) {
  13702. var frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;
  13703. var stamp = pts + frameIndex * frameDuration;
  13704. var sample = {
  13705. unit: data.subarray(offset, offset + header.frameLength),
  13706. pts: stamp,
  13707. dts: stamp
  13708. };
  13709. track.config = [];
  13710. track.channelCount = header.channelCount;
  13711. track.samplerate = header.sampleRate;
  13712. track.samples.push(sample);
  13713. return {
  13714. sample: sample,
  13715. length: header.frameLength,
  13716. missing: 0
  13717. };
  13718. }
  13719. }
  13720. function parseHeader(data, offset) {
  13721. var mpegVersion = data[offset + 1] >> 3 & 3;
  13722. var mpegLayer = data[offset + 1] >> 1 & 3;
  13723. var bitRateIndex = data[offset + 2] >> 4 & 15;
  13724. var sampleRateIndex = data[offset + 2] >> 2 & 3;
  13725. if (mpegVersion !== 1 && bitRateIndex !== 0 && bitRateIndex !== 15 && sampleRateIndex !== 3) {
  13726. var paddingBit = data[offset + 2] >> 1 & 1;
  13727. var channelMode = data[offset + 3] >> 6;
  13728. var columnInBitrates = mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4;
  13729. var bitRate = BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1000;
  13730. var columnInSampleRates = mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2;
  13731. var sampleRate = SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex];
  13732. var channelCount = channelMode === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)
  13733. var sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer];
  13734. var bytesInSlot = BytesInSlot[mpegLayer];
  13735. var samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
  13736. var frameLength = Math.floor(sampleCoefficient * bitRate / sampleRate + paddingBit) * bytesInSlot;
  13737. if (chromeVersion$1 === null) {
  13738. var userAgent = navigator.userAgent || '';
  13739. var result = userAgent.match(/Chrome\/(\d+)/i);
  13740. chromeVersion$1 = result ? parseInt(result[1]) : 0;
  13741. }
  13742. var needChromeFix = !!chromeVersion$1 && chromeVersion$1 <= 87;
  13743. if (needChromeFix && mpegLayer === 2 && bitRate >= 224000 && channelMode === 0) {
  13744. // Work around bug in Chromium by setting channelMode to dual-channel (01) instead of stereo (00)
  13745. data[offset + 3] = data[offset + 3] | 0x80;
  13746. }
  13747. return {
  13748. sampleRate: sampleRate,
  13749. channelCount: channelCount,
  13750. frameLength: frameLength,
  13751. samplesPerFrame: samplesPerFrame
  13752. };
  13753. }
  13754. }
  13755. function isHeaderPattern(data, offset) {
  13756. return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;
  13757. }
  13758. function isHeader(data, offset) {
  13759. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  13760. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  13761. // More info http://www.mp3-tech.org/programmer/frame_header.html
  13762. return offset + 1 < data.length && isHeaderPattern(data, offset);
  13763. }
  13764. function canParse(data, offset) {
  13765. var headerSize = 4;
  13766. return isHeaderPattern(data, offset) && headerSize <= data.length - offset;
  13767. }
  13768. function probe(data, offset) {
  13769. // same as isHeader but we also check that MPEG frame follows last MPEG frame
  13770. // or end of data is reached
  13771. if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
  13772. // MPEG header Length
  13773. var headerLength = 4;
  13774. // MPEG frame Length
  13775. var header = parseHeader(data, offset);
  13776. var frameLength = headerLength;
  13777. if (header != null && header.frameLength) {
  13778. frameLength = header.frameLength;
  13779. }
  13780. var newOffset = offset + frameLength;
  13781. return newOffset === data.length || isHeader(data, newOffset);
  13782. }
  13783. return false;
  13784. }
  13785. var AACDemuxer = /*#__PURE__*/function (_BaseAudioDemuxer) {
  13786. _inheritsLoose(AACDemuxer, _BaseAudioDemuxer);
  13787. function AACDemuxer(observer, config) {
  13788. var _this;
  13789. _this = _BaseAudioDemuxer.call(this) || this;
  13790. _this.observer = void 0;
  13791. _this.config = void 0;
  13792. _this.observer = observer;
  13793. _this.config = config;
  13794. return _this;
  13795. }
  13796. var _proto = AACDemuxer.prototype;
  13797. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  13798. _BaseAudioDemuxer.prototype.resetInitSegment.call(this, initSegment, audioCodec, videoCodec, trackDuration);
  13799. this._audioTrack = {
  13800. container: 'audio/adts',
  13801. type: 'audio',
  13802. id: 2,
  13803. pid: -1,
  13804. sequenceNumber: 0,
  13805. segmentCodec: 'aac',
  13806. samples: [],
  13807. manifestCodec: audioCodec,
  13808. duration: trackDuration,
  13809. inputTimeScale: 90000,
  13810. dropped: 0
  13811. };
  13812. }
  13813. // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS
  13814. ;
  13815. AACDemuxer.probe = function probe$2(data) {
  13816. if (!data) {
  13817. return false;
  13818. }
  13819. // Check for the ADTS sync word
  13820. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  13821. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  13822. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  13823. var id3Data = getID3Data(data, 0);
  13824. var offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  13825. if (probe(data, offset)) {
  13826. return false;
  13827. }
  13828. for (var length = data.length; offset < length; offset++) {
  13829. if (probe$1(data, offset)) {
  13830. logger.log('ADTS sync word found !');
  13831. return true;
  13832. }
  13833. }
  13834. return false;
  13835. };
  13836. _proto.canParse = function canParse(data, offset) {
  13837. return canParse$1(data, offset);
  13838. };
  13839. _proto.appendFrame = function appendFrame(track, data, offset) {
  13840. initTrackConfig(track, this.observer, data, offset, track.manifestCodec);
  13841. var frame = appendFrame$1(track, data, offset, this.basePTS, this.frameIndex);
  13842. if (frame && frame.missing === 0) {
  13843. return frame;
  13844. }
  13845. };
  13846. return AACDemuxer;
  13847. }(BaseAudioDemuxer);
  13848. var emsgSchemePattern = /\/emsg[-/]ID3/i;
  13849. var MP4Demuxer = /*#__PURE__*/function () {
  13850. function MP4Demuxer(observer, config) {
  13851. this.remainderData = null;
  13852. this.timeOffset = 0;
  13853. this.config = void 0;
  13854. this.videoTrack = void 0;
  13855. this.audioTrack = void 0;
  13856. this.id3Track = void 0;
  13857. this.txtTrack = void 0;
  13858. this.config = config;
  13859. }
  13860. var _proto = MP4Demuxer.prototype;
  13861. _proto.resetTimeStamp = function resetTimeStamp() {};
  13862. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  13863. var videoTrack = this.videoTrack = dummyTrack('video', 1);
  13864. var audioTrack = this.audioTrack = dummyTrack('audio', 1);
  13865. var captionTrack = this.txtTrack = dummyTrack('text', 1);
  13866. this.id3Track = dummyTrack('id3', 1);
  13867. this.timeOffset = 0;
  13868. if (!(initSegment != null && initSegment.byteLength)) {
  13869. return;
  13870. }
  13871. var initData = parseInitSegment(initSegment);
  13872. if (initData.video) {
  13873. var _initData$video = initData.video,
  13874. id = _initData$video.id,
  13875. timescale = _initData$video.timescale,
  13876. codec = _initData$video.codec;
  13877. videoTrack.id = id;
  13878. videoTrack.timescale = captionTrack.timescale = timescale;
  13879. videoTrack.codec = codec;
  13880. }
  13881. if (initData.audio) {
  13882. var _initData$audio = initData.audio,
  13883. _id = _initData$audio.id,
  13884. _timescale = _initData$audio.timescale,
  13885. _codec = _initData$audio.codec;
  13886. audioTrack.id = _id;
  13887. audioTrack.timescale = _timescale;
  13888. audioTrack.codec = _codec;
  13889. }
  13890. captionTrack.id = RemuxerTrackIdConfig.text;
  13891. videoTrack.sampleDuration = 0;
  13892. videoTrack.duration = audioTrack.duration = trackDuration;
  13893. };
  13894. _proto.resetContiguity = function resetContiguity() {
  13895. this.remainderData = null;
  13896. };
  13897. MP4Demuxer.probe = function probe(data) {
  13898. return hasMoofData(data);
  13899. };
  13900. _proto.demux = function demux(data, timeOffset) {
  13901. this.timeOffset = timeOffset;
  13902. // 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
  13903. var videoSamples = data;
  13904. var videoTrack = this.videoTrack;
  13905. var textTrack = this.txtTrack;
  13906. if (this.config.progressive) {
  13907. // Split the bytestream into two ranges: one encompassing all data up until the start of the last moof, and everything else.
  13908. // This is done to guarantee that we're sending valid data to MSE - when demuxing progressively, we have no guarantee
  13909. // that the fetch loader gives us flush moof+mdat pairs. If we push jagged data to MSE, it will throw an exception.
  13910. if (this.remainderData) {
  13911. videoSamples = appendUint8Array(this.remainderData, data);
  13912. }
  13913. var segmentedData = segmentValidRange(videoSamples);
  13914. this.remainderData = segmentedData.remainder;
  13915. videoTrack.samples = segmentedData.valid || new Uint8Array();
  13916. } else {
  13917. videoTrack.samples = videoSamples;
  13918. }
  13919. var id3Track = this.extractID3Track(videoTrack, timeOffset);
  13920. textTrack.samples = parseSamples(timeOffset, videoTrack);
  13921. return {
  13922. videoTrack: videoTrack,
  13923. audioTrack: this.audioTrack,
  13924. id3Track: id3Track,
  13925. textTrack: this.txtTrack
  13926. };
  13927. };
  13928. _proto.flush = function flush() {
  13929. var timeOffset = this.timeOffset;
  13930. var videoTrack = this.videoTrack;
  13931. var textTrack = this.txtTrack;
  13932. videoTrack.samples = this.remainderData || new Uint8Array();
  13933. this.remainderData = null;
  13934. var id3Track = this.extractID3Track(videoTrack, this.timeOffset);
  13935. textTrack.samples = parseSamples(timeOffset, videoTrack);
  13936. return {
  13937. videoTrack: videoTrack,
  13938. audioTrack: dummyTrack(),
  13939. id3Track: id3Track,
  13940. textTrack: dummyTrack()
  13941. };
  13942. };
  13943. _proto.extractID3Track = function extractID3Track(videoTrack, timeOffset) {
  13944. var id3Track = this.id3Track;
  13945. if (videoTrack.samples.length) {
  13946. var emsgs = findBox(videoTrack.samples, ['emsg']);
  13947. if (emsgs) {
  13948. emsgs.forEach(function (data) {
  13949. var emsgInfo = parseEmsg(data);
  13950. if (emsgSchemePattern.test(emsgInfo.schemeIdUri)) {
  13951. var pts = isFiniteNumber(emsgInfo.presentationTime) ? emsgInfo.presentationTime / emsgInfo.timeScale : timeOffset + emsgInfo.presentationTimeDelta / emsgInfo.timeScale;
  13952. var duration = emsgInfo.eventDuration === 0xffffffff ? Number.POSITIVE_INFINITY : emsgInfo.eventDuration / emsgInfo.timeScale;
  13953. // Safari takes anything <= 0.001 seconds and maps it to Infinity
  13954. if (duration <= 0.001) {
  13955. duration = Number.POSITIVE_INFINITY;
  13956. }
  13957. var payload = emsgInfo.payload;
  13958. id3Track.samples.push({
  13959. data: payload,
  13960. len: payload.byteLength,
  13961. dts: pts,
  13962. pts: pts,
  13963. type: MetadataSchema.emsg,
  13964. duration: duration
  13965. });
  13966. }
  13967. });
  13968. }
  13969. }
  13970. return id3Track;
  13971. };
  13972. _proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
  13973. return Promise.reject(new Error('The MP4 demuxer does not support SAMPLE-AES decryption'));
  13974. };
  13975. _proto.destroy = function destroy() {};
  13976. return MP4Demuxer;
  13977. }();
  13978. var getAudioBSID = function getAudioBSID(data, offset) {
  13979. // check the bsid to confirm ac-3 | ec-3
  13980. var bsid = 0;
  13981. var numBits = 5;
  13982. offset += numBits;
  13983. var temp = new Uint32Array(1); // unsigned 32 bit for temporary storage
  13984. var mask = new Uint32Array(1); // unsigned 32 bit mask value
  13985. var _byte = new Uint8Array(1); // unsigned 8 bit for temporary storage
  13986. while (numBits > 0) {
  13987. _byte[0] = data[offset];
  13988. // read remaining bits, upto 8 bits at a time
  13989. var bits = Math.min(numBits, 8);
  13990. var shift = 8 - bits;
  13991. mask[0] = 0xff000000 >>> 24 + shift << shift;
  13992. temp[0] = (_byte[0] & mask[0]) >> shift;
  13993. bsid = !bsid ? temp[0] : bsid << bits | temp[0];
  13994. offset += 1;
  13995. numBits -= bits;
  13996. }
  13997. return bsid;
  13998. };
  13999. var BaseVideoParser = /*#__PURE__*/function () {
  14000. function BaseVideoParser() {
  14001. this.VideoSample = null;
  14002. }
  14003. var _proto = BaseVideoParser.prototype;
  14004. _proto.createVideoSample = function createVideoSample(key, pts, dts, debug) {
  14005. return {
  14006. key: key,
  14007. frame: false,
  14008. pts: pts,
  14009. dts: dts,
  14010. units: [],
  14011. debug: debug,
  14012. length: 0
  14013. };
  14014. };
  14015. _proto.getLastNalUnit = function getLastNalUnit(samples) {
  14016. var _VideoSample;
  14017. var VideoSample = this.VideoSample;
  14018. var lastUnit;
  14019. // try to fallback to previous sample if current one is empty
  14020. if (!VideoSample || VideoSample.units.length === 0) {
  14021. VideoSample = samples[samples.length - 1];
  14022. }
  14023. if ((_VideoSample = VideoSample) != null && _VideoSample.units) {
  14024. var units = VideoSample.units;
  14025. lastUnit = units[units.length - 1];
  14026. }
  14027. return lastUnit;
  14028. };
  14029. _proto.pushAccessUnit = function pushAccessUnit(VideoSample, videoTrack) {
  14030. if (VideoSample.units.length && VideoSample.frame) {
  14031. // if sample does not have PTS/DTS, patch with last sample PTS/DTS
  14032. if (VideoSample.pts === undefined) {
  14033. var samples = videoTrack.samples;
  14034. var nbSamples = samples.length;
  14035. if (nbSamples) {
  14036. var lastSample = samples[nbSamples - 1];
  14037. VideoSample.pts = lastSample.pts;
  14038. VideoSample.dts = lastSample.dts;
  14039. } else {
  14040. // dropping samples, no timestamp found
  14041. videoTrack.dropped++;
  14042. return;
  14043. }
  14044. }
  14045. videoTrack.samples.push(VideoSample);
  14046. }
  14047. if (VideoSample.debug.length) {
  14048. logger.log(VideoSample.pts + '/' + VideoSample.dts + ':' + VideoSample.debug);
  14049. }
  14050. };
  14051. return BaseVideoParser;
  14052. }();
  14053. /**
  14054. * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
  14055. */
  14056. var ExpGolomb = /*#__PURE__*/function () {
  14057. function ExpGolomb(data) {
  14058. this.data = void 0;
  14059. this.bytesAvailable = void 0;
  14060. this.word = void 0;
  14061. this.bitsAvailable = void 0;
  14062. this.data = data;
  14063. // the number of bytes left to examine in this.data
  14064. this.bytesAvailable = data.byteLength;
  14065. // the current word being examined
  14066. this.word = 0; // :uint
  14067. // the number of bits left to examine in the current word
  14068. this.bitsAvailable = 0; // :uint
  14069. }
  14070. // ():void
  14071. var _proto = ExpGolomb.prototype;
  14072. _proto.loadWord = function loadWord() {
  14073. var data = this.data;
  14074. var bytesAvailable = this.bytesAvailable;
  14075. var position = data.byteLength - bytesAvailable;
  14076. var workingBytes = new Uint8Array(4);
  14077. var availableBytes = Math.min(4, bytesAvailable);
  14078. if (availableBytes === 0) {
  14079. throw new Error('no bytes available');
  14080. }
  14081. workingBytes.set(data.subarray(position, position + availableBytes));
  14082. this.word = new DataView(workingBytes.buffer).getUint32(0);
  14083. // track the amount of this.data that has been processed
  14084. this.bitsAvailable = availableBytes * 8;
  14085. this.bytesAvailable -= availableBytes;
  14086. }
  14087. // (count:int):void
  14088. ;
  14089. _proto.skipBits = function skipBits(count) {
  14090. var skipBytes; // :int
  14091. count = Math.min(count, this.bytesAvailable * 8 + this.bitsAvailable);
  14092. if (this.bitsAvailable > count) {
  14093. this.word <<= count;
  14094. this.bitsAvailable -= count;
  14095. } else {
  14096. count -= this.bitsAvailable;
  14097. skipBytes = count >> 3;
  14098. count -= skipBytes << 3;
  14099. this.bytesAvailable -= skipBytes;
  14100. this.loadWord();
  14101. this.word <<= count;
  14102. this.bitsAvailable -= count;
  14103. }
  14104. }
  14105. // (size:int):uint
  14106. ;
  14107. _proto.readBits = function readBits(size) {
  14108. var bits = Math.min(this.bitsAvailable, size); // :uint
  14109. var valu = this.word >>> 32 - bits; // :uint
  14110. if (size > 32) {
  14111. logger.error('Cannot read more than 32 bits at a time');
  14112. }
  14113. this.bitsAvailable -= bits;
  14114. if (this.bitsAvailable > 0) {
  14115. this.word <<= bits;
  14116. } else if (this.bytesAvailable > 0) {
  14117. this.loadWord();
  14118. } else {
  14119. throw new Error('no bits available');
  14120. }
  14121. bits = size - bits;
  14122. if (bits > 0 && this.bitsAvailable) {
  14123. return valu << bits | this.readBits(bits);
  14124. } else {
  14125. return valu;
  14126. }
  14127. }
  14128. // ():uint
  14129. ;
  14130. _proto.skipLZ = function skipLZ() {
  14131. var leadingZeroCount; // :uint
  14132. for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
  14133. if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) {
  14134. // the first bit of working word is 1
  14135. this.word <<= leadingZeroCount;
  14136. this.bitsAvailable -= leadingZeroCount;
  14137. return leadingZeroCount;
  14138. }
  14139. }
  14140. // we exhausted word and still have not found a 1
  14141. this.loadWord();
  14142. return leadingZeroCount + this.skipLZ();
  14143. }
  14144. // ():void
  14145. ;
  14146. _proto.skipUEG = function skipUEG() {
  14147. this.skipBits(1 + this.skipLZ());
  14148. }
  14149. // ():void
  14150. ;
  14151. _proto.skipEG = function skipEG() {
  14152. this.skipBits(1 + this.skipLZ());
  14153. }
  14154. // ():uint
  14155. ;
  14156. _proto.readUEG = function readUEG() {
  14157. var clz = this.skipLZ(); // :uint
  14158. return this.readBits(clz + 1) - 1;
  14159. }
  14160. // ():int
  14161. ;
  14162. _proto.readEG = function readEG() {
  14163. var valu = this.readUEG(); // :int
  14164. if (0x01 & valu) {
  14165. // the number is odd if the low order bit is set
  14166. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  14167. } else {
  14168. return -1 * (valu >>> 1); // divide by two then make it negative
  14169. }
  14170. }
  14171. // Some convenience functions
  14172. // :Boolean
  14173. ;
  14174. _proto.readBoolean = function readBoolean() {
  14175. return this.readBits(1) === 1;
  14176. }
  14177. // ():int
  14178. ;
  14179. _proto.readUByte = function readUByte() {
  14180. return this.readBits(8);
  14181. }
  14182. // ():int
  14183. ;
  14184. _proto.readUShort = function readUShort() {
  14185. return this.readBits(16);
  14186. }
  14187. // ():int
  14188. ;
  14189. _proto.readUInt = function readUInt() {
  14190. return this.readBits(32);
  14191. }
  14192. /**
  14193. * Advance the ExpGolomb decoder past a scaling list. The scaling
  14194. * list is optionally transmitted as part of a sequence parameter
  14195. * set and is not relevant to transmuxing.
  14196. * @param count the number of entries in this scaling list
  14197. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  14198. */;
  14199. _proto.skipScalingList = function skipScalingList(count) {
  14200. var lastScale = 8;
  14201. var nextScale = 8;
  14202. var deltaScale;
  14203. for (var j = 0; j < count; j++) {
  14204. if (nextScale !== 0) {
  14205. deltaScale = this.readEG();
  14206. nextScale = (lastScale + deltaScale + 256) % 256;
  14207. }
  14208. lastScale = nextScale === 0 ? lastScale : nextScale;
  14209. }
  14210. }
  14211. /**
  14212. * Read a sequence parameter set and return some interesting video
  14213. * properties. A sequence parameter set is the H264 metadata that
  14214. * describes the properties of upcoming video frames.
  14215. * @returns an object with configuration parsed from the
  14216. * sequence parameter set, including the dimensions of the
  14217. * associated video frames.
  14218. */;
  14219. _proto.readSPS = function readSPS() {
  14220. var frameCropLeftOffset = 0;
  14221. var frameCropRightOffset = 0;
  14222. var frameCropTopOffset = 0;
  14223. var frameCropBottomOffset = 0;
  14224. var numRefFramesInPicOrderCntCycle;
  14225. var scalingListCount;
  14226. var i;
  14227. var readUByte = this.readUByte.bind(this);
  14228. var readBits = this.readBits.bind(this);
  14229. var readUEG = this.readUEG.bind(this);
  14230. var readBoolean = this.readBoolean.bind(this);
  14231. var skipBits = this.skipBits.bind(this);
  14232. var skipEG = this.skipEG.bind(this);
  14233. var skipUEG = this.skipUEG.bind(this);
  14234. var skipScalingList = this.skipScalingList.bind(this);
  14235. readUByte();
  14236. var profileIdc = readUByte(); // profile_idc
  14237. readBits(5); // profileCompat constraint_set[0-4]_flag, u(5)
  14238. skipBits(3); // reserved_zero_3bits u(3),
  14239. readUByte(); // level_idc u(8)
  14240. skipUEG(); // seq_parameter_set_id
  14241. // some profiles have more optional data we don't need
  14242. if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
  14243. var chromaFormatIdc = readUEG();
  14244. if (chromaFormatIdc === 3) {
  14245. skipBits(1);
  14246. } // separate_colour_plane_flag
  14247. skipUEG(); // bit_depth_luma_minus8
  14248. skipUEG(); // bit_depth_chroma_minus8
  14249. skipBits(1); // qpprime_y_zero_transform_bypass_flag
  14250. if (readBoolean()) {
  14251. // seq_scaling_matrix_present_flag
  14252. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  14253. for (i = 0; i < scalingListCount; i++) {
  14254. if (readBoolean()) {
  14255. // seq_scaling_list_present_flag[ i ]
  14256. if (i < 6) {
  14257. skipScalingList(16);
  14258. } else {
  14259. skipScalingList(64);
  14260. }
  14261. }
  14262. }
  14263. }
  14264. }
  14265. skipUEG(); // log2_max_frame_num_minus4
  14266. var picOrderCntType = readUEG();
  14267. if (picOrderCntType === 0) {
  14268. readUEG(); // log2_max_pic_order_cnt_lsb_minus4
  14269. } else if (picOrderCntType === 1) {
  14270. skipBits(1); // delta_pic_order_always_zero_flag
  14271. skipEG(); // offset_for_non_ref_pic
  14272. skipEG(); // offset_for_top_to_bottom_field
  14273. numRefFramesInPicOrderCntCycle = readUEG();
  14274. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  14275. skipEG();
  14276. } // offset_for_ref_frame[ i ]
  14277. }
  14278. skipUEG(); // max_num_ref_frames
  14279. skipBits(1); // gaps_in_frame_num_value_allowed_flag
  14280. var picWidthInMbsMinus1 = readUEG();
  14281. var picHeightInMapUnitsMinus1 = readUEG();
  14282. var frameMbsOnlyFlag = readBits(1);
  14283. if (frameMbsOnlyFlag === 0) {
  14284. skipBits(1);
  14285. } // mb_adaptive_frame_field_flag
  14286. skipBits(1); // direct_8x8_inference_flag
  14287. if (readBoolean()) {
  14288. // frame_cropping_flag
  14289. frameCropLeftOffset = readUEG();
  14290. frameCropRightOffset = readUEG();
  14291. frameCropTopOffset = readUEG();
  14292. frameCropBottomOffset = readUEG();
  14293. }
  14294. var pixelRatio = [1, 1];
  14295. if (readBoolean()) {
  14296. // vui_parameters_present_flag
  14297. if (readBoolean()) {
  14298. // aspect_ratio_info_present_flag
  14299. var aspectRatioIdc = readUByte();
  14300. switch (aspectRatioIdc) {
  14301. case 1:
  14302. pixelRatio = [1, 1];
  14303. break;
  14304. case 2:
  14305. pixelRatio = [12, 11];
  14306. break;
  14307. case 3:
  14308. pixelRatio = [10, 11];
  14309. break;
  14310. case 4:
  14311. pixelRatio = [16, 11];
  14312. break;
  14313. case 5:
  14314. pixelRatio = [40, 33];
  14315. break;
  14316. case 6:
  14317. pixelRatio = [24, 11];
  14318. break;
  14319. case 7:
  14320. pixelRatio = [20, 11];
  14321. break;
  14322. case 8:
  14323. pixelRatio = [32, 11];
  14324. break;
  14325. case 9:
  14326. pixelRatio = [80, 33];
  14327. break;
  14328. case 10:
  14329. pixelRatio = [18, 11];
  14330. break;
  14331. case 11:
  14332. pixelRatio = [15, 11];
  14333. break;
  14334. case 12:
  14335. pixelRatio = [64, 33];
  14336. break;
  14337. case 13:
  14338. pixelRatio = [160, 99];
  14339. break;
  14340. case 14:
  14341. pixelRatio = [4, 3];
  14342. break;
  14343. case 15:
  14344. pixelRatio = [3, 2];
  14345. break;
  14346. case 16:
  14347. pixelRatio = [2, 1];
  14348. break;
  14349. case 255:
  14350. {
  14351. pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
  14352. break;
  14353. }
  14354. }
  14355. }
  14356. }
  14357. return {
  14358. width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
  14359. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
  14360. pixelRatio: pixelRatio
  14361. };
  14362. };
  14363. _proto.readSliceType = function readSliceType() {
  14364. // skip NALu type
  14365. this.readUByte();
  14366. // discard first_mb_in_slice
  14367. this.readUEG();
  14368. // return slice_type
  14369. return this.readUEG();
  14370. };
  14371. return ExpGolomb;
  14372. }();
  14373. var AvcVideoParser = /*#__PURE__*/function (_BaseVideoParser) {
  14374. _inheritsLoose(AvcVideoParser, _BaseVideoParser);
  14375. function AvcVideoParser() {
  14376. return _BaseVideoParser.apply(this, arguments) || this;
  14377. }
  14378. var _proto = AvcVideoParser.prototype;
  14379. _proto.parseAVCPES = function parseAVCPES(track, textTrack, pes, last, duration) {
  14380. var _this = this;
  14381. var units = this.parseAVCNALu(track, pes.data);
  14382. var VideoSample = this.VideoSample;
  14383. var push;
  14384. var spsfound = false;
  14385. // free pes.data to save up some memory
  14386. pes.data = null;
  14387. // if new NAL units found and last sample still there, let's push ...
  14388. // this helps parsing streams with missing AUD (only do this if AUD never found)
  14389. if (VideoSample && units.length && !track.audFound) {
  14390. this.pushAccessUnit(VideoSample, track);
  14391. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts, '');
  14392. }
  14393. units.forEach(function (unit) {
  14394. var _VideoSample2;
  14395. switch (unit.type) {
  14396. // NDR
  14397. case 1:
  14398. {
  14399. var iskey = false;
  14400. push = true;
  14401. var data = unit.data;
  14402. // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)
  14403. if (spsfound && data.length > 4) {
  14404. // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR
  14405. var sliceType = new ExpGolomb(data).readSliceType();
  14406. // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice
  14407. // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.
  14408. // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.
  14409. // I slice: A slice that is not an SI slice that is decoded using intra prediction only.
  14410. // if (sliceType === 2 || sliceType === 7) {
  14411. if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
  14412. iskey = true;
  14413. }
  14414. }
  14415. if (iskey) {
  14416. var _VideoSample;
  14417. // if we have non-keyframe data already, that cannot belong to the same frame as a keyframe, so force a push
  14418. if ((_VideoSample = VideoSample) != null && _VideoSample.frame && !VideoSample.key) {
  14419. _this.pushAccessUnit(VideoSample, track);
  14420. VideoSample = _this.VideoSample = null;
  14421. }
  14422. }
  14423. if (!VideoSample) {
  14424. VideoSample = _this.VideoSample = _this.createVideoSample(true, pes.pts, pes.dts, '');
  14425. }
  14426. VideoSample.frame = true;
  14427. VideoSample.key = iskey;
  14428. break;
  14429. // IDR
  14430. }
  14431. case 5:
  14432. push = true;
  14433. // handle PES not starting with AUD
  14434. // if we have frame data already, that cannot belong to the same frame, so force a push
  14435. if ((_VideoSample2 = VideoSample) != null && _VideoSample2.frame && !VideoSample.key) {
  14436. _this.pushAccessUnit(VideoSample, track);
  14437. VideoSample = _this.VideoSample = null;
  14438. }
  14439. if (!VideoSample) {
  14440. VideoSample = _this.VideoSample = _this.createVideoSample(true, pes.pts, pes.dts, '');
  14441. }
  14442. VideoSample.key = true;
  14443. VideoSample.frame = true;
  14444. break;
  14445. // SEI
  14446. case 6:
  14447. {
  14448. push = true;
  14449. parseSEIMessageFromNALu(unit.data, 1, pes.pts, textTrack.samples);
  14450. break;
  14451. // SPS
  14452. }
  14453. case 7:
  14454. {
  14455. var _track$pixelRatio, _track$pixelRatio2;
  14456. push = true;
  14457. spsfound = true;
  14458. var sps = unit.data;
  14459. var expGolombDecoder = new ExpGolomb(sps);
  14460. var config = expGolombDecoder.readSPS();
  14461. 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]) {
  14462. track.width = config.width;
  14463. track.height = config.height;
  14464. track.pixelRatio = config.pixelRatio;
  14465. track.sps = [sps];
  14466. track.duration = duration;
  14467. var codecarray = sps.subarray(1, 4);
  14468. var codecstring = 'avc1.';
  14469. for (var i = 0; i < 3; i++) {
  14470. var h = codecarray[i].toString(16);
  14471. if (h.length < 2) {
  14472. h = '0' + h;
  14473. }
  14474. codecstring += h;
  14475. }
  14476. track.codec = codecstring;
  14477. }
  14478. break;
  14479. }
  14480. // PPS
  14481. case 8:
  14482. push = true;
  14483. track.pps = [unit.data];
  14484. break;
  14485. // AUD
  14486. case 9:
  14487. push = true;
  14488. track.audFound = true;
  14489. if (VideoSample) {
  14490. _this.pushAccessUnit(VideoSample, track);
  14491. }
  14492. VideoSample = _this.VideoSample = _this.createVideoSample(false, pes.pts, pes.dts, '');
  14493. break;
  14494. // Filler Data
  14495. case 12:
  14496. push = true;
  14497. break;
  14498. default:
  14499. push = false;
  14500. if (VideoSample) {
  14501. VideoSample.debug += 'unknown NAL ' + unit.type + ' ';
  14502. }
  14503. break;
  14504. }
  14505. if (VideoSample && push) {
  14506. var _units = VideoSample.units;
  14507. _units.push(unit);
  14508. }
  14509. });
  14510. // if last PES packet, push samples
  14511. if (last && VideoSample) {
  14512. this.pushAccessUnit(VideoSample, track);
  14513. this.VideoSample = null;
  14514. }
  14515. };
  14516. _proto.parseAVCNALu = function parseAVCNALu(track, array) {
  14517. var len = array.byteLength;
  14518. var state = track.naluState || 0;
  14519. var lastState = state;
  14520. var units = [];
  14521. var i = 0;
  14522. var value;
  14523. var overflow;
  14524. var unitType;
  14525. var lastUnitStart = -1;
  14526. var lastUnitType = 0;
  14527. // logger.log('PES:' + Hex.hexDump(array));
  14528. if (state === -1) {
  14529. // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet
  14530. lastUnitStart = 0;
  14531. // NALu type is value read from offset 0
  14532. lastUnitType = array[0] & 0x1f;
  14533. state = 0;
  14534. i = 1;
  14535. }
  14536. while (i < len) {
  14537. value = array[i++];
  14538. // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case
  14539. if (!state) {
  14540. state = value ? 0 : 1;
  14541. continue;
  14542. }
  14543. if (state === 1) {
  14544. state = value ? 0 : 2;
  14545. continue;
  14546. }
  14547. // here we have state either equal to 2 or 3
  14548. if (!value) {
  14549. state = 3;
  14550. } else if (value === 1) {
  14551. overflow = i - state - 1;
  14552. if (lastUnitStart >= 0) {
  14553. var unit = {
  14554. data: array.subarray(lastUnitStart, overflow),
  14555. type: lastUnitType
  14556. };
  14557. // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
  14558. units.push(unit);
  14559. } else {
  14560. // lastUnitStart is undefined => this is the first start code found in this PES packet
  14561. // first check if start code delimiter is overlapping between 2 PES packets,
  14562. // ie it started in last packet (lastState not zero)
  14563. // and ended at the beginning of this PES packet (i <= 4 - lastState)
  14564. var lastUnit = this.getLastNalUnit(track.samples);
  14565. if (lastUnit) {
  14566. if (lastState && i <= 4 - lastState) {
  14567. // start delimiter overlapping between PES packets
  14568. // strip start delimiter bytes from the end of last NAL unit
  14569. // check if lastUnit had a state different from zero
  14570. if (lastUnit.state) {
  14571. // strip last bytes
  14572. lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
  14573. }
  14574. }
  14575. // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.
  14576. if (overflow > 0) {
  14577. // logger.log('first NALU found with overflow:' + overflow);
  14578. lastUnit.data = appendUint8Array(lastUnit.data, array.subarray(0, overflow));
  14579. lastUnit.state = 0;
  14580. }
  14581. }
  14582. }
  14583. // check if we can read unit type
  14584. if (i < len) {
  14585. unitType = array[i] & 0x1f;
  14586. // logger.log('find NALU @ offset:' + i + ',type:' + unitType);
  14587. lastUnitStart = i;
  14588. lastUnitType = unitType;
  14589. state = 0;
  14590. } else {
  14591. // not enough byte to read unit type. let's read it on next PES parsing
  14592. state = -1;
  14593. }
  14594. } else {
  14595. state = 0;
  14596. }
  14597. }
  14598. if (lastUnitStart >= 0 && state >= 0) {
  14599. var _unit = {
  14600. data: array.subarray(lastUnitStart, len),
  14601. type: lastUnitType,
  14602. state: state
  14603. };
  14604. units.push(_unit);
  14605. // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);
  14606. }
  14607. // no NALu found
  14608. if (units.length === 0) {
  14609. // append pes.data to previous NAL unit
  14610. var _lastUnit = this.getLastNalUnit(track.samples);
  14611. if (_lastUnit) {
  14612. _lastUnit.data = appendUint8Array(_lastUnit.data, array);
  14613. }
  14614. }
  14615. track.naluState = state;
  14616. return units;
  14617. };
  14618. return AvcVideoParser;
  14619. }(BaseVideoParser);
  14620. /**
  14621. * SAMPLE-AES decrypter
  14622. */
  14623. var SampleAesDecrypter = /*#__PURE__*/function () {
  14624. function SampleAesDecrypter(observer, config, keyData) {
  14625. this.keyData = void 0;
  14626. this.decrypter = void 0;
  14627. this.keyData = keyData;
  14628. this.decrypter = new Decrypter(config, {
  14629. removePKCS7Padding: false
  14630. });
  14631. }
  14632. var _proto = SampleAesDecrypter.prototype;
  14633. _proto.decryptBuffer = function decryptBuffer(encryptedData) {
  14634. return this.decrypter.decrypt(encryptedData, this.keyData.key.buffer, this.keyData.iv.buffer);
  14635. }
  14636. // AAC - encrypt all full 16 bytes blocks starting from offset 16
  14637. ;
  14638. _proto.decryptAacSample = function decryptAacSample(samples, sampleIndex, callback) {
  14639. var _this = this;
  14640. var curUnit = samples[sampleIndex].unit;
  14641. if (curUnit.length <= 16) {
  14642. // No encrypted portion in this sample (first 16 bytes is not
  14643. // encrypted, see https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/HLS_Sample_Encryption/Encryption/Encryption.html),
  14644. return;
  14645. }
  14646. var encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
  14647. var encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
  14648. this.decryptBuffer(encryptedBuffer).then(function (decryptedBuffer) {
  14649. var decryptedData = new Uint8Array(decryptedBuffer);
  14650. curUnit.set(decryptedData, 16);
  14651. if (!_this.decrypter.isSync()) {
  14652. _this.decryptAacSamples(samples, sampleIndex + 1, callback);
  14653. }
  14654. });
  14655. };
  14656. _proto.decryptAacSamples = function decryptAacSamples(samples, sampleIndex, callback) {
  14657. for (;; sampleIndex++) {
  14658. if (sampleIndex >= samples.length) {
  14659. callback();
  14660. return;
  14661. }
  14662. if (samples[sampleIndex].unit.length < 32) {
  14663. continue;
  14664. }
  14665. this.decryptAacSample(samples, sampleIndex, callback);
  14666. if (!this.decrypter.isSync()) {
  14667. return;
  14668. }
  14669. }
  14670. }
  14671. // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
  14672. ;
  14673. _proto.getAvcEncryptedData = function getAvcEncryptedData(decodedData) {
  14674. var encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
  14675. var encryptedData = new Int8Array(encryptedDataLen);
  14676. var outputPos = 0;
  14677. for (var inputPos = 32; inputPos < decodedData.length - 16; inputPos += 160, outputPos += 16) {
  14678. encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
  14679. }
  14680. return encryptedData;
  14681. };
  14682. _proto.getAvcDecryptedUnit = function getAvcDecryptedUnit(decodedData, decryptedData) {
  14683. var uint8DecryptedData = new Uint8Array(decryptedData);
  14684. var inputPos = 0;
  14685. for (var outputPos = 32; outputPos < decodedData.length - 16; outputPos += 160, inputPos += 16) {
  14686. decodedData.set(uint8DecryptedData.subarray(inputPos, inputPos + 16), outputPos);
  14687. }
  14688. return decodedData;
  14689. };
  14690. _proto.decryptAvcSample = function decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit) {
  14691. var _this2 = this;
  14692. var decodedData = discardEPB(curUnit.data);
  14693. var encryptedData = this.getAvcEncryptedData(decodedData);
  14694. this.decryptBuffer(encryptedData.buffer).then(function (decryptedBuffer) {
  14695. curUnit.data = _this2.getAvcDecryptedUnit(decodedData, decryptedBuffer);
  14696. if (!_this2.decrypter.isSync()) {
  14697. _this2.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
  14698. }
  14699. });
  14700. };
  14701. _proto.decryptAvcSamples = function decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
  14702. if (samples instanceof Uint8Array) {
  14703. throw new Error('Cannot decrypt samples of type Uint8Array');
  14704. }
  14705. for (;; sampleIndex++, unitIndex = 0) {
  14706. if (sampleIndex >= samples.length) {
  14707. callback();
  14708. return;
  14709. }
  14710. var curUnits = samples[sampleIndex].units;
  14711. for (;; unitIndex++) {
  14712. if (unitIndex >= curUnits.length) {
  14713. break;
  14714. }
  14715. var curUnit = curUnits[unitIndex];
  14716. if (curUnit.data.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
  14717. continue;
  14718. }
  14719. this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit);
  14720. if (!this.decrypter.isSync()) {
  14721. return;
  14722. }
  14723. }
  14724. }
  14725. };
  14726. return SampleAesDecrypter;
  14727. }();
  14728. var PACKET_LENGTH = 188;
  14729. var TSDemuxer = /*#__PURE__*/function () {
  14730. function TSDemuxer(observer, config, typeSupported) {
  14731. this.observer = void 0;
  14732. this.config = void 0;
  14733. this.typeSupported = void 0;
  14734. this.sampleAes = null;
  14735. this.pmtParsed = false;
  14736. this.audioCodec = void 0;
  14737. this.videoCodec = void 0;
  14738. this._duration = 0;
  14739. this._pmtId = -1;
  14740. this._videoTrack = void 0;
  14741. this._audioTrack = void 0;
  14742. this._id3Track = void 0;
  14743. this._txtTrack = void 0;
  14744. this.aacOverFlow = null;
  14745. this.remainderData = null;
  14746. this.videoParser = void 0;
  14747. this.observer = observer;
  14748. this.config = config;
  14749. this.typeSupported = typeSupported;
  14750. this.videoParser = new AvcVideoParser();
  14751. }
  14752. TSDemuxer.probe = function probe(data) {
  14753. var syncOffset = TSDemuxer.syncOffset(data);
  14754. if (syncOffset > 0) {
  14755. logger.warn("MPEG2-TS detected but first sync word found @ offset " + syncOffset);
  14756. }
  14757. return syncOffset !== -1;
  14758. };
  14759. TSDemuxer.syncOffset = function syncOffset(data) {
  14760. var length = data.length;
  14761. var scanwindow = Math.min(PACKET_LENGTH * 5, length - PACKET_LENGTH) + 1;
  14762. var i = 0;
  14763. while (i < scanwindow) {
  14764. // a TS init segment should contain at least 2 TS packets: PAT and PMT, each starting with 0x47
  14765. var foundPat = false;
  14766. var packetStart = -1;
  14767. var tsPackets = 0;
  14768. for (var j = i; j < length; j += PACKET_LENGTH) {
  14769. if (data[j] === 0x47 && (length - j === PACKET_LENGTH || data[j + PACKET_LENGTH] === 0x47)) {
  14770. tsPackets++;
  14771. if (packetStart === -1) {
  14772. packetStart = j;
  14773. // First sync word found at offset, increase scan length (#5251)
  14774. if (packetStart !== 0) {
  14775. scanwindow = Math.min(packetStart + PACKET_LENGTH * 99, data.length - PACKET_LENGTH) + 1;
  14776. }
  14777. }
  14778. if (!foundPat) {
  14779. foundPat = parsePID(data, j) === 0;
  14780. }
  14781. // Sync word found at 0 with 3 packets, or found at offset least 2 packets up to scanwindow (#5501)
  14782. if (foundPat && tsPackets > 1 && (packetStart === 0 && tsPackets > 2 || j + PACKET_LENGTH > scanwindow)) {
  14783. return packetStart;
  14784. }
  14785. } else if (tsPackets) {
  14786. // Exit if sync word found, but does not contain contiguous packets
  14787. return -1;
  14788. } else {
  14789. break;
  14790. }
  14791. }
  14792. i++;
  14793. }
  14794. return -1;
  14795. }
  14796. /**
  14797. * Creates a track model internal to demuxer used to drive remuxing input
  14798. */;
  14799. TSDemuxer.createTrack = function createTrack(type, duration) {
  14800. return {
  14801. container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,
  14802. type: type,
  14803. id: RemuxerTrackIdConfig[type],
  14804. pid: -1,
  14805. inputTimeScale: 90000,
  14806. sequenceNumber: 0,
  14807. samples: [],
  14808. dropped: 0,
  14809. duration: type === 'audio' ? duration : undefined
  14810. };
  14811. }
  14812. /**
  14813. * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
  14814. * Resets all internal track instances of the demuxer.
  14815. */;
  14816. var _proto = TSDemuxer.prototype;
  14817. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  14818. this.pmtParsed = false;
  14819. this._pmtId = -1;
  14820. this._videoTrack = TSDemuxer.createTrack('video');
  14821. this._audioTrack = TSDemuxer.createTrack('audio', trackDuration);
  14822. this._id3Track = TSDemuxer.createTrack('id3');
  14823. this._txtTrack = TSDemuxer.createTrack('text');
  14824. this._audioTrack.segmentCodec = 'aac';
  14825. // flush any partial content
  14826. this.aacOverFlow = null;
  14827. this.remainderData = null;
  14828. this.audioCodec = audioCodec;
  14829. this.videoCodec = videoCodec;
  14830. this._duration = trackDuration;
  14831. };
  14832. _proto.resetTimeStamp = function resetTimeStamp() {};
  14833. _proto.resetContiguity = function resetContiguity() {
  14834. var _audioTrack = this._audioTrack,
  14835. _videoTrack = this._videoTrack,
  14836. _id3Track = this._id3Track;
  14837. if (_audioTrack) {
  14838. _audioTrack.pesData = null;
  14839. }
  14840. if (_videoTrack) {
  14841. _videoTrack.pesData = null;
  14842. }
  14843. if (_id3Track) {
  14844. _id3Track.pesData = null;
  14845. }
  14846. this.aacOverFlow = null;
  14847. this.remainderData = null;
  14848. };
  14849. _proto.demux = function demux(data, timeOffset, isSampleAes, flush) {
  14850. if (isSampleAes === void 0) {
  14851. isSampleAes = false;
  14852. }
  14853. if (flush === void 0) {
  14854. flush = false;
  14855. }
  14856. if (!isSampleAes) {
  14857. this.sampleAes = null;
  14858. }
  14859. var pes;
  14860. var videoTrack = this._videoTrack;
  14861. var audioTrack = this._audioTrack;
  14862. var id3Track = this._id3Track;
  14863. var textTrack = this._txtTrack;
  14864. var videoPid = videoTrack.pid;
  14865. var videoData = videoTrack.pesData;
  14866. var audioPid = audioTrack.pid;
  14867. var id3Pid = id3Track.pid;
  14868. var audioData = audioTrack.pesData;
  14869. var id3Data = id3Track.pesData;
  14870. var unknownPID = null;
  14871. var pmtParsed = this.pmtParsed;
  14872. var pmtId = this._pmtId;
  14873. var len = data.length;
  14874. if (this.remainderData) {
  14875. data = appendUint8Array(this.remainderData, data);
  14876. len = data.length;
  14877. this.remainderData = null;
  14878. }
  14879. if (len < PACKET_LENGTH && !flush) {
  14880. this.remainderData = data;
  14881. return {
  14882. audioTrack: audioTrack,
  14883. videoTrack: videoTrack,
  14884. id3Track: id3Track,
  14885. textTrack: textTrack
  14886. };
  14887. }
  14888. var syncOffset = Math.max(0, TSDemuxer.syncOffset(data));
  14889. len -= (len - syncOffset) % PACKET_LENGTH;
  14890. if (len < data.byteLength && !flush) {
  14891. this.remainderData = new Uint8Array(data.buffer, len, data.buffer.byteLength - len);
  14892. }
  14893. // loop through TS packets
  14894. var tsPacketErrors = 0;
  14895. for (var start = syncOffset; start < len; start += PACKET_LENGTH) {
  14896. if (data[start] === 0x47) {
  14897. var stt = !!(data[start + 1] & 0x40);
  14898. var pid = parsePID(data, start);
  14899. var atf = (data[start + 3] & 0x30) >> 4;
  14900. // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.
  14901. var offset = void 0;
  14902. if (atf > 1) {
  14903. offset = start + 5 + data[start + 4];
  14904. // continue if there is only adaptation field
  14905. if (offset === start + PACKET_LENGTH) {
  14906. continue;
  14907. }
  14908. } else {
  14909. offset = start + 4;
  14910. }
  14911. switch (pid) {
  14912. case videoPid:
  14913. if (stt) {
  14914. if (videoData && (pes = parsePES(videoData))) {
  14915. this.videoParser.parseAVCPES(videoTrack, textTrack, pes, false, this._duration);
  14916. }
  14917. videoData = {
  14918. data: [],
  14919. size: 0
  14920. };
  14921. }
  14922. if (videoData) {
  14923. videoData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  14924. videoData.size += start + PACKET_LENGTH - offset;
  14925. }
  14926. break;
  14927. case audioPid:
  14928. if (stt) {
  14929. if (audioData && (pes = parsePES(audioData))) {
  14930. switch (audioTrack.segmentCodec) {
  14931. case 'aac':
  14932. this.parseAACPES(audioTrack, pes);
  14933. break;
  14934. case 'mp3':
  14935. this.parseMPEGPES(audioTrack, pes);
  14936. break;
  14937. }
  14938. }
  14939. audioData = {
  14940. data: [],
  14941. size: 0
  14942. };
  14943. }
  14944. if (audioData) {
  14945. audioData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  14946. audioData.size += start + PACKET_LENGTH - offset;
  14947. }
  14948. break;
  14949. case id3Pid:
  14950. if (stt) {
  14951. if (id3Data && (pes = parsePES(id3Data))) {
  14952. this.parseID3PES(id3Track, pes);
  14953. }
  14954. id3Data = {
  14955. data: [],
  14956. size: 0
  14957. };
  14958. }
  14959. if (id3Data) {
  14960. id3Data.data.push(data.subarray(offset, start + PACKET_LENGTH));
  14961. id3Data.size += start + PACKET_LENGTH - offset;
  14962. }
  14963. break;
  14964. case 0:
  14965. if (stt) {
  14966. offset += data[offset] + 1;
  14967. }
  14968. pmtId = this._pmtId = parsePAT(data, offset);
  14969. // logger.log('PMT PID:' + this._pmtId);
  14970. break;
  14971. case pmtId:
  14972. {
  14973. if (stt) {
  14974. offset += data[offset] + 1;
  14975. }
  14976. var parsedPIDs = parsePMT(data, offset, this.typeSupported, isSampleAes, this.observer);
  14977. // only update track id if track PID found while parsing PMT
  14978. // this is to avoid resetting the PID to -1 in case
  14979. // track PID transiently disappears from the stream
  14980. // this could happen in case of transient missing audio samples for example
  14981. // NOTE this is only the PID of the track as found in TS,
  14982. // but we are not using this for MP4 track IDs.
  14983. videoPid = parsedPIDs.videoPid;
  14984. if (videoPid > 0) {
  14985. videoTrack.pid = videoPid;
  14986. videoTrack.segmentCodec = parsedPIDs.segmentVideoCodec;
  14987. }
  14988. audioPid = parsedPIDs.audioPid;
  14989. if (audioPid > 0) {
  14990. audioTrack.pid = audioPid;
  14991. audioTrack.segmentCodec = parsedPIDs.segmentAudioCodec;
  14992. }
  14993. id3Pid = parsedPIDs.id3Pid;
  14994. if (id3Pid > 0) {
  14995. id3Track.pid = id3Pid;
  14996. }
  14997. if (unknownPID !== null && !pmtParsed) {
  14998. logger.warn("MPEG-TS PMT found at " + start + " after unknown PID '" + unknownPID + "'. Backtracking to sync byte @" + syncOffset + " to parse all TS packets.");
  14999. unknownPID = null;
  15000. // we set it to -188, the += 188 in the for loop will reset start to 0
  15001. start = syncOffset - 188;
  15002. }
  15003. pmtParsed = this.pmtParsed = true;
  15004. break;
  15005. }
  15006. case 0x11:
  15007. case 0x1fff:
  15008. break;
  15009. default:
  15010. unknownPID = pid;
  15011. break;
  15012. }
  15013. } else {
  15014. tsPacketErrors++;
  15015. }
  15016. }
  15017. if (tsPacketErrors > 0) {
  15018. emitParsingError(this.observer, new Error("Found " + tsPacketErrors + " TS packet/s that do not start with 0x47"));
  15019. }
  15020. videoTrack.pesData = videoData;
  15021. audioTrack.pesData = audioData;
  15022. id3Track.pesData = id3Data;
  15023. var demuxResult = {
  15024. audioTrack: audioTrack,
  15025. videoTrack: videoTrack,
  15026. id3Track: id3Track,
  15027. textTrack: textTrack
  15028. };
  15029. if (flush) {
  15030. this.extractRemainingSamples(demuxResult);
  15031. }
  15032. return demuxResult;
  15033. };
  15034. _proto.flush = function flush() {
  15035. var remainderData = this.remainderData;
  15036. this.remainderData = null;
  15037. var result;
  15038. if (remainderData) {
  15039. result = this.demux(remainderData, -1, false, true);
  15040. } else {
  15041. result = {
  15042. videoTrack: this._videoTrack,
  15043. audioTrack: this._audioTrack,
  15044. id3Track: this._id3Track,
  15045. textTrack: this._txtTrack
  15046. };
  15047. }
  15048. this.extractRemainingSamples(result);
  15049. if (this.sampleAes) {
  15050. return this.decrypt(result, this.sampleAes);
  15051. }
  15052. return result;
  15053. };
  15054. _proto.extractRemainingSamples = function extractRemainingSamples(demuxResult) {
  15055. var audioTrack = demuxResult.audioTrack,
  15056. videoTrack = demuxResult.videoTrack,
  15057. id3Track = demuxResult.id3Track,
  15058. textTrack = demuxResult.textTrack;
  15059. var videoData = videoTrack.pesData;
  15060. var audioData = audioTrack.pesData;
  15061. var id3Data = id3Track.pesData;
  15062. // try to parse last PES packets
  15063. var pes;
  15064. if (videoData && (pes = parsePES(videoData))) {
  15065. this.videoParser.parseAVCPES(videoTrack, textTrack, pes, true, this._duration);
  15066. videoTrack.pesData = null;
  15067. } else {
  15068. // either avcData null or PES truncated, keep it for next frag parsing
  15069. videoTrack.pesData = videoData;
  15070. }
  15071. if (audioData && (pes = parsePES(audioData))) {
  15072. switch (audioTrack.segmentCodec) {
  15073. case 'aac':
  15074. this.parseAACPES(audioTrack, pes);
  15075. break;
  15076. case 'mp3':
  15077. this.parseMPEGPES(audioTrack, pes);
  15078. break;
  15079. }
  15080. audioTrack.pesData = null;
  15081. } else {
  15082. if (audioData != null && audioData.size) {
  15083. logger.log('last AAC PES packet truncated,might overlap between fragments');
  15084. }
  15085. // either audioData null or PES truncated, keep it for next frag parsing
  15086. audioTrack.pesData = audioData;
  15087. }
  15088. if (id3Data && (pes = parsePES(id3Data))) {
  15089. this.parseID3PES(id3Track, pes);
  15090. id3Track.pesData = null;
  15091. } else {
  15092. // either id3Data null or PES truncated, keep it for next frag parsing
  15093. id3Track.pesData = id3Data;
  15094. }
  15095. };
  15096. _proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
  15097. var demuxResult = this.demux(data, timeOffset, true, !this.config.progressive);
  15098. var sampleAes = this.sampleAes = new SampleAesDecrypter(this.observer, this.config, keyData);
  15099. return this.decrypt(demuxResult, sampleAes);
  15100. };
  15101. _proto.decrypt = function decrypt(demuxResult, sampleAes) {
  15102. return new Promise(function (resolve) {
  15103. var audioTrack = demuxResult.audioTrack,
  15104. videoTrack = demuxResult.videoTrack;
  15105. if (audioTrack.samples && audioTrack.segmentCodec === 'aac') {
  15106. sampleAes.decryptAacSamples(audioTrack.samples, 0, function () {
  15107. if (videoTrack.samples) {
  15108. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, function () {
  15109. resolve(demuxResult);
  15110. });
  15111. } else {
  15112. resolve(demuxResult);
  15113. }
  15114. });
  15115. } else if (videoTrack.samples) {
  15116. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, function () {
  15117. resolve(demuxResult);
  15118. });
  15119. }
  15120. });
  15121. };
  15122. _proto.destroy = function destroy() {
  15123. this._duration = 0;
  15124. };
  15125. _proto.parseAACPES = function parseAACPES(track, pes) {
  15126. var startOffset = 0;
  15127. var aacOverFlow = this.aacOverFlow;
  15128. var data = pes.data;
  15129. if (aacOverFlow) {
  15130. this.aacOverFlow = null;
  15131. var frameMissingBytes = aacOverFlow.missing;
  15132. var sampleLength = aacOverFlow.sample.unit.byteLength;
  15133. // logger.log(`AAC: append overflowing ${sampleLength} bytes to beginning of new PES`);
  15134. if (frameMissingBytes === -1) {
  15135. data = appendUint8Array(aacOverFlow.sample.unit, data);
  15136. } else {
  15137. var frameOverflowBytes = sampleLength - frameMissingBytes;
  15138. aacOverFlow.sample.unit.set(data.subarray(0, frameMissingBytes), frameOverflowBytes);
  15139. track.samples.push(aacOverFlow.sample);
  15140. startOffset = aacOverFlow.missing;
  15141. }
  15142. }
  15143. // look for ADTS header (0xFFFx)
  15144. var offset;
  15145. var len;
  15146. for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
  15147. if (isHeader$1(data, offset)) {
  15148. break;
  15149. }
  15150. }
  15151. // if ADTS header does not start straight from the beginning of the PES payload, raise an error
  15152. if (offset !== startOffset) {
  15153. var reason;
  15154. var recoverable = offset < len - 1;
  15155. if (recoverable) {
  15156. reason = "AAC PES did not start with ADTS header,offset:" + offset;
  15157. } else {
  15158. reason = 'No ADTS header found in AAC PES';
  15159. }
  15160. emitParsingError(this.observer, new Error(reason), recoverable);
  15161. if (!recoverable) {
  15162. return;
  15163. }
  15164. }
  15165. initTrackConfig(track, this.observer, data, offset, this.audioCodec);
  15166. var pts;
  15167. if (pes.pts !== undefined) {
  15168. pts = pes.pts;
  15169. } else if (aacOverFlow) {
  15170. // if last AAC frame is overflowing, we should ensure timestamps are contiguous:
  15171. // first sample PTS should be equal to last sample PTS + frameDuration
  15172. var frameDuration = getFrameDuration(track.samplerate);
  15173. pts = aacOverFlow.sample.pts + frameDuration;
  15174. } else {
  15175. logger.warn('[tsdemuxer]: AAC PES unknown PTS');
  15176. return;
  15177. }
  15178. // scan for aac samples
  15179. var frameIndex = 0;
  15180. var frame;
  15181. while (offset < len) {
  15182. frame = appendFrame$1(track, data, offset, pts, frameIndex);
  15183. offset += frame.length;
  15184. if (!frame.missing) {
  15185. frameIndex++;
  15186. for (; offset < len - 1; offset++) {
  15187. if (isHeader$1(data, offset)) {
  15188. break;
  15189. }
  15190. }
  15191. } else {
  15192. this.aacOverFlow = frame;
  15193. break;
  15194. }
  15195. }
  15196. };
  15197. _proto.parseMPEGPES = function parseMPEGPES(track, pes) {
  15198. var data = pes.data;
  15199. var length = data.length;
  15200. var frameIndex = 0;
  15201. var offset = 0;
  15202. var pts = pes.pts;
  15203. if (pts === undefined) {
  15204. logger.warn('[tsdemuxer]: MPEG PES unknown PTS');
  15205. return;
  15206. }
  15207. while (offset < length) {
  15208. if (isHeader(data, offset)) {
  15209. var frame = appendFrame(track, data, offset, pts, frameIndex);
  15210. if (frame) {
  15211. offset += frame.length;
  15212. frameIndex++;
  15213. } else {
  15214. // logger.log('Unable to parse Mpeg audio frame');
  15215. break;
  15216. }
  15217. } else {
  15218. // nothing found, keep looking
  15219. offset++;
  15220. }
  15221. }
  15222. };
  15223. _proto.parseAC3PES = function parseAC3PES(track, pes) {
  15224. };
  15225. _proto.parseID3PES = function parseID3PES(id3Track, pes) {
  15226. if (pes.pts === undefined) {
  15227. logger.warn('[tsdemuxer]: ID3 PES unknown PTS');
  15228. return;
  15229. }
  15230. var id3Sample = _extends({}, pes, {
  15231. type: this._videoTrack ? MetadataSchema.emsg : MetadataSchema.audioId3,
  15232. duration: Number.POSITIVE_INFINITY
  15233. });
  15234. id3Track.samples.push(id3Sample);
  15235. };
  15236. return TSDemuxer;
  15237. }();
  15238. function parsePID(data, offset) {
  15239. // pid is a 13-bit field starting at the last bit of TS[1]
  15240. return ((data[offset + 1] & 0x1f) << 8) + data[offset + 2];
  15241. }
  15242. function parsePAT(data, offset) {
  15243. // skip the PSI header and parse the first PMT entry
  15244. return (data[offset + 10] & 0x1f) << 8 | data[offset + 11];
  15245. }
  15246. function parsePMT(data, offset, typeSupported, isSampleAes, observer) {
  15247. var result = {
  15248. audioPid: -1,
  15249. videoPid: -1,
  15250. id3Pid: -1,
  15251. segmentVideoCodec: 'avc',
  15252. segmentAudioCodec: 'aac'
  15253. };
  15254. var sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
  15255. var tableEnd = offset + 3 + sectionLength - 4;
  15256. // to determine where the table is, we have to figure out how
  15257. // long the program info descriptors are
  15258. var programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11];
  15259. // advance the offset to the first entry in the mapping table
  15260. offset += 12 + programInfoLength;
  15261. while (offset < tableEnd) {
  15262. var pid = parsePID(data, offset);
  15263. var esInfoLength = (data[offset + 3] & 0x0f) << 8 | data[offset + 4];
  15264. switch (data[offset]) {
  15265. case 0xcf:
  15266. // SAMPLE-AES AAC
  15267. if (!isSampleAes) {
  15268. logEncryptedSamplesFoundInUnencryptedStream('ADTS AAC');
  15269. break;
  15270. }
  15271. /* falls through */
  15272. case 0x0f:
  15273. // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
  15274. // logger.log('AAC PID:' + pid);
  15275. if (result.audioPid === -1) {
  15276. result.audioPid = pid;
  15277. }
  15278. break;
  15279. // Packetized metadata (ID3)
  15280. case 0x15:
  15281. // logger.log('ID3 PID:' + pid);
  15282. if (result.id3Pid === -1) {
  15283. result.id3Pid = pid;
  15284. }
  15285. break;
  15286. case 0xdb:
  15287. // SAMPLE-AES AVC
  15288. if (!isSampleAes) {
  15289. logEncryptedSamplesFoundInUnencryptedStream('H.264');
  15290. break;
  15291. }
  15292. /* falls through */
  15293. case 0x1b:
  15294. // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
  15295. // logger.log('AVC PID:' + pid);
  15296. if (result.videoPid === -1) {
  15297. result.videoPid = pid;
  15298. result.segmentVideoCodec = 'avc';
  15299. }
  15300. break;
  15301. // ISO/IEC 11172-3 (MPEG-1 audio)
  15302. // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)
  15303. case 0x03:
  15304. case 0x04:
  15305. // logger.log('MPEG PID:' + pid);
  15306. if (!typeSupported.mpeg && !typeSupported.mp3) {
  15307. logger.log('MPEG audio found, not supported in this browser');
  15308. } else if (result.audioPid === -1) {
  15309. result.audioPid = pid;
  15310. result.segmentAudioCodec = 'mp3';
  15311. }
  15312. break;
  15313. case 0xc1:
  15314. // SAMPLE-AES AC3
  15315. if (!isSampleAes) {
  15316. logEncryptedSamplesFoundInUnencryptedStream('AC-3');
  15317. break;
  15318. }
  15319. /* falls through */
  15320. case 0x81:
  15321. {
  15322. logger.warn('AC-3 in M2TS support not included in build');
  15323. }
  15324. break;
  15325. case 0x06:
  15326. // stream_type 6 can mean a lot of different things in case of DVB.
  15327. // We need to look at the descriptors. Right now, we're only interested
  15328. // in AC-3 audio, so we do the descriptor parsing only when we don't have
  15329. // an audio PID yet.
  15330. if (result.audioPid === -1 && esInfoLength > 0) {
  15331. var parsePos = offset + 5;
  15332. var remaining = esInfoLength;
  15333. while (remaining > 2) {
  15334. var descriptorId = data[parsePos];
  15335. switch (descriptorId) {
  15336. case 0x6a:
  15337. // DVB Descriptor for AC-3
  15338. {
  15339. logger.warn('AC-3 in M2TS support not included in build');
  15340. }
  15341. break;
  15342. }
  15343. var descriptorLen = data[parsePos + 1] + 2;
  15344. parsePos += descriptorLen;
  15345. remaining -= descriptorLen;
  15346. }
  15347. }
  15348. break;
  15349. case 0xc2: // SAMPLE-AES EC3
  15350. /* falls through */
  15351. case 0x87:
  15352. emitParsingError(observer, new Error('Unsupported EC-3 in M2TS found'));
  15353. return result;
  15354. case 0x24:
  15355. emitParsingError(observer, new Error('Unsupported HEVC in M2TS found'));
  15356. return result;
  15357. }
  15358. // move to the next table entry
  15359. // skip past the elementary stream descriptors, if present
  15360. offset += esInfoLength + 5;
  15361. }
  15362. return result;
  15363. }
  15364. function emitParsingError(observer, error, levelRetry) {
  15365. logger.warn("parsing error: " + error.message);
  15366. observer.emit(Events.ERROR, Events.ERROR, {
  15367. type: ErrorTypes.MEDIA_ERROR,
  15368. details: ErrorDetails.FRAG_PARSING_ERROR,
  15369. fatal: false,
  15370. levelRetry: levelRetry,
  15371. error: error,
  15372. reason: error.message
  15373. });
  15374. }
  15375. function logEncryptedSamplesFoundInUnencryptedStream(type) {
  15376. logger.log(type + " with AES-128-CBC encryption found in unencrypted stream");
  15377. }
  15378. function parsePES(stream) {
  15379. var i = 0;
  15380. var frag;
  15381. var pesLen;
  15382. var pesHdrLen;
  15383. var pesPts;
  15384. var pesDts;
  15385. var data = stream.data;
  15386. // safety check
  15387. if (!stream || stream.size === 0) {
  15388. return null;
  15389. }
  15390. // we might need up to 19 bytes to read PES header
  15391. // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes
  15392. // usually only one merge is needed (and this is rare ...)
  15393. while (data[0].length < 19 && data.length > 1) {
  15394. data[0] = appendUint8Array(data[0], data[1]);
  15395. data.splice(1, 1);
  15396. }
  15397. // retrieve PTS/DTS from first fragment
  15398. frag = data[0];
  15399. var pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
  15400. if (pesPrefix === 1) {
  15401. pesLen = (frag[4] << 8) + frag[5];
  15402. // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated
  15403. // minus 6 : PES header size
  15404. if (pesLen && pesLen > stream.size - 6) {
  15405. return null;
  15406. }
  15407. var pesFlags = frag[7];
  15408. if (pesFlags & 0xc0) {
  15409. /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  15410. as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
  15411. as Bitwise operators treat their operands as a sequence of 32 bits */
  15412. pesPts = (frag[9] & 0x0e) * 536870912 +
  15413. // 1 << 29
  15414. (frag[10] & 0xff) * 4194304 +
  15415. // 1 << 22
  15416. (frag[11] & 0xfe) * 16384 +
  15417. // 1 << 14
  15418. (frag[12] & 0xff) * 128 +
  15419. // 1 << 7
  15420. (frag[13] & 0xfe) / 2;
  15421. if (pesFlags & 0x40) {
  15422. pesDts = (frag[14] & 0x0e) * 536870912 +
  15423. // 1 << 29
  15424. (frag[15] & 0xff) * 4194304 +
  15425. // 1 << 22
  15426. (frag[16] & 0xfe) * 16384 +
  15427. // 1 << 14
  15428. (frag[17] & 0xff) * 128 +
  15429. // 1 << 7
  15430. (frag[18] & 0xfe) / 2;
  15431. if (pesPts - pesDts > 60 * 90000) {
  15432. logger.warn(Math.round((pesPts - pesDts) / 90000) + "s delta between PTS and DTS, align them");
  15433. pesPts = pesDts;
  15434. }
  15435. } else {
  15436. pesDts = pesPts;
  15437. }
  15438. }
  15439. pesHdrLen = frag[8];
  15440. // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension
  15441. var payloadStartOffset = pesHdrLen + 9;
  15442. if (stream.size <= payloadStartOffset) {
  15443. return null;
  15444. }
  15445. stream.size -= payloadStartOffset;
  15446. // reassemble PES packet
  15447. var pesData = new Uint8Array(stream.size);
  15448. for (var j = 0, dataLen = data.length; j < dataLen; j++) {
  15449. frag = data[j];
  15450. var len = frag.byteLength;
  15451. if (payloadStartOffset) {
  15452. if (payloadStartOffset > len) {
  15453. // trim full frag if PES header bigger than frag
  15454. payloadStartOffset -= len;
  15455. continue;
  15456. } else {
  15457. // trim partial frag if PES header smaller than frag
  15458. frag = frag.subarray(payloadStartOffset);
  15459. len -= payloadStartOffset;
  15460. payloadStartOffset = 0;
  15461. }
  15462. }
  15463. pesData.set(frag, i);
  15464. i += len;
  15465. }
  15466. if (pesLen) {
  15467. // payload size : remove PES header + PES extension
  15468. pesLen -= pesHdrLen + 3;
  15469. }
  15470. return {
  15471. data: pesData,
  15472. pts: pesPts,
  15473. dts: pesDts,
  15474. len: pesLen
  15475. };
  15476. }
  15477. return null;
  15478. }
  15479. var MP3Demuxer = /*#__PURE__*/function (_BaseAudioDemuxer) {
  15480. _inheritsLoose(MP3Demuxer, _BaseAudioDemuxer);
  15481. function MP3Demuxer() {
  15482. return _BaseAudioDemuxer.apply(this, arguments) || this;
  15483. }
  15484. var _proto = MP3Demuxer.prototype;
  15485. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  15486. _BaseAudioDemuxer.prototype.resetInitSegment.call(this, initSegment, audioCodec, videoCodec, trackDuration);
  15487. this._audioTrack = {
  15488. container: 'audio/mpeg',
  15489. type: 'audio',
  15490. id: 2,
  15491. pid: -1,
  15492. sequenceNumber: 0,
  15493. segmentCodec: 'mp3',
  15494. samples: [],
  15495. manifestCodec: audioCodec,
  15496. duration: trackDuration,
  15497. inputTimeScale: 90000,
  15498. dropped: 0
  15499. };
  15500. };
  15501. MP3Demuxer.probe = function probe$1(data) {
  15502. if (!data) {
  15503. return false;
  15504. }
  15505. // check if data contains ID3 timestamp and MPEG sync word
  15506. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  15507. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  15508. // More info http://www.mp3-tech.org/programmer/frame_header.html
  15509. var id3Data = getID3Data(data, 0);
  15510. var offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  15511. // Check for ac-3|ec-3 sync bytes and return false if present
  15512. if (id3Data && data[offset] === 0x0b && data[offset + 1] === 0x77 && getTimeStamp(id3Data) !== undefined &&
  15513. // check the bsid to confirm ac-3 or ec-3 (not mp3)
  15514. getAudioBSID(data, offset) <= 16) {
  15515. return false;
  15516. }
  15517. for (var length = data.length; offset < length; offset++) {
  15518. if (probe(data, offset)) {
  15519. logger.log('MPEG Audio sync word found !');
  15520. return true;
  15521. }
  15522. }
  15523. return false;
  15524. };
  15525. _proto.canParse = function canParse$1(data, offset) {
  15526. return canParse(data, offset);
  15527. };
  15528. _proto.appendFrame = function appendFrame$1(track, data, offset) {
  15529. if (this.basePTS === null) {
  15530. return;
  15531. }
  15532. return appendFrame(track, data, offset, this.basePTS, this.frameIndex);
  15533. };
  15534. return MP3Demuxer;
  15535. }(BaseAudioDemuxer);
  15536. /**
  15537. * AAC helper
  15538. */
  15539. var AAC = /*#__PURE__*/function () {
  15540. function AAC() {}
  15541. AAC.getSilentFrame = function getSilentFrame(codec, channelCount) {
  15542. switch (codec) {
  15543. case 'mp4a.40.2':
  15544. if (channelCount === 1) {
  15545. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
  15546. } else if (channelCount === 2) {
  15547. return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
  15548. } else if (channelCount === 3) {
  15549. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
  15550. } else if (channelCount === 4) {
  15551. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
  15552. } else if (channelCount === 5) {
  15553. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
  15554. } else if (channelCount === 6) {
  15555. 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]);
  15556. }
  15557. break;
  15558. // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)
  15559. default:
  15560. if (channelCount === 1) {
  15561. // 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
  15562. 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]);
  15563. } else if (channelCount === 2) {
  15564. // 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
  15565. 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]);
  15566. } else if (channelCount === 3) {
  15567. // 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
  15568. 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]);
  15569. }
  15570. break;
  15571. }
  15572. return undefined;
  15573. };
  15574. return AAC;
  15575. }();
  15576. /**
  15577. * Generate MP4 Box
  15578. */
  15579. var UINT32_MAX = Math.pow(2, 32) - 1;
  15580. var MP4 = /*#__PURE__*/function () {
  15581. function MP4() {}
  15582. MP4.init = function init() {
  15583. MP4.types = {
  15584. avc1: [],
  15585. // codingname
  15586. avcC: [],
  15587. btrt: [],
  15588. dinf: [],
  15589. dref: [],
  15590. esds: [],
  15591. ftyp: [],
  15592. hdlr: [],
  15593. mdat: [],
  15594. mdhd: [],
  15595. mdia: [],
  15596. mfhd: [],
  15597. minf: [],
  15598. moof: [],
  15599. moov: [],
  15600. mp4a: [],
  15601. '.mp3': [],
  15602. dac3: [],
  15603. 'ac-3': [],
  15604. mvex: [],
  15605. mvhd: [],
  15606. pasp: [],
  15607. sdtp: [],
  15608. stbl: [],
  15609. stco: [],
  15610. stsc: [],
  15611. stsd: [],
  15612. stsz: [],
  15613. stts: [],
  15614. tfdt: [],
  15615. tfhd: [],
  15616. traf: [],
  15617. trak: [],
  15618. trun: [],
  15619. trex: [],
  15620. tkhd: [],
  15621. vmhd: [],
  15622. smhd: []
  15623. };
  15624. var i;
  15625. for (i in MP4.types) {
  15626. if (MP4.types.hasOwnProperty(i)) {
  15627. MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  15628. }
  15629. }
  15630. var videoHdlr = new Uint8Array([0x00,
  15631. // version 0
  15632. 0x00, 0x00, 0x00,
  15633. // flags
  15634. 0x00, 0x00, 0x00, 0x00,
  15635. // pre_defined
  15636. 0x76, 0x69, 0x64, 0x65,
  15637. // handler_type: 'vide'
  15638. 0x00, 0x00, 0x00, 0x00,
  15639. // reserved
  15640. 0x00, 0x00, 0x00, 0x00,
  15641. // reserved
  15642. 0x00, 0x00, 0x00, 0x00,
  15643. // reserved
  15644. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  15645. ]);
  15646. var audioHdlr = new Uint8Array([0x00,
  15647. // version 0
  15648. 0x00, 0x00, 0x00,
  15649. // flags
  15650. 0x00, 0x00, 0x00, 0x00,
  15651. // pre_defined
  15652. 0x73, 0x6f, 0x75, 0x6e,
  15653. // handler_type: 'soun'
  15654. 0x00, 0x00, 0x00, 0x00,
  15655. // reserved
  15656. 0x00, 0x00, 0x00, 0x00,
  15657. // reserved
  15658. 0x00, 0x00, 0x00, 0x00,
  15659. // reserved
  15660. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  15661. ]);
  15662. MP4.HDLR_TYPES = {
  15663. video: videoHdlr,
  15664. audio: audioHdlr
  15665. };
  15666. var dref = new Uint8Array([0x00,
  15667. // version 0
  15668. 0x00, 0x00, 0x00,
  15669. // flags
  15670. 0x00, 0x00, 0x00, 0x01,
  15671. // entry_count
  15672. 0x00, 0x00, 0x00, 0x0c,
  15673. // entry_size
  15674. 0x75, 0x72, 0x6c, 0x20,
  15675. // 'url' type
  15676. 0x00,
  15677. // version 0
  15678. 0x00, 0x00, 0x01 // entry_flags
  15679. ]);
  15680. var stco = new Uint8Array([0x00,
  15681. // version
  15682. 0x00, 0x00, 0x00,
  15683. // flags
  15684. 0x00, 0x00, 0x00, 0x00 // entry_count
  15685. ]);
  15686. MP4.STTS = MP4.STSC = MP4.STCO = stco;
  15687. MP4.STSZ = new Uint8Array([0x00,
  15688. // version
  15689. 0x00, 0x00, 0x00,
  15690. // flags
  15691. 0x00, 0x00, 0x00, 0x00,
  15692. // sample_size
  15693. 0x00, 0x00, 0x00, 0x00 // sample_count
  15694. ]);
  15695. MP4.VMHD = new Uint8Array([0x00,
  15696. // version
  15697. 0x00, 0x00, 0x01,
  15698. // flags
  15699. 0x00, 0x00,
  15700. // graphicsmode
  15701. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  15702. ]);
  15703. MP4.SMHD = new Uint8Array([0x00,
  15704. // version
  15705. 0x00, 0x00, 0x00,
  15706. // flags
  15707. 0x00, 0x00,
  15708. // balance
  15709. 0x00, 0x00 // reserved
  15710. ]);
  15711. MP4.STSD = new Uint8Array([0x00,
  15712. // version 0
  15713. 0x00, 0x00, 0x00,
  15714. // flags
  15715. 0x00, 0x00, 0x00, 0x01]); // entry_count
  15716. var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom
  15717. var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1
  15718. var minorVersion = new Uint8Array([0, 0, 0, 1]);
  15719. MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
  15720. MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
  15721. };
  15722. MP4.box = function box(type) {
  15723. var size = 8;
  15724. for (var _len = arguments.length, payload = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  15725. payload[_key - 1] = arguments[_key];
  15726. }
  15727. var i = payload.length;
  15728. var len = i;
  15729. // calculate the total size we need to allocate
  15730. while (i--) {
  15731. size += payload[i].byteLength;
  15732. }
  15733. var result = new Uint8Array(size);
  15734. result[0] = size >> 24 & 0xff;
  15735. result[1] = size >> 16 & 0xff;
  15736. result[2] = size >> 8 & 0xff;
  15737. result[3] = size & 0xff;
  15738. result.set(type, 4);
  15739. // copy the payload into the result
  15740. for (i = 0, size = 8; i < len; i++) {
  15741. // copy payload[i] array @ offset size
  15742. result.set(payload[i], size);
  15743. size += payload[i].byteLength;
  15744. }
  15745. return result;
  15746. };
  15747. MP4.hdlr = function hdlr(type) {
  15748. return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
  15749. };
  15750. MP4.mdat = function mdat(data) {
  15751. return MP4.box(MP4.types.mdat, data);
  15752. };
  15753. MP4.mdhd = function mdhd(timescale, duration) {
  15754. duration *= timescale;
  15755. var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  15756. var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  15757. return MP4.box(MP4.types.mdhd, new Uint8Array([0x01,
  15758. // version 1
  15759. 0x00, 0x00, 0x00,
  15760. // flags
  15761. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  15762. // creation_time
  15763. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  15764. // modification_time
  15765. timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff,
  15766. // timescale
  15767. upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x55, 0xc4,
  15768. // 'und' language (undetermined)
  15769. 0x00, 0x00]));
  15770. };
  15771. MP4.mdia = function mdia(track) {
  15772. return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));
  15773. };
  15774. MP4.mfhd = function mfhd(sequenceNumber) {
  15775. return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00,
  15776. // flags
  15777. sequenceNumber >> 24, sequenceNumber >> 16 & 0xff, sequenceNumber >> 8 & 0xff, sequenceNumber & 0xff // sequence_number
  15778. ]));
  15779. };
  15780. MP4.minf = function minf(track) {
  15781. if (track.type === 'audio') {
  15782. return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
  15783. } else {
  15784. return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
  15785. }
  15786. };
  15787. MP4.moof = function moof(sn, baseMediaDecodeTime, track) {
  15788. return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
  15789. };
  15790. MP4.moov = function moov(tracks) {
  15791. var i = tracks.length;
  15792. var boxes = [];
  15793. while (i--) {
  15794. boxes[i] = MP4.trak(tracks[i]);
  15795. }
  15796. return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));
  15797. };
  15798. MP4.mvex = function mvex(tracks) {
  15799. var i = tracks.length;
  15800. var boxes = [];
  15801. while (i--) {
  15802. boxes[i] = MP4.trex(tracks[i]);
  15803. }
  15804. return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));
  15805. };
  15806. MP4.mvhd = function mvhd(timescale, duration) {
  15807. duration *= timescale;
  15808. var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  15809. var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  15810. var bytes = new Uint8Array([0x01,
  15811. // version 1
  15812. 0x00, 0x00, 0x00,
  15813. // flags
  15814. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  15815. // creation_time
  15816. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  15817. // modification_time
  15818. timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff,
  15819. // timescale
  15820. upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x00, 0x01, 0x00, 0x00,
  15821. // 1.0 rate
  15822. 0x01, 0x00,
  15823. // 1.0 volume
  15824. 0x00, 0x00,
  15825. // reserved
  15826. 0x00, 0x00, 0x00, 0x00,
  15827. // reserved
  15828. 0x00, 0x00, 0x00, 0x00,
  15829. // reserved
  15830. 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,
  15831. // transformation: unity matrix
  15832. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  15833. // pre_defined
  15834. 0xff, 0xff, 0xff, 0xff // next_track_ID
  15835. ]);
  15836. return MP4.box(MP4.types.mvhd, bytes);
  15837. };
  15838. MP4.sdtp = function sdtp(track) {
  15839. var samples = track.samples || [];
  15840. var bytes = new Uint8Array(4 + samples.length);
  15841. var i;
  15842. var flags;
  15843. // leave the full box header (4 bytes) all zero
  15844. // write the sample table
  15845. for (i = 0; i < samples.length; i++) {
  15846. flags = samples[i].flags;
  15847. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  15848. }
  15849. return MP4.box(MP4.types.sdtp, bytes);
  15850. };
  15851. MP4.stbl = function stbl(track) {
  15852. 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));
  15853. };
  15854. MP4.avc1 = function avc1(track) {
  15855. var sps = [];
  15856. var pps = [];
  15857. var i;
  15858. var data;
  15859. var len;
  15860. // assemble the SPSs
  15861. for (i = 0; i < track.sps.length; i++) {
  15862. data = track.sps[i];
  15863. len = data.byteLength;
  15864. sps.push(len >>> 8 & 0xff);
  15865. sps.push(len & 0xff);
  15866. // SPS
  15867. sps = sps.concat(Array.prototype.slice.call(data));
  15868. }
  15869. // assemble the PPSs
  15870. for (i = 0; i < track.pps.length; i++) {
  15871. data = track.pps[i];
  15872. len = data.byteLength;
  15873. pps.push(len >>> 8 & 0xff);
  15874. pps.push(len & 0xff);
  15875. pps = pps.concat(Array.prototype.slice.call(data));
  15876. }
  15877. var avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01,
  15878. // version
  15879. sps[3],
  15880. // profile
  15881. sps[4],
  15882. // profile compat
  15883. sps[5],
  15884. // level
  15885. 0xfc | 3,
  15886. // lengthSizeMinusOne, hard-coded to 4 bytes
  15887. 0xe0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets
  15888. ].concat(sps).concat([track.pps.length // numOfPictureParameterSets
  15889. ]).concat(pps))); // "PPS"
  15890. var width = track.width;
  15891. var height = track.height;
  15892. var hSpacing = track.pixelRatio[0];
  15893. var vSpacing = track.pixelRatio[1];
  15894. return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00,
  15895. // reserved
  15896. 0x00, 0x00, 0x00,
  15897. // reserved
  15898. 0x00, 0x01,
  15899. // data_reference_index
  15900. 0x00, 0x00,
  15901. // pre_defined
  15902. 0x00, 0x00,
  15903. // reserved
  15904. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  15905. // pre_defined
  15906. width >> 8 & 0xff, width & 0xff,
  15907. // width
  15908. height >> 8 & 0xff, height & 0xff,
  15909. // height
  15910. 0x00, 0x48, 0x00, 0x00,
  15911. // horizresolution
  15912. 0x00, 0x48, 0x00, 0x00,
  15913. // vertresolution
  15914. 0x00, 0x00, 0x00, 0x00,
  15915. // reserved
  15916. 0x00, 0x01,
  15917. // frame_count
  15918. 0x12, 0x64, 0x61, 0x69, 0x6c,
  15919. // dailymotion/hls.js
  15920. 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,
  15921. // compressorname
  15922. 0x00, 0x18,
  15923. // depth = 24
  15924. 0x11, 0x11]),
  15925. // pre_defined = -1
  15926. avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80,
  15927. // bufferSizeDB
  15928. 0x00, 0x2d, 0xc6, 0xc0,
  15929. // maxBitrate
  15930. 0x00, 0x2d, 0xc6, 0xc0])),
  15931. // avgBitrate
  15932. MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24,
  15933. // hSpacing
  15934. hSpacing >> 16 & 0xff, hSpacing >> 8 & 0xff, hSpacing & 0xff, vSpacing >> 24,
  15935. // vSpacing
  15936. vSpacing >> 16 & 0xff, vSpacing >> 8 & 0xff, vSpacing & 0xff])));
  15937. };
  15938. MP4.esds = function esds(track) {
  15939. var configlen = track.config.length;
  15940. return new Uint8Array([0x00,
  15941. // version 0
  15942. 0x00, 0x00, 0x00,
  15943. // flags
  15944. 0x03,
  15945. // descriptor_type
  15946. 0x17 + configlen,
  15947. // length
  15948. 0x00, 0x01,
  15949. // es_id
  15950. 0x00,
  15951. // stream_priority
  15952. 0x04,
  15953. // descriptor_type
  15954. 0x0f + configlen,
  15955. // length
  15956. 0x40,
  15957. // codec : mpeg4_audio
  15958. 0x15,
  15959. // stream_type
  15960. 0x00, 0x00, 0x00,
  15961. // buffer_size
  15962. 0x00, 0x00, 0x00, 0x00,
  15963. // maxBitrate
  15964. 0x00, 0x00, 0x00, 0x00,
  15965. // avgBitrate
  15966. 0x05 // descriptor_type
  15967. ].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor
  15968. };
  15969. MP4.audioStsd = function audioStsd(track) {
  15970. var samplerate = track.samplerate;
  15971. return new Uint8Array([0x00, 0x00, 0x00,
  15972. // reserved
  15973. 0x00, 0x00, 0x00,
  15974. // reserved
  15975. 0x00, 0x01,
  15976. // data_reference_index
  15977. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  15978. // reserved
  15979. 0x00, track.channelCount,
  15980. // channelcount
  15981. 0x00, 0x10,
  15982. // sampleSize:16bits
  15983. 0x00, 0x00, 0x00, 0x00,
  15984. // reserved2
  15985. samplerate >> 8 & 0xff, samplerate & 0xff,
  15986. //
  15987. 0x00, 0x00]);
  15988. };
  15989. MP4.mp4a = function mp4a(track) {
  15990. return MP4.box(MP4.types.mp4a, MP4.audioStsd(track), MP4.box(MP4.types.esds, MP4.esds(track)));
  15991. };
  15992. MP4.mp3 = function mp3(track) {
  15993. return MP4.box(MP4.types['.mp3'], MP4.audioStsd(track));
  15994. };
  15995. MP4.ac3 = function ac3(track) {
  15996. return MP4.box(MP4.types['ac-3'], MP4.audioStsd(track), MP4.box(MP4.types.dac3, track.config));
  15997. };
  15998. MP4.stsd = function stsd(track) {
  15999. if (track.type === 'audio') {
  16000. if (track.segmentCodec === 'mp3' && track.codec === 'mp3') {
  16001. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));
  16002. }
  16003. if (track.segmentCodec === 'ac3') {
  16004. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.ac3(track));
  16005. }
  16006. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
  16007. } else {
  16008. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
  16009. }
  16010. };
  16011. MP4.tkhd = function tkhd(track) {
  16012. var id = track.id;
  16013. var duration = track.duration * track.timescale;
  16014. var width = track.width;
  16015. var height = track.height;
  16016. var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  16017. var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  16018. return MP4.box(MP4.types.tkhd, new Uint8Array([0x01,
  16019. // version 1
  16020. 0x00, 0x00, 0x07,
  16021. // flags
  16022. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  16023. // creation_time
  16024. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  16025. // modification_time
  16026. id >> 24 & 0xff, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff,
  16027. // track_ID
  16028. 0x00, 0x00, 0x00, 0x00,
  16029. // reserved
  16030. 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,
  16031. // reserved
  16032. 0x00, 0x00,
  16033. // layer
  16034. 0x00, 0x00,
  16035. // alternate_group
  16036. 0x00, 0x00,
  16037. // non-audio track volume
  16038. 0x00, 0x00,
  16039. // reserved
  16040. 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,
  16041. // transformation: unity matrix
  16042. width >> 8 & 0xff, width & 0xff, 0x00, 0x00,
  16043. // width
  16044. height >> 8 & 0xff, height & 0xff, 0x00, 0x00 // height
  16045. ]));
  16046. };
  16047. MP4.traf = function traf(track, baseMediaDecodeTime) {
  16048. var sampleDependencyTable = MP4.sdtp(track);
  16049. var id = track.id;
  16050. var upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
  16051. var lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
  16052. return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00,
  16053. // version 0
  16054. 0x00, 0x00, 0x00,
  16055. // flags
  16056. id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff // track_ID
  16057. ])), MP4.box(MP4.types.tfdt, new Uint8Array([0x01,
  16058. // version 1
  16059. 0x00, 0x00, 0x00,
  16060. // flags
  16061. 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 +
  16062. // tfhd
  16063. 20 +
  16064. // tfdt
  16065. 8 +
  16066. // traf header
  16067. 16 +
  16068. // mfhd
  16069. 8 +
  16070. // moof header
  16071. 8),
  16072. // mdat header
  16073. sampleDependencyTable);
  16074. }
  16075. /**
  16076. * Generate a track box.
  16077. * @param track a track definition
  16078. */;
  16079. MP4.trak = function trak(track) {
  16080. track.duration = track.duration || 0xffffffff;
  16081. return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
  16082. };
  16083. MP4.trex = function trex(track) {
  16084. var id = track.id;
  16085. return MP4.box(MP4.types.trex, new Uint8Array([0x00,
  16086. // version 0
  16087. 0x00, 0x00, 0x00,
  16088. // flags
  16089. id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff,
  16090. // track_ID
  16091. 0x00, 0x00, 0x00, 0x01,
  16092. // default_sample_description_index
  16093. 0x00, 0x00, 0x00, 0x00,
  16094. // default_sample_duration
  16095. 0x00, 0x00, 0x00, 0x00,
  16096. // default_sample_size
  16097. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  16098. ]));
  16099. };
  16100. MP4.trun = function trun(track, offset) {
  16101. var samples = track.samples || [];
  16102. var len = samples.length;
  16103. var arraylen = 12 + 16 * len;
  16104. var array = new Uint8Array(arraylen);
  16105. var i;
  16106. var sample;
  16107. var duration;
  16108. var size;
  16109. var flags;
  16110. var cts;
  16111. offset += 8 + arraylen;
  16112. array.set([track.type === 'video' ? 0x01 : 0x00,
  16113. // version 1 for video with signed-int sample_composition_time_offset
  16114. 0x00, 0x0f, 0x01,
  16115. // flags
  16116. len >>> 24 & 0xff, len >>> 16 & 0xff, len >>> 8 & 0xff, len & 0xff,
  16117. // sample_count
  16118. offset >>> 24 & 0xff, offset >>> 16 & 0xff, offset >>> 8 & 0xff, offset & 0xff // data_offset
  16119. ], 0);
  16120. for (i = 0; i < len; i++) {
  16121. sample = samples[i];
  16122. duration = sample.duration;
  16123. size = sample.size;
  16124. flags = sample.flags;
  16125. cts = sample.cts;
  16126. array.set([duration >>> 24 & 0xff, duration >>> 16 & 0xff, duration >>> 8 & 0xff, duration & 0xff,
  16127. // sample_duration
  16128. size >>> 24 & 0xff, size >>> 16 & 0xff, size >>> 8 & 0xff, size & 0xff,
  16129. // sample_size
  16130. flags.isLeading << 2 | flags.dependsOn, flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync, flags.degradPrio & 0xf0 << 8, flags.degradPrio & 0x0f,
  16131. // sample_flags
  16132. cts >>> 24 & 0xff, cts >>> 16 & 0xff, cts >>> 8 & 0xff, cts & 0xff // sample_composition_time_offset
  16133. ], 12 + 16 * i);
  16134. }
  16135. return MP4.box(MP4.types.trun, array);
  16136. };
  16137. MP4.initSegment = function initSegment(tracks) {
  16138. if (!MP4.types) {
  16139. MP4.init();
  16140. }
  16141. var movie = MP4.moov(tracks);
  16142. var result = appendUint8Array(MP4.FTYP, movie);
  16143. return result;
  16144. };
  16145. return MP4;
  16146. }();
  16147. MP4.types = void 0;
  16148. MP4.HDLR_TYPES = void 0;
  16149. MP4.STTS = void 0;
  16150. MP4.STSC = void 0;
  16151. MP4.STCO = void 0;
  16152. MP4.STSZ = void 0;
  16153. MP4.VMHD = void 0;
  16154. MP4.SMHD = void 0;
  16155. MP4.STSD = void 0;
  16156. MP4.FTYP = void 0;
  16157. MP4.DINF = void 0;
  16158. var MPEG_TS_CLOCK_FREQ_HZ = 90000;
  16159. function toTimescaleFromBase(baseTime, destScale, srcBase, round) {
  16160. if (srcBase === void 0) {
  16161. srcBase = 1;
  16162. }
  16163. if (round === void 0) {
  16164. round = false;
  16165. }
  16166. var result = baseTime * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)`
  16167. return round ? Math.round(result) : result;
  16168. }
  16169. function toMsFromMpegTsClock(baseTime, round) {
  16170. if (round === void 0) {
  16171. round = false;
  16172. }
  16173. return toTimescaleFromBase(baseTime, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);
  16174. }
  16175. var MAX_SILENT_FRAME_DURATION = 10 * 1000; // 10 seconds
  16176. var AAC_SAMPLES_PER_FRAME = 1024;
  16177. var MPEG_AUDIO_SAMPLE_PER_FRAME = 1152;
  16178. var AC3_SAMPLES_PER_FRAME = 1536;
  16179. var chromeVersion = null;
  16180. var safariWebkitVersion = null;
  16181. var MP4Remuxer = /*#__PURE__*/function () {
  16182. function MP4Remuxer(observer, config, typeSupported, vendor) {
  16183. this.observer = void 0;
  16184. this.config = void 0;
  16185. this.typeSupported = void 0;
  16186. this.ISGenerated = false;
  16187. this._initPTS = null;
  16188. this._initDTS = null;
  16189. this.nextAvcDts = null;
  16190. this.nextAudioPts = null;
  16191. this.videoSampleDuration = null;
  16192. this.isAudioContiguous = false;
  16193. this.isVideoContiguous = false;
  16194. this.videoTrackConfig = void 0;
  16195. this.observer = observer;
  16196. this.config = config;
  16197. this.typeSupported = typeSupported;
  16198. this.ISGenerated = false;
  16199. if (chromeVersion === null) {
  16200. var userAgent = navigator.userAgent || '';
  16201. var result = userAgent.match(/Chrome\/(\d+)/i);
  16202. chromeVersion = result ? parseInt(result[1]) : 0;
  16203. }
  16204. if (safariWebkitVersion === null) {
  16205. var _result = navigator.userAgent.match(/Safari\/(\d+)/i);
  16206. safariWebkitVersion = _result ? parseInt(_result[1]) : 0;
  16207. }
  16208. }
  16209. var _proto = MP4Remuxer.prototype;
  16210. _proto.destroy = function destroy() {
  16211. // @ts-ignore
  16212. this.config = this.videoTrackConfig = this._initPTS = this._initDTS = null;
  16213. };
  16214. _proto.resetTimeStamp = function resetTimeStamp(defaultTimeStamp) {
  16215. logger.log('[mp4-remuxer]: initPTS & initDTS reset');
  16216. this._initPTS = this._initDTS = defaultTimeStamp;
  16217. };
  16218. _proto.resetNextTimestamp = function resetNextTimestamp() {
  16219. logger.log('[mp4-remuxer]: reset next timestamp');
  16220. this.isVideoContiguous = false;
  16221. this.isAudioContiguous = false;
  16222. };
  16223. _proto.resetInitSegment = function resetInitSegment() {
  16224. logger.log('[mp4-remuxer]: ISGenerated flag reset');
  16225. this.ISGenerated = false;
  16226. this.videoTrackConfig = undefined;
  16227. };
  16228. _proto.getVideoStartPts = function getVideoStartPts(videoSamples) {
  16229. var rolloverDetected = false;
  16230. var startPTS = videoSamples.reduce(function (minPTS, sample) {
  16231. var delta = sample.pts - minPTS;
  16232. if (delta < -4294967296) {
  16233. // 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation
  16234. rolloverDetected = true;
  16235. return normalizePts(minPTS, sample.pts);
  16236. } else if (delta > 0) {
  16237. return minPTS;
  16238. } else {
  16239. return sample.pts;
  16240. }
  16241. }, videoSamples[0].pts);
  16242. if (rolloverDetected) {
  16243. logger.debug('PTS rollover detected');
  16244. }
  16245. return startPTS;
  16246. };
  16247. _proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, flush, playlistType) {
  16248. var video;
  16249. var audio;
  16250. var initSegment;
  16251. var text;
  16252. var id3;
  16253. var independent;
  16254. var audioTimeOffset = timeOffset;
  16255. var videoTimeOffset = timeOffset;
  16256. // If we're remuxing audio and video progressively, wait until we've received enough samples for each track before proceeding.
  16257. // This is done to synchronize the audio and video streams. We know if the current segment will have samples if the "pid"
  16258. // parameter is greater than -1. The pid is set when the PMT is parsed, which contains the tracks list.
  16259. // However, if the initSegment has already been generated, or we've reached the end of a segment (flush),
  16260. // then we can remux one track without waiting for the other.
  16261. var hasAudio = audioTrack.pid > -1;
  16262. var hasVideo = videoTrack.pid > -1;
  16263. var length = videoTrack.samples.length;
  16264. var enoughAudioSamples = audioTrack.samples.length > 0;
  16265. var enoughVideoSamples = flush && length > 0 || length > 1;
  16266. var canRemuxAvc = (!hasAudio || enoughAudioSamples) && (!hasVideo || enoughVideoSamples) || this.ISGenerated || flush;
  16267. if (canRemuxAvc) {
  16268. if (this.ISGenerated) {
  16269. var _videoTrack$pixelRati, _config$pixelRatio, _videoTrack$pixelRati2, _config$pixelRatio2;
  16270. var config = this.videoTrackConfig;
  16271. 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]))) {
  16272. this.resetInitSegment();
  16273. }
  16274. } else {
  16275. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  16276. }
  16277. var isVideoContiguous = this.isVideoContiguous;
  16278. var firstKeyFrameIndex = -1;
  16279. var firstKeyFramePTS;
  16280. if (enoughVideoSamples) {
  16281. firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples);
  16282. if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) {
  16283. independent = true;
  16284. if (firstKeyFrameIndex > 0) {
  16285. logger.warn("[mp4-remuxer]: Dropped " + firstKeyFrameIndex + " out of " + length + " video samples due to a missing keyframe");
  16286. var startPTS = this.getVideoStartPts(videoTrack.samples);
  16287. videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex);
  16288. videoTrack.dropped += firstKeyFrameIndex;
  16289. videoTimeOffset += (videoTrack.samples[0].pts - startPTS) / videoTrack.inputTimeScale;
  16290. firstKeyFramePTS = videoTimeOffset;
  16291. } else if (firstKeyFrameIndex === -1) {
  16292. logger.warn("[mp4-remuxer]: No keyframe found out of " + length + " video samples");
  16293. independent = false;
  16294. }
  16295. }
  16296. }
  16297. if (this.ISGenerated) {
  16298. if (enoughAudioSamples && enoughVideoSamples) {
  16299. // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)
  16300. // if first audio DTS is not aligned with first video DTS then we need to take that into account
  16301. // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small
  16302. // drift between audio and video streams
  16303. var _startPTS = this.getVideoStartPts(videoTrack.samples);
  16304. var tsDelta = normalizePts(audioTrack.samples[0].pts, _startPTS) - _startPTS;
  16305. var audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;
  16306. audioTimeOffset += Math.max(0, audiovideoTimestampDelta);
  16307. videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);
  16308. }
  16309. // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is calculated in remuxAudio.
  16310. if (enoughAudioSamples) {
  16311. // if initSegment was generated without audio samples, regenerate it again
  16312. if (!audioTrack.samplerate) {
  16313. logger.warn('[mp4-remuxer]: regenerate InitSegment as audio detected');
  16314. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  16315. }
  16316. audio = this.remuxAudio(audioTrack, audioTimeOffset, this.isAudioContiguous, accurateTimeOffset, hasVideo || enoughVideoSamples || playlistType === PlaylistLevelType.AUDIO ? videoTimeOffset : undefined);
  16317. if (enoughVideoSamples) {
  16318. var audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0;
  16319. // if initSegment was generated without video samples, regenerate it again
  16320. if (!videoTrack.inputTimeScale) {
  16321. logger.warn('[mp4-remuxer]: regenerate InitSegment as video detected');
  16322. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  16323. }
  16324. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, audioTrackLength);
  16325. }
  16326. } else if (enoughVideoSamples) {
  16327. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, 0);
  16328. }
  16329. if (video) {
  16330. video.firstKeyFrame = firstKeyFrameIndex;
  16331. video.independent = firstKeyFrameIndex !== -1;
  16332. video.firstKeyFramePTS = firstKeyFramePTS;
  16333. }
  16334. }
  16335. }
  16336. // Allow ID3 and text to remux, even if more audio/video samples are required
  16337. if (this.ISGenerated && this._initPTS && this._initDTS) {
  16338. if (id3Track.samples.length) {
  16339. id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, this._initPTS, this._initDTS);
  16340. }
  16341. if (textTrack.samples.length) {
  16342. text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, this._initPTS);
  16343. }
  16344. }
  16345. return {
  16346. audio: audio,
  16347. video: video,
  16348. initSegment: initSegment,
  16349. independent: independent,
  16350. text: text,
  16351. id3: id3
  16352. };
  16353. };
  16354. _proto.generateIS = function generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset) {
  16355. var audioSamples = audioTrack.samples;
  16356. var videoSamples = videoTrack.samples;
  16357. var typeSupported = this.typeSupported;
  16358. var tracks = {};
  16359. var _initPTS = this._initPTS;
  16360. var computePTSDTS = !_initPTS || accurateTimeOffset;
  16361. var container = 'audio/mp4';
  16362. var initPTS;
  16363. var initDTS;
  16364. var timescale;
  16365. if (computePTSDTS) {
  16366. initPTS = initDTS = Infinity;
  16367. }
  16368. if (audioTrack.config && audioSamples.length) {
  16369. // let's use audio sampling rate as MP4 time scale.
  16370. // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)
  16371. // using audio sampling rate here helps having an integer MP4 frame duration
  16372. // this avoids potential rounding issue and AV sync issue
  16373. audioTrack.timescale = audioTrack.samplerate;
  16374. switch (audioTrack.segmentCodec) {
  16375. case 'mp3':
  16376. if (typeSupported.mpeg) {
  16377. // Chrome and Safari
  16378. container = 'audio/mpeg';
  16379. audioTrack.codec = '';
  16380. } else if (typeSupported.mp3) {
  16381. // Firefox
  16382. audioTrack.codec = 'mp3';
  16383. }
  16384. break;
  16385. case 'ac3':
  16386. audioTrack.codec = 'ac-3';
  16387. break;
  16388. }
  16389. tracks.audio = {
  16390. id: 'audio',
  16391. container: container,
  16392. codec: audioTrack.codec,
  16393. initSegment: audioTrack.segmentCodec === 'mp3' && typeSupported.mpeg ? new Uint8Array(0) : MP4.initSegment([audioTrack]),
  16394. metadata: {
  16395. channelCount: audioTrack.channelCount
  16396. }
  16397. };
  16398. if (computePTSDTS) {
  16399. timescale = audioTrack.inputTimeScale;
  16400. if (!_initPTS || timescale !== _initPTS.timescale) {
  16401. // remember first PTS of this demuxing context. for audio, PTS = DTS
  16402. initPTS = initDTS = audioSamples[0].pts - Math.round(timescale * timeOffset);
  16403. } else {
  16404. computePTSDTS = false;
  16405. }
  16406. }
  16407. }
  16408. if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
  16409. // let's use input time scale as MP4 video timescale
  16410. // we use input time scale straight away to avoid rounding issues on frame duration / cts computation
  16411. videoTrack.timescale = videoTrack.inputTimeScale;
  16412. tracks.video = {
  16413. id: 'main',
  16414. container: 'video/mp4',
  16415. codec: videoTrack.codec,
  16416. initSegment: MP4.initSegment([videoTrack]),
  16417. metadata: {
  16418. width: videoTrack.width,
  16419. height: videoTrack.height
  16420. }
  16421. };
  16422. if (computePTSDTS) {
  16423. timescale = videoTrack.inputTimeScale;
  16424. if (!_initPTS || timescale !== _initPTS.timescale) {
  16425. var startPTS = this.getVideoStartPts(videoSamples);
  16426. var startOffset = Math.round(timescale * timeOffset);
  16427. initDTS = Math.min(initDTS, normalizePts(videoSamples[0].dts, startPTS) - startOffset);
  16428. initPTS = Math.min(initPTS, startPTS - startOffset);
  16429. } else {
  16430. computePTSDTS = false;
  16431. }
  16432. }
  16433. this.videoTrackConfig = {
  16434. width: videoTrack.width,
  16435. height: videoTrack.height,
  16436. pixelRatio: videoTrack.pixelRatio
  16437. };
  16438. }
  16439. if (Object.keys(tracks).length) {
  16440. this.ISGenerated = true;
  16441. if (computePTSDTS) {
  16442. this._initPTS = {
  16443. baseTime: initPTS,
  16444. timescale: timescale
  16445. };
  16446. this._initDTS = {
  16447. baseTime: initDTS,
  16448. timescale: timescale
  16449. };
  16450. } else {
  16451. initPTS = timescale = undefined;
  16452. }
  16453. return {
  16454. tracks: tracks,
  16455. initPTS: initPTS,
  16456. timescale: timescale
  16457. };
  16458. }
  16459. };
  16460. _proto.remuxVideo = function remuxVideo(track, timeOffset, contiguous, audioTrackLength) {
  16461. var timeScale = track.inputTimeScale;
  16462. var inputSamples = track.samples;
  16463. var outputSamples = [];
  16464. var nbSamples = inputSamples.length;
  16465. var initPTS = this._initPTS;
  16466. var nextAvcDts = this.nextAvcDts;
  16467. var offset = 8;
  16468. var mp4SampleDuration = this.videoSampleDuration;
  16469. var firstDTS;
  16470. var lastDTS;
  16471. var minPTS = Number.POSITIVE_INFINITY;
  16472. var maxPTS = Number.NEGATIVE_INFINITY;
  16473. var sortSamples = false;
  16474. // if parsed fragment is contiguous with last one, let's use last DTS value as reference
  16475. if (!contiguous || nextAvcDts === null) {
  16476. var pts = timeOffset * timeScale;
  16477. var cts = inputSamples[0].pts - normalizePts(inputSamples[0].dts, inputSamples[0].pts);
  16478. if (chromeVersion && nextAvcDts !== null && Math.abs(pts - cts - nextAvcDts) < 15000) {
  16479. // treat as contigous to adjust samples that would otherwise produce video buffer gaps in Chrome
  16480. contiguous = true;
  16481. } else {
  16482. // if not contiguous, let's use target timeOffset
  16483. nextAvcDts = pts - cts;
  16484. }
  16485. }
  16486. // PTS is coded on 33bits, and can loop from -2^32 to 2^32
  16487. // PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value
  16488. var initTime = initPTS.baseTime * timeScale / initPTS.timescale;
  16489. for (var i = 0; i < nbSamples; i++) {
  16490. var sample = inputSamples[i];
  16491. sample.pts = normalizePts(sample.pts - initTime, nextAvcDts);
  16492. sample.dts = normalizePts(sample.dts - initTime, nextAvcDts);
  16493. if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {
  16494. sortSamples = true;
  16495. }
  16496. }
  16497. // sort video samples by DTS then PTS then demux id order
  16498. if (sortSamples) {
  16499. inputSamples.sort(function (a, b) {
  16500. var deltadts = a.dts - b.dts;
  16501. var deltapts = a.pts - b.pts;
  16502. return deltadts || deltapts;
  16503. });
  16504. }
  16505. // Get first/last DTS
  16506. firstDTS = inputSamples[0].dts;
  16507. lastDTS = inputSamples[inputSamples.length - 1].dts;
  16508. // Sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS
  16509. // set this constant duration as being the avg delta between consecutive DTS.
  16510. var inputDuration = lastDTS - firstDTS;
  16511. var averageSampleDuration = inputDuration ? Math.round(inputDuration / (nbSamples - 1)) : mp4SampleDuration || track.inputTimeScale / 30;
  16512. // if fragment are contiguous, detect hole/overlapping between fragments
  16513. if (contiguous) {
  16514. // check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)
  16515. var delta = firstDTS - nextAvcDts;
  16516. var foundHole = delta > averageSampleDuration;
  16517. var foundOverlap = delta < -1;
  16518. if (foundHole || foundOverlap) {
  16519. if (foundHole) {
  16520. logger.warn("AVC: " + toMsFromMpegTsClock(delta, true) + " ms (" + delta + "dts) hole between fragments detected at " + timeOffset.toFixed(3));
  16521. } else {
  16522. logger.warn("AVC: " + toMsFromMpegTsClock(-delta, true) + " ms (" + delta + "dts) overlapping between fragments detected at " + timeOffset.toFixed(3));
  16523. }
  16524. if (!foundOverlap || nextAvcDts >= inputSamples[0].pts || chromeVersion) {
  16525. firstDTS = nextAvcDts;
  16526. var firstPTS = inputSamples[0].pts - delta;
  16527. if (foundHole) {
  16528. inputSamples[0].dts = firstDTS;
  16529. inputSamples[0].pts = firstPTS;
  16530. } else {
  16531. for (var _i = 0; _i < inputSamples.length; _i++) {
  16532. if (inputSamples[_i].dts > firstPTS) {
  16533. break;
  16534. }
  16535. inputSamples[_i].dts -= delta;
  16536. inputSamples[_i].pts -= delta;
  16537. }
  16538. }
  16539. logger.log("Video: Initial PTS/DTS adjusted: " + toMsFromMpegTsClock(firstPTS, true) + "/" + toMsFromMpegTsClock(firstDTS, true) + ", delta: " + toMsFromMpegTsClock(delta, true) + " ms");
  16540. }
  16541. }
  16542. }
  16543. firstDTS = Math.max(0, firstDTS);
  16544. var nbNalu = 0;
  16545. var naluLen = 0;
  16546. var dtsStep = firstDTS;
  16547. for (var _i2 = 0; _i2 < nbSamples; _i2++) {
  16548. // compute total/avc sample length and nb of NAL units
  16549. var _sample = inputSamples[_i2];
  16550. var units = _sample.units;
  16551. var nbUnits = units.length;
  16552. var sampleLen = 0;
  16553. for (var j = 0; j < nbUnits; j++) {
  16554. sampleLen += units[j].data.length;
  16555. }
  16556. naluLen += sampleLen;
  16557. nbNalu += nbUnits;
  16558. _sample.length = sampleLen;
  16559. // ensure sample monotonic DTS
  16560. if (_sample.dts < dtsStep) {
  16561. _sample.dts = dtsStep;
  16562. dtsStep += averageSampleDuration / 4 | 0 || 1;
  16563. } else {
  16564. dtsStep = _sample.dts;
  16565. }
  16566. minPTS = Math.min(_sample.pts, minPTS);
  16567. maxPTS = Math.max(_sample.pts, maxPTS);
  16568. }
  16569. lastDTS = inputSamples[nbSamples - 1].dts;
  16570. /* concatenate the video data and construct the mdat in place
  16571. (need 8 more bytes to fill length and mpdat type) */
  16572. var mdatSize = naluLen + 4 * nbNalu + 8;
  16573. var mdat;
  16574. try {
  16575. mdat = new Uint8Array(mdatSize);
  16576. } catch (err) {
  16577. this.observer.emit(Events.ERROR, Events.ERROR, {
  16578. type: ErrorTypes.MUX_ERROR,
  16579. details: ErrorDetails.REMUX_ALLOC_ERROR,
  16580. fatal: false,
  16581. error: err,
  16582. bytes: mdatSize,
  16583. reason: "fail allocating video mdat " + mdatSize
  16584. });
  16585. return;
  16586. }
  16587. var view = new DataView(mdat.buffer);
  16588. view.setUint32(0, mdatSize);
  16589. mdat.set(MP4.types.mdat, 4);
  16590. var stretchedLastFrame = false;
  16591. var minDtsDelta = Number.POSITIVE_INFINITY;
  16592. var minPtsDelta = Number.POSITIVE_INFINITY;
  16593. var maxDtsDelta = Number.NEGATIVE_INFINITY;
  16594. var maxPtsDelta = Number.NEGATIVE_INFINITY;
  16595. for (var _i3 = 0; _i3 < nbSamples; _i3++) {
  16596. var _VideoSample = inputSamples[_i3];
  16597. var VideoSampleUnits = _VideoSample.units;
  16598. var mp4SampleLength = 0;
  16599. // convert NALU bitstream to MP4 format (prepend NALU with size field)
  16600. for (var _j = 0, _nbUnits = VideoSampleUnits.length; _j < _nbUnits; _j++) {
  16601. var unit = VideoSampleUnits[_j];
  16602. var unitData = unit.data;
  16603. var unitDataLen = unit.data.byteLength;
  16604. view.setUint32(offset, unitDataLen);
  16605. offset += 4;
  16606. mdat.set(unitData, offset);
  16607. offset += unitDataLen;
  16608. mp4SampleLength += 4 + unitDataLen;
  16609. }
  16610. // expected sample duration is the Decoding Timestamp diff of consecutive samples
  16611. var ptsDelta = void 0;
  16612. if (_i3 < nbSamples - 1) {
  16613. mp4SampleDuration = inputSamples[_i3 + 1].dts - _VideoSample.dts;
  16614. ptsDelta = inputSamples[_i3 + 1].pts - _VideoSample.pts;
  16615. } else {
  16616. var config = this.config;
  16617. var lastFrameDuration = _i3 > 0 ? _VideoSample.dts - inputSamples[_i3 - 1].dts : averageSampleDuration;
  16618. ptsDelta = _i3 > 0 ? _VideoSample.pts - inputSamples[_i3 - 1].pts : averageSampleDuration;
  16619. if (config.stretchShortVideoTrack && this.nextAudioPts !== null) {
  16620. // In some cases, a segment's audio track duration may exceed the video track duration.
  16621. // Since we've already remuxed audio, and we know how long the audio track is, we look to
  16622. // see if the delta to the next segment is longer than maxBufferHole.
  16623. // If so, playback would potentially get stuck, so we artificially inflate
  16624. // the duration of the last frame to minimize any potential gap between segments.
  16625. var gapTolerance = Math.floor(config.maxBufferHole * timeScale);
  16626. var deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioPts) - _VideoSample.pts;
  16627. if (deltaToFrameEnd > gapTolerance) {
  16628. // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video
  16629. // frame overlap. maxBufferHole should be >> lastFrameDuration anyway.
  16630. mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
  16631. if (mp4SampleDuration < 0) {
  16632. mp4SampleDuration = lastFrameDuration;
  16633. } else {
  16634. stretchedLastFrame = true;
  16635. }
  16636. logger.log("[mp4-remuxer]: It is approximately " + deltaToFrameEnd / 90 + " ms to the next segment; using duration " + mp4SampleDuration / 90 + " ms for the last video frame.");
  16637. } else {
  16638. mp4SampleDuration = lastFrameDuration;
  16639. }
  16640. } else {
  16641. mp4SampleDuration = lastFrameDuration;
  16642. }
  16643. }
  16644. var compositionTimeOffset = Math.round(_VideoSample.pts - _VideoSample.dts);
  16645. minDtsDelta = Math.min(minDtsDelta, mp4SampleDuration);
  16646. maxDtsDelta = Math.max(maxDtsDelta, mp4SampleDuration);
  16647. minPtsDelta = Math.min(minPtsDelta, ptsDelta);
  16648. maxPtsDelta = Math.max(maxPtsDelta, ptsDelta);
  16649. outputSamples.push(new Mp4Sample(_VideoSample.key, mp4SampleDuration, mp4SampleLength, compositionTimeOffset));
  16650. }
  16651. if (outputSamples.length) {
  16652. if (chromeVersion) {
  16653. if (chromeVersion < 70) {
  16654. // Chrome workaround, mark first sample as being a Random Access Point (keyframe) to avoid sourcebuffer append issue
  16655. // https://code.google.com/p/chromium/issues/detail?id=229412
  16656. var flags = outputSamples[0].flags;
  16657. flags.dependsOn = 2;
  16658. flags.isNonSync = 0;
  16659. }
  16660. } else if (safariWebkitVersion) {
  16661. // Fix for "CNN special report, with CC" in test-streams (Safari browser only)
  16662. // Ignore DTS when frame durations are irregular. Safari MSE does not handle this leading to gaps.
  16663. if (maxPtsDelta - minPtsDelta < maxDtsDelta - minDtsDelta && averageSampleDuration / maxDtsDelta < 0.025 && outputSamples[0].cts === 0) {
  16664. logger.warn('Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.');
  16665. var dts = firstDTS;
  16666. for (var _i4 = 0, len = outputSamples.length; _i4 < len; _i4++) {
  16667. var nextDts = dts + outputSamples[_i4].duration;
  16668. var _pts = dts + outputSamples[_i4].cts;
  16669. if (_i4 < len - 1) {
  16670. var nextPts = nextDts + outputSamples[_i4 + 1].cts;
  16671. outputSamples[_i4].duration = nextPts - _pts;
  16672. } else {
  16673. outputSamples[_i4].duration = _i4 ? outputSamples[_i4 - 1].duration : averageSampleDuration;
  16674. }
  16675. outputSamples[_i4].cts = 0;
  16676. dts = nextDts;
  16677. }
  16678. }
  16679. }
  16680. }
  16681. // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)
  16682. mp4SampleDuration = stretchedLastFrame || !mp4SampleDuration ? averageSampleDuration : mp4SampleDuration;
  16683. this.nextAvcDts = nextAvcDts = lastDTS + mp4SampleDuration;
  16684. this.videoSampleDuration = mp4SampleDuration;
  16685. this.isVideoContiguous = true;
  16686. var moof = MP4.moof(track.sequenceNumber++, firstDTS, _extends({}, track, {
  16687. samples: outputSamples
  16688. }));
  16689. var type = 'video';
  16690. var data = {
  16691. data1: moof,
  16692. data2: mdat,
  16693. startPTS: minPTS / timeScale,
  16694. endPTS: (maxPTS + mp4SampleDuration) / timeScale,
  16695. startDTS: firstDTS / timeScale,
  16696. endDTS: nextAvcDts / timeScale,
  16697. type: type,
  16698. hasAudio: false,
  16699. hasVideo: true,
  16700. nb: outputSamples.length,
  16701. dropped: track.dropped
  16702. };
  16703. track.samples = [];
  16704. track.dropped = 0;
  16705. return data;
  16706. };
  16707. _proto.getSamplesPerFrame = function getSamplesPerFrame(track) {
  16708. switch (track.segmentCodec) {
  16709. case 'mp3':
  16710. return MPEG_AUDIO_SAMPLE_PER_FRAME;
  16711. case 'ac3':
  16712. return AC3_SAMPLES_PER_FRAME;
  16713. default:
  16714. return AAC_SAMPLES_PER_FRAME;
  16715. }
  16716. };
  16717. _proto.remuxAudio = function remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, videoTimeOffset) {
  16718. var inputTimeScale = track.inputTimeScale;
  16719. var mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
  16720. var scaleFactor = inputTimeScale / mp4timeScale;
  16721. var mp4SampleDuration = this.getSamplesPerFrame(track);
  16722. var inputSampleDuration = mp4SampleDuration * scaleFactor;
  16723. var initPTS = this._initPTS;
  16724. var rawMPEG = track.segmentCodec === 'mp3' && this.typeSupported.mpeg;
  16725. var outputSamples = [];
  16726. var alignedWithVideo = videoTimeOffset !== undefined;
  16727. var inputSamples = track.samples;
  16728. var offset = rawMPEG ? 0 : 8;
  16729. var nextAudioPts = this.nextAudioPts || -1;
  16730. // window.audioSamples ? window.audioSamples.push(inputSamples.map(s => s.pts)) : (window.audioSamples = [inputSamples.map(s => s.pts)]);
  16731. // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),
  16732. // for sake of clarity:
  16733. // consecutive fragments are frags with
  16734. // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
  16735. // - less than 20 audio frames distance
  16736. // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
  16737. // this helps ensuring audio continuity
  16738. // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame
  16739. var timeOffsetMpegTS = timeOffset * inputTimeScale;
  16740. var initTime = initPTS.baseTime * inputTimeScale / initPTS.timescale;
  16741. this.isAudioContiguous = contiguous = contiguous || inputSamples.length && nextAudioPts > 0 && (accurateTimeOffset && Math.abs(timeOffsetMpegTS - nextAudioPts) < 9000 || Math.abs(normalizePts(inputSamples[0].pts - initTime, timeOffsetMpegTS) - nextAudioPts) < 20 * inputSampleDuration);
  16742. // compute normalized PTS
  16743. inputSamples.forEach(function (sample) {
  16744. sample.pts = normalizePts(sample.pts - initTime, timeOffsetMpegTS);
  16745. });
  16746. if (!contiguous || nextAudioPts < 0) {
  16747. // filter out sample with negative PTS that are not playable anyway
  16748. // if we don't remove these negative samples, they will shift all audio samples forward.
  16749. // leading to audio overlap between current / next fragment
  16750. inputSamples = inputSamples.filter(function (sample) {
  16751. return sample.pts >= 0;
  16752. });
  16753. // in case all samples have negative PTS, and have been filtered out, return now
  16754. if (!inputSamples.length) {
  16755. return;
  16756. }
  16757. if (videoTimeOffset === 0) {
  16758. // Set the start to 0 to match video so that start gaps larger than inputSampleDuration are filled with silence
  16759. nextAudioPts = 0;
  16760. } else if (accurateTimeOffset && !alignedWithVideo) {
  16761. // When not seeking, not live, and LevelDetails.PTSKnown, use fragment start as predicted next audio PTS
  16762. nextAudioPts = Math.max(0, timeOffsetMpegTS);
  16763. } else {
  16764. // if frags are not contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS
  16765. nextAudioPts = inputSamples[0].pts;
  16766. }
  16767. }
  16768. // If the audio track is missing samples, the frames seem to get "left-shifted" within the
  16769. // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.
  16770. // In an effort to prevent this from happening, we inject frames here where there are gaps.
  16771. // When possible, we inject a silent frame; when that's not possible, we duplicate the last
  16772. // frame.
  16773. if (track.segmentCodec === 'aac') {
  16774. var maxAudioFramesDrift = this.config.maxAudioFramesDrift;
  16775. for (var i = 0, nextPts = nextAudioPts; i < inputSamples.length; i++) {
  16776. // First, let's see how far off this frame is from where we expect it to be
  16777. var sample = inputSamples[i];
  16778. var pts = sample.pts;
  16779. var delta = pts - nextPts;
  16780. var duration = Math.abs(1000 * delta / inputTimeScale);
  16781. // When remuxing with video, if we're overlapping by more than a duration, drop this sample to stay in sync
  16782. if (delta <= -maxAudioFramesDrift * inputSampleDuration && alignedWithVideo) {
  16783. if (i === 0) {
  16784. logger.warn("Audio frame @ " + (pts / inputTimeScale).toFixed(3) + "s overlaps nextAudioPts by " + Math.round(1000 * delta / inputTimeScale) + " ms.");
  16785. this.nextAudioPts = nextAudioPts = nextPts = pts;
  16786. }
  16787. } // eslint-disable-line brace-style
  16788. // Insert missing frames if:
  16789. // 1: We're more than maxAudioFramesDrift frame away
  16790. // 2: Not more than MAX_SILENT_FRAME_DURATION away
  16791. // 3: currentTime (aka nextPtsNorm) is not 0
  16792. // 4: remuxing with video (videoTimeOffset !== undefined)
  16793. else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && alignedWithVideo) {
  16794. var missing = Math.round(delta / inputSampleDuration);
  16795. // Adjust nextPts so that silent samples are aligned with media pts. This will prevent media samples from
  16796. // later being shifted if nextPts is based on timeOffset and delta is not a multiple of inputSampleDuration.
  16797. nextPts = pts - missing * inputSampleDuration;
  16798. if (nextPts < 0) {
  16799. missing--;
  16800. nextPts += inputSampleDuration;
  16801. }
  16802. if (i === 0) {
  16803. this.nextAudioPts = nextAudioPts = nextPts;
  16804. }
  16805. logger.warn("[mp4-remuxer]: Injecting " + missing + " audio frame @ " + (nextPts / inputTimeScale).toFixed(3) + "s due to " + Math.round(1000 * delta / inputTimeScale) + " ms gap.");
  16806. for (var j = 0; j < missing; j++) {
  16807. var newStamp = Math.max(nextPts, 0);
  16808. var fillFrame = AAC.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  16809. if (!fillFrame) {
  16810. logger.log('[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead.');
  16811. fillFrame = sample.unit.subarray();
  16812. }
  16813. inputSamples.splice(i, 0, {
  16814. unit: fillFrame,
  16815. pts: newStamp
  16816. });
  16817. nextPts += inputSampleDuration;
  16818. i++;
  16819. }
  16820. }
  16821. sample.pts = nextPts;
  16822. nextPts += inputSampleDuration;
  16823. }
  16824. }
  16825. var firstPTS = null;
  16826. var lastPTS = null;
  16827. var mdat;
  16828. var mdatSize = 0;
  16829. var sampleLength = inputSamples.length;
  16830. while (sampleLength--) {
  16831. mdatSize += inputSamples[sampleLength].unit.byteLength;
  16832. }
  16833. for (var _j2 = 0, _nbSamples = inputSamples.length; _j2 < _nbSamples; _j2++) {
  16834. var audioSample = inputSamples[_j2];
  16835. var unit = audioSample.unit;
  16836. var _pts2 = audioSample.pts;
  16837. if (lastPTS !== null) {
  16838. // If we have more than one sample, set the duration of the sample to the "real" duration; the PTS diff with
  16839. // the previous sample
  16840. var prevSample = outputSamples[_j2 - 1];
  16841. prevSample.duration = Math.round((_pts2 - lastPTS) / scaleFactor);
  16842. } else {
  16843. if (contiguous && track.segmentCodec === 'aac') {
  16844. // set PTS/DTS to expected PTS/DTS
  16845. _pts2 = nextAudioPts;
  16846. }
  16847. // remember first PTS of our audioSamples
  16848. firstPTS = _pts2;
  16849. if (mdatSize > 0) {
  16850. /* concatenate the audio data and construct the mdat in place
  16851. (need 8 more bytes to fill length and mdat type) */
  16852. mdatSize += offset;
  16853. try {
  16854. mdat = new Uint8Array(mdatSize);
  16855. } catch (err) {
  16856. this.observer.emit(Events.ERROR, Events.ERROR, {
  16857. type: ErrorTypes.MUX_ERROR,
  16858. details: ErrorDetails.REMUX_ALLOC_ERROR,
  16859. fatal: false,
  16860. error: err,
  16861. bytes: mdatSize,
  16862. reason: "fail allocating audio mdat " + mdatSize
  16863. });
  16864. return;
  16865. }
  16866. if (!rawMPEG) {
  16867. var view = new DataView(mdat.buffer);
  16868. view.setUint32(0, mdatSize);
  16869. mdat.set(MP4.types.mdat, 4);
  16870. }
  16871. } else {
  16872. // no audio samples
  16873. return;
  16874. }
  16875. }
  16876. mdat.set(unit, offset);
  16877. var unitLen = unit.byteLength;
  16878. offset += unitLen;
  16879. // Default the sample's duration to the computed mp4SampleDuration, which will either be 1024 for AAC or 1152 for MPEG
  16880. // In the case that we have 1 sample, this will be the duration. If we have more than one sample, the duration
  16881. // becomes the PTS diff with the previous sample
  16882. outputSamples.push(new Mp4Sample(true, mp4SampleDuration, unitLen, 0));
  16883. lastPTS = _pts2;
  16884. }
  16885. // We could end up with no audio samples if all input samples were overlapping with the previously remuxed ones
  16886. var nbSamples = outputSamples.length;
  16887. if (!nbSamples) {
  16888. return;
  16889. }
  16890. // The next audio sample PTS should be equal to last sample PTS + duration
  16891. var lastSample = outputSamples[outputSamples.length - 1];
  16892. this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSample.duration;
  16893. // Set the track samples from inputSamples to outputSamples before remuxing
  16894. var moof = rawMPEG ? new Uint8Array(0) : MP4.moof(track.sequenceNumber++, firstPTS / scaleFactor, _extends({}, track, {
  16895. samples: outputSamples
  16896. }));
  16897. // Clear the track samples. This also clears the samples array in the demuxer, since the reference is shared
  16898. track.samples = [];
  16899. var start = firstPTS / inputTimeScale;
  16900. var end = nextAudioPts / inputTimeScale;
  16901. var type = 'audio';
  16902. var audioData = {
  16903. data1: moof,
  16904. data2: mdat,
  16905. startPTS: start,
  16906. endPTS: end,
  16907. startDTS: start,
  16908. endDTS: end,
  16909. type: type,
  16910. hasAudio: true,
  16911. hasVideo: false,
  16912. nb: nbSamples
  16913. };
  16914. this.isAudioContiguous = true;
  16915. return audioData;
  16916. };
  16917. _proto.remuxEmptyAudio = function remuxEmptyAudio(track, timeOffset, contiguous, videoData) {
  16918. var inputTimeScale = track.inputTimeScale;
  16919. var mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
  16920. var scaleFactor = inputTimeScale / mp4timeScale;
  16921. var nextAudioPts = this.nextAudioPts;
  16922. // sync with video's timestamp
  16923. var initDTS = this._initDTS;
  16924. var init90kHz = initDTS.baseTime * 90000 / initDTS.timescale;
  16925. var startDTS = (nextAudioPts !== null ? nextAudioPts : videoData.startDTS * inputTimeScale) + init90kHz;
  16926. var endDTS = videoData.endDTS * inputTimeScale + init90kHz;
  16927. // one sample's duration value
  16928. var frameDuration = scaleFactor * AAC_SAMPLES_PER_FRAME;
  16929. // samples count of this segment's duration
  16930. var nbSamples = Math.ceil((endDTS - startDTS) / frameDuration);
  16931. // silent frame
  16932. var silentFrame = AAC.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  16933. logger.warn('[mp4-remuxer]: remux empty Audio');
  16934. // Can't remux if we can't generate a silent frame...
  16935. if (!silentFrame) {
  16936. logger.trace('[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec');
  16937. return;
  16938. }
  16939. var samples = [];
  16940. for (var i = 0; i < nbSamples; i++) {
  16941. var stamp = startDTS + i * frameDuration;
  16942. samples.push({
  16943. unit: silentFrame,
  16944. pts: stamp,
  16945. dts: stamp
  16946. });
  16947. }
  16948. track.samples = samples;
  16949. return this.remuxAudio(track, timeOffset, contiguous, false);
  16950. };
  16951. return MP4Remuxer;
  16952. }();
  16953. function normalizePts(value, reference) {
  16954. var offset;
  16955. if (reference === null) {
  16956. return value;
  16957. }
  16958. if (reference < value) {
  16959. // - 2^33
  16960. offset = -8589934592;
  16961. } else {
  16962. // + 2^33
  16963. offset = 8589934592;
  16964. }
  16965. /* PTS is 33bit (from 0 to 2^33 -1)
  16966. if diff between value and reference is bigger than half of the amplitude (2^32) then it means that
  16967. PTS looping occured. fill the gap */
  16968. while (Math.abs(value - reference) > 4294967296) {
  16969. value += offset;
  16970. }
  16971. return value;
  16972. }
  16973. function findKeyframeIndex(samples) {
  16974. for (var i = 0; i < samples.length; i++) {
  16975. if (samples[i].key) {
  16976. return i;
  16977. }
  16978. }
  16979. return -1;
  16980. }
  16981. function flushTextTrackMetadataCueSamples(track, timeOffset, initPTS, initDTS) {
  16982. var length = track.samples.length;
  16983. if (!length) {
  16984. return;
  16985. }
  16986. var inputTimeScale = track.inputTimeScale;
  16987. for (var index = 0; index < length; index++) {
  16988. var sample = track.samples[index];
  16989. // setting id3 pts, dts to relative time
  16990. // using this._initPTS and this._initDTS to calculate relative time
  16991. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  16992. sample.dts = normalizePts(sample.dts - initDTS.baseTime * inputTimeScale / initDTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  16993. }
  16994. var samples = track.samples;
  16995. track.samples = [];
  16996. return {
  16997. samples: samples
  16998. };
  16999. }
  17000. function flushTextTrackUserdataCueSamples(track, timeOffset, initPTS) {
  17001. var length = track.samples.length;
  17002. if (!length) {
  17003. return;
  17004. }
  17005. var inputTimeScale = track.inputTimeScale;
  17006. for (var index = 0; index < length; index++) {
  17007. var sample = track.samples[index];
  17008. // setting text pts, dts to relative time
  17009. // using this._initPTS and this._initDTS to calculate relative time
  17010. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  17011. }
  17012. track.samples.sort(function (a, b) {
  17013. return a.pts - b.pts;
  17014. });
  17015. var samples = track.samples;
  17016. track.samples = [];
  17017. return {
  17018. samples: samples
  17019. };
  17020. }
  17021. var Mp4Sample = function Mp4Sample(isKeyframe, duration, size, cts) {
  17022. this.size = void 0;
  17023. this.duration = void 0;
  17024. this.cts = void 0;
  17025. this.flags = void 0;
  17026. this.duration = duration;
  17027. this.size = size;
  17028. this.cts = cts;
  17029. this.flags = {
  17030. isLeading: 0,
  17031. isDependedOn: 0,
  17032. hasRedundancy: 0,
  17033. degradPrio: 0,
  17034. dependsOn: isKeyframe ? 2 : 1,
  17035. isNonSync: isKeyframe ? 0 : 1
  17036. };
  17037. };
  17038. var PassThroughRemuxer = /*#__PURE__*/function () {
  17039. function PassThroughRemuxer() {
  17040. this.emitInitSegment = false;
  17041. this.audioCodec = void 0;
  17042. this.videoCodec = void 0;
  17043. this.initData = void 0;
  17044. this.initPTS = null;
  17045. this.initTracks = void 0;
  17046. this.lastEndTime = null;
  17047. }
  17048. var _proto = PassThroughRemuxer.prototype;
  17049. _proto.destroy = function destroy() {};
  17050. _proto.resetTimeStamp = function resetTimeStamp(defaultInitPTS) {
  17051. this.initPTS = defaultInitPTS;
  17052. this.lastEndTime = null;
  17053. };
  17054. _proto.resetNextTimestamp = function resetNextTimestamp() {
  17055. this.lastEndTime = null;
  17056. };
  17057. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, decryptdata) {
  17058. this.audioCodec = audioCodec;
  17059. this.videoCodec = videoCodec;
  17060. this.generateInitSegment(patchEncyptionData(initSegment, decryptdata));
  17061. this.emitInitSegment = true;
  17062. };
  17063. _proto.generateInitSegment = function generateInitSegment(initSegment) {
  17064. var audioCodec = this.audioCodec,
  17065. videoCodec = this.videoCodec;
  17066. if (!(initSegment != null && initSegment.byteLength)) {
  17067. this.initTracks = undefined;
  17068. this.initData = undefined;
  17069. return;
  17070. }
  17071. var initData = this.initData = parseInitSegment(initSegment);
  17072. // Get codec from initSegment or fallback to default
  17073. if (initData.audio) {
  17074. audioCodec = getParsedTrackCodec(initData.audio, ElementaryStreamTypes.AUDIO);
  17075. }
  17076. if (initData.video) {
  17077. videoCodec = getParsedTrackCodec(initData.video, ElementaryStreamTypes.VIDEO);
  17078. }
  17079. var tracks = {};
  17080. if (initData.audio && initData.video) {
  17081. tracks.audiovideo = {
  17082. container: 'video/mp4',
  17083. codec: audioCodec + ',' + videoCodec,
  17084. initSegment: initSegment,
  17085. id: 'main'
  17086. };
  17087. } else if (initData.audio) {
  17088. tracks.audio = {
  17089. container: 'audio/mp4',
  17090. codec: audioCodec,
  17091. initSegment: initSegment,
  17092. id: 'audio'
  17093. };
  17094. } else if (initData.video) {
  17095. tracks.video = {
  17096. container: 'video/mp4',
  17097. codec: videoCodec,
  17098. initSegment: initSegment,
  17099. id: 'main'
  17100. };
  17101. } else {
  17102. logger.warn('[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes.');
  17103. }
  17104. this.initTracks = tracks;
  17105. };
  17106. _proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset) {
  17107. var _initData, _initData2;
  17108. var initPTS = this.initPTS,
  17109. lastEndTime = this.lastEndTime;
  17110. var result = {
  17111. audio: undefined,
  17112. video: undefined,
  17113. text: textTrack,
  17114. id3: id3Track,
  17115. initSegment: undefined
  17116. };
  17117. // If we haven't yet set a lastEndDTS, or it was reset, set it to the provided timeOffset. We want to use the
  17118. // lastEndDTS over timeOffset whenever possible; during progressive playback, the media source will not update
  17119. // the media duration (which is what timeOffset is provided as) before we need to process the next chunk.
  17120. if (!isFiniteNumber(lastEndTime)) {
  17121. lastEndTime = this.lastEndTime = timeOffset || 0;
  17122. }
  17123. // The binary segment data is added to the videoTrack in the mp4demuxer. We don't check to see if the data is only
  17124. // audio or video (or both); adding it to video was an arbitrary choice.
  17125. var data = videoTrack.samples;
  17126. if (!(data != null && data.length)) {
  17127. return result;
  17128. }
  17129. var initSegment = {
  17130. initPTS: undefined,
  17131. timescale: 1
  17132. };
  17133. var initData = this.initData;
  17134. if (!((_initData = initData) != null && _initData.length)) {
  17135. this.generateInitSegment(data);
  17136. initData = this.initData;
  17137. }
  17138. if (!((_initData2 = initData) != null && _initData2.length)) {
  17139. // We can't remux if the initSegment could not be generated
  17140. logger.warn('[passthrough-remuxer.ts]: Failed to generate initSegment.');
  17141. return result;
  17142. }
  17143. if (this.emitInitSegment) {
  17144. initSegment.tracks = this.initTracks;
  17145. this.emitInitSegment = false;
  17146. }
  17147. var duration = getDuration(data, initData);
  17148. var startDTS = getStartDTS(initData, data);
  17149. var decodeTime = startDTS === null ? timeOffset : startDTS;
  17150. if (isInvalidInitPts(initPTS, decodeTime, timeOffset, duration) || initSegment.timescale !== initPTS.timescale && accurateTimeOffset) {
  17151. initSegment.initPTS = decodeTime - timeOffset;
  17152. if (initPTS && initPTS.timescale === 1) {
  17153. logger.warn("Adjusting initPTS by " + (initSegment.initPTS - initPTS.baseTime));
  17154. }
  17155. this.initPTS = initPTS = {
  17156. baseTime: initSegment.initPTS,
  17157. timescale: 1
  17158. };
  17159. }
  17160. var startTime = audioTrack ? decodeTime - initPTS.baseTime / initPTS.timescale : lastEndTime;
  17161. var endTime = startTime + duration;
  17162. offsetStartDTS(initData, data, initPTS.baseTime / initPTS.timescale);
  17163. if (duration > 0) {
  17164. this.lastEndTime = endTime;
  17165. } else {
  17166. logger.warn('Duration parsed from mp4 should be greater than zero');
  17167. this.resetNextTimestamp();
  17168. }
  17169. var hasAudio = !!initData.audio;
  17170. var hasVideo = !!initData.video;
  17171. var type = '';
  17172. if (hasAudio) {
  17173. type += 'audio';
  17174. }
  17175. if (hasVideo) {
  17176. type += 'video';
  17177. }
  17178. var track = {
  17179. data1: data,
  17180. startPTS: startTime,
  17181. startDTS: startTime,
  17182. endPTS: endTime,
  17183. endDTS: endTime,
  17184. type: type,
  17185. hasAudio: hasAudio,
  17186. hasVideo: hasVideo,
  17187. nb: 1,
  17188. dropped: 0
  17189. };
  17190. result.audio = track.type === 'audio' ? track : undefined;
  17191. result.video = track.type !== 'audio' ? track : undefined;
  17192. result.initSegment = initSegment;
  17193. result.id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, initPTS, initPTS);
  17194. if (textTrack.samples.length) {
  17195. result.text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, initPTS);
  17196. }
  17197. return result;
  17198. };
  17199. return PassThroughRemuxer;
  17200. }();
  17201. function isInvalidInitPts(initPTS, startDTS, timeOffset, duration) {
  17202. if (initPTS === null) {
  17203. return true;
  17204. }
  17205. // InitPTS is invalid when distance from program would be more than segment duration or a minimum of one second
  17206. var minDuration = Math.max(duration, 1);
  17207. var startTime = startDTS - initPTS.baseTime / initPTS.timescale;
  17208. return Math.abs(startTime - timeOffset) > minDuration;
  17209. }
  17210. function getParsedTrackCodec(track, type) {
  17211. var parsedCodec = track == null ? void 0 : track.codec;
  17212. if (parsedCodec && parsedCodec.length > 4) {
  17213. return parsedCodec;
  17214. }
  17215. if (type === ElementaryStreamTypes.AUDIO) {
  17216. if (parsedCodec === 'ec-3' || parsedCodec === 'ac-3' || parsedCodec === 'alac') {
  17217. return parsedCodec;
  17218. }
  17219. if (parsedCodec === 'fLaC' || parsedCodec === 'Opus') {
  17220. // Opting not to get `preferManagedMediaSource` from player config for isSupported() check for simplicity
  17221. var preferManagedMediaSource = false;
  17222. return getCodecCompatibleName(parsedCodec, preferManagedMediaSource);
  17223. }
  17224. var result = 'mp4a.40.5';
  17225. logger.info("Parsed audio codec \"" + parsedCodec + "\" or audio object type not handled. Using \"" + result + "\"");
  17226. return result;
  17227. }
  17228. // Provide defaults based on codec type
  17229. // This allows for some playback of some fmp4 playlists without CODECS defined in manifest
  17230. logger.warn("Unhandled video codec \"" + parsedCodec + "\"");
  17231. if (parsedCodec === 'hvc1' || parsedCodec === 'hev1') {
  17232. return 'hvc1.1.6.L120.90';
  17233. }
  17234. if (parsedCodec === 'av01') {
  17235. return 'av01.0.04M.08';
  17236. }
  17237. return 'avc1.42e01e';
  17238. }
  17239. /** returns `undefined` is `self` is missing, e.g. in node */
  17240. var optionalSelf = typeof self !== 'undefined' ? self : undefined;
  17241. var now;
  17242. // performance.now() not available on WebWorker, at least on Safari Desktop
  17243. try {
  17244. now = self.performance.now.bind(self.performance);
  17245. } catch (err) {
  17246. logger.debug('Unable to use Performance API on this environment');
  17247. now = optionalSelf == null ? void 0 : optionalSelf.Date.now;
  17248. }
  17249. var muxConfig = [{
  17250. demux: MP4Demuxer,
  17251. remux: PassThroughRemuxer
  17252. }, {
  17253. demux: TSDemuxer,
  17254. remux: MP4Remuxer
  17255. }, {
  17256. demux: AACDemuxer,
  17257. remux: MP4Remuxer
  17258. }, {
  17259. demux: MP3Demuxer,
  17260. remux: MP4Remuxer
  17261. }];
  17262. var Transmuxer = /*#__PURE__*/function () {
  17263. function Transmuxer(observer, typeSupported, config, vendor, id) {
  17264. this.async = false;
  17265. this.observer = void 0;
  17266. this.typeSupported = void 0;
  17267. this.config = void 0;
  17268. this.vendor = void 0;
  17269. this.id = void 0;
  17270. this.demuxer = void 0;
  17271. this.remuxer = void 0;
  17272. this.decrypter = void 0;
  17273. this.probe = void 0;
  17274. this.decryptionPromise = null;
  17275. this.transmuxConfig = void 0;
  17276. this.currentTransmuxState = void 0;
  17277. this.observer = observer;
  17278. this.typeSupported = typeSupported;
  17279. this.config = config;
  17280. this.vendor = vendor;
  17281. this.id = id;
  17282. }
  17283. var _proto = Transmuxer.prototype;
  17284. _proto.configure = function configure(transmuxConfig) {
  17285. this.transmuxConfig = transmuxConfig;
  17286. if (this.decrypter) {
  17287. this.decrypter.reset();
  17288. }
  17289. };
  17290. _proto.push = function push(data, decryptdata, chunkMeta, state) {
  17291. var _this = this;
  17292. var stats = chunkMeta.transmuxing;
  17293. stats.executeStart = now();
  17294. var uintData = new Uint8Array(data);
  17295. var currentTransmuxState = this.currentTransmuxState,
  17296. transmuxConfig = this.transmuxConfig;
  17297. if (state) {
  17298. this.currentTransmuxState = state;
  17299. }
  17300. var _ref = state || currentTransmuxState,
  17301. contiguous = _ref.contiguous,
  17302. discontinuity = _ref.discontinuity,
  17303. trackSwitch = _ref.trackSwitch,
  17304. accurateTimeOffset = _ref.accurateTimeOffset,
  17305. timeOffset = _ref.timeOffset,
  17306. initSegmentChange = _ref.initSegmentChange;
  17307. var audioCodec = transmuxConfig.audioCodec,
  17308. videoCodec = transmuxConfig.videoCodec,
  17309. defaultInitPts = transmuxConfig.defaultInitPts,
  17310. duration = transmuxConfig.duration,
  17311. initSegmentData = transmuxConfig.initSegmentData;
  17312. var keyData = getEncryptionType(uintData, decryptdata);
  17313. if (keyData && keyData.method === 'AES-128') {
  17314. var decrypter = this.getDecrypter();
  17315. // Software decryption is synchronous; webCrypto is not
  17316. if (decrypter.isSync()) {
  17317. // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
  17318. // data is handled in the flush() call
  17319. var decryptedData = decrypter.softwareDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer);
  17320. // For Low-Latency HLS Parts, decrypt in place, since part parsing is expected on push progress
  17321. var loadingParts = chunkMeta.part > -1;
  17322. if (loadingParts) {
  17323. decryptedData = decrypter.flush();
  17324. }
  17325. if (!decryptedData) {
  17326. stats.executeEnd = now();
  17327. return emptyResult(chunkMeta);
  17328. }
  17329. uintData = new Uint8Array(decryptedData);
  17330. } else {
  17331. this.decryptionPromise = decrypter.webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer).then(function (decryptedData) {
  17332. // Calling push here is important; if flush() is called while this is still resolving, this ensures that
  17333. // the decrypted data has been transmuxed
  17334. var result = _this.push(decryptedData, null, chunkMeta);
  17335. _this.decryptionPromise = null;
  17336. return result;
  17337. });
  17338. return this.decryptionPromise;
  17339. }
  17340. }
  17341. var resetMuxers = this.needsProbing(discontinuity, trackSwitch);
  17342. if (resetMuxers) {
  17343. var error = this.configureTransmuxer(uintData);
  17344. if (error) {
  17345. logger.warn("[transmuxer] " + error.message);
  17346. this.observer.emit(Events.ERROR, Events.ERROR, {
  17347. type: ErrorTypes.MEDIA_ERROR,
  17348. details: ErrorDetails.FRAG_PARSING_ERROR,
  17349. fatal: false,
  17350. error: error,
  17351. reason: error.message
  17352. });
  17353. stats.executeEnd = now();
  17354. return emptyResult(chunkMeta);
  17355. }
  17356. }
  17357. if (discontinuity || trackSwitch || initSegmentChange || resetMuxers) {
  17358. this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration, decryptdata);
  17359. }
  17360. if (discontinuity || initSegmentChange || resetMuxers) {
  17361. this.resetInitialTimestamp(defaultInitPts);
  17362. }
  17363. if (!contiguous) {
  17364. this.resetContiguity();
  17365. }
  17366. var result = this.transmux(uintData, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  17367. var currentState = this.currentTransmuxState;
  17368. currentState.contiguous = true;
  17369. currentState.discontinuity = false;
  17370. currentState.trackSwitch = false;
  17371. stats.executeEnd = now();
  17372. return result;
  17373. }
  17374. // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type)
  17375. ;
  17376. _proto.flush = function flush(chunkMeta) {
  17377. var _this2 = this;
  17378. var stats = chunkMeta.transmuxing;
  17379. stats.executeStart = now();
  17380. var decrypter = this.decrypter,
  17381. currentTransmuxState = this.currentTransmuxState,
  17382. decryptionPromise = this.decryptionPromise;
  17383. if (decryptionPromise) {
  17384. // Upon resolution, the decryption promise calls push() and returns its TransmuxerResult up the stack. Therefore
  17385. // only flushing is required for async decryption
  17386. return decryptionPromise.then(function () {
  17387. return _this2.flush(chunkMeta);
  17388. });
  17389. }
  17390. var transmuxResults = [];
  17391. var timeOffset = currentTransmuxState.timeOffset;
  17392. if (decrypter) {
  17393. // The decrypter may have data cached, which needs to be demuxed. In this case we'll have two TransmuxResults
  17394. // This happens in the case that we receive only 1 push call for a segment (either for non-progressive downloads,
  17395. // or for progressive downloads with small segments)
  17396. var decryptedData = decrypter.flush();
  17397. if (decryptedData) {
  17398. // Push always returns a TransmuxerResult if decryptdata is null
  17399. transmuxResults.push(this.push(decryptedData, null, chunkMeta));
  17400. }
  17401. }
  17402. var demuxer = this.demuxer,
  17403. remuxer = this.remuxer;
  17404. if (!demuxer || !remuxer) {
  17405. // If probing failed, then Hls.js has been given content its not able to handle
  17406. stats.executeEnd = now();
  17407. return [emptyResult(chunkMeta)];
  17408. }
  17409. var demuxResultOrPromise = demuxer.flush(timeOffset);
  17410. if (isPromise(demuxResultOrPromise)) {
  17411. // Decrypt final SAMPLE-AES samples
  17412. return demuxResultOrPromise.then(function (demuxResult) {
  17413. _this2.flushRemux(transmuxResults, demuxResult, chunkMeta);
  17414. return transmuxResults;
  17415. });
  17416. }
  17417. this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta);
  17418. return transmuxResults;
  17419. };
  17420. _proto.flushRemux = function flushRemux(transmuxResults, demuxResult, chunkMeta) {
  17421. var audioTrack = demuxResult.audioTrack,
  17422. videoTrack = demuxResult.videoTrack,
  17423. id3Track = demuxResult.id3Track,
  17424. textTrack = demuxResult.textTrack;
  17425. var _this$currentTransmux = this.currentTransmuxState,
  17426. accurateTimeOffset = _this$currentTransmux.accurateTimeOffset,
  17427. timeOffset = _this$currentTransmux.timeOffset;
  17428. logger.log("[transmuxer.ts]: Flushed fragment " + chunkMeta.sn + (chunkMeta.part > -1 ? ' p: ' + chunkMeta.part : '') + " of level " + chunkMeta.level);
  17429. var remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, true, this.id);
  17430. transmuxResults.push({
  17431. remuxResult: remuxResult,
  17432. chunkMeta: chunkMeta
  17433. });
  17434. chunkMeta.transmuxing.executeEnd = now();
  17435. };
  17436. _proto.resetInitialTimestamp = function resetInitialTimestamp(defaultInitPts) {
  17437. var demuxer = this.demuxer,
  17438. remuxer = this.remuxer;
  17439. if (!demuxer || !remuxer) {
  17440. return;
  17441. }
  17442. demuxer.resetTimeStamp(defaultInitPts);
  17443. remuxer.resetTimeStamp(defaultInitPts);
  17444. };
  17445. _proto.resetContiguity = function resetContiguity() {
  17446. var demuxer = this.demuxer,
  17447. remuxer = this.remuxer;
  17448. if (!demuxer || !remuxer) {
  17449. return;
  17450. }
  17451. demuxer.resetContiguity();
  17452. remuxer.resetNextTimestamp();
  17453. };
  17454. _proto.resetInitSegment = function resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration, decryptdata) {
  17455. var demuxer = this.demuxer,
  17456. remuxer = this.remuxer;
  17457. if (!demuxer || !remuxer) {
  17458. return;
  17459. }
  17460. demuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration);
  17461. remuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, decryptdata);
  17462. };
  17463. _proto.destroy = function destroy() {
  17464. if (this.demuxer) {
  17465. this.demuxer.destroy();
  17466. this.demuxer = undefined;
  17467. }
  17468. if (this.remuxer) {
  17469. this.remuxer.destroy();
  17470. this.remuxer = undefined;
  17471. }
  17472. };
  17473. _proto.transmux = function transmux(data, keyData, timeOffset, accurateTimeOffset, chunkMeta) {
  17474. var result;
  17475. if (keyData && keyData.method === 'SAMPLE-AES') {
  17476. result = this.transmuxSampleAes(data, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  17477. } else {
  17478. result = this.transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta);
  17479. }
  17480. return result;
  17481. };
  17482. _proto.transmuxUnencrypted = function transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta) {
  17483. var _demux = this.demuxer.demux(data, timeOffset, false, !this.config.progressive),
  17484. audioTrack = _demux.audioTrack,
  17485. videoTrack = _demux.videoTrack,
  17486. id3Track = _demux.id3Track,
  17487. textTrack = _demux.textTrack;
  17488. var remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, false, this.id);
  17489. return {
  17490. remuxResult: remuxResult,
  17491. chunkMeta: chunkMeta
  17492. };
  17493. };
  17494. _proto.transmuxSampleAes = function transmuxSampleAes(data, decryptData, timeOffset, accurateTimeOffset, chunkMeta) {
  17495. var _this3 = this;
  17496. return this.demuxer.demuxSampleAes(data, decryptData, timeOffset).then(function (demuxResult) {
  17497. var remuxResult = _this3.remuxer.remux(demuxResult.audioTrack, demuxResult.videoTrack, demuxResult.id3Track, demuxResult.textTrack, timeOffset, accurateTimeOffset, false, _this3.id);
  17498. return {
  17499. remuxResult: remuxResult,
  17500. chunkMeta: chunkMeta
  17501. };
  17502. });
  17503. };
  17504. _proto.configureTransmuxer = function configureTransmuxer(data) {
  17505. var config = this.config,
  17506. observer = this.observer,
  17507. typeSupported = this.typeSupported,
  17508. vendor = this.vendor;
  17509. // probe for content type
  17510. var mux;
  17511. for (var i = 0, len = muxConfig.length; i < len; i++) {
  17512. var _muxConfig$i$demux;
  17513. if ((_muxConfig$i$demux = muxConfig[i].demux) != null && _muxConfig$i$demux.probe(data)) {
  17514. mux = muxConfig[i];
  17515. break;
  17516. }
  17517. }
  17518. if (!mux) {
  17519. return new Error('Failed to find demuxer by probing fragment data');
  17520. }
  17521. // so let's check that current remuxer and demuxer are still valid
  17522. var demuxer = this.demuxer;
  17523. var remuxer = this.remuxer;
  17524. var Remuxer = mux.remux;
  17525. var Demuxer = mux.demux;
  17526. if (!remuxer || !(remuxer instanceof Remuxer)) {
  17527. this.remuxer = new Remuxer(observer, config, typeSupported, vendor);
  17528. }
  17529. if (!demuxer || !(demuxer instanceof Demuxer)) {
  17530. this.demuxer = new Demuxer(observer, config, typeSupported);
  17531. this.probe = Demuxer.probe;
  17532. }
  17533. };
  17534. _proto.needsProbing = function needsProbing(discontinuity, trackSwitch) {
  17535. // in case of continuity change, or track switch
  17536. // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)
  17537. return !this.demuxer || !this.remuxer || discontinuity || trackSwitch;
  17538. };
  17539. _proto.getDecrypter = function getDecrypter() {
  17540. var decrypter = this.decrypter;
  17541. if (!decrypter) {
  17542. decrypter = this.decrypter = new Decrypter(this.config);
  17543. }
  17544. return decrypter;
  17545. };
  17546. return Transmuxer;
  17547. }();
  17548. function getEncryptionType(data, decryptData) {
  17549. var encryptionType = null;
  17550. if (data.byteLength > 0 && (decryptData == null ? void 0 : decryptData.key) != null && decryptData.iv !== null && decryptData.method != null) {
  17551. encryptionType = decryptData;
  17552. }
  17553. return encryptionType;
  17554. }
  17555. var emptyResult = function emptyResult(chunkMeta) {
  17556. return {
  17557. remuxResult: {},
  17558. chunkMeta: chunkMeta
  17559. };
  17560. };
  17561. function isPromise(p) {
  17562. return 'then' in p && p.then instanceof Function;
  17563. }
  17564. var TransmuxConfig = function TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPts) {
  17565. this.audioCodec = void 0;
  17566. this.videoCodec = void 0;
  17567. this.initSegmentData = void 0;
  17568. this.duration = void 0;
  17569. this.defaultInitPts = void 0;
  17570. this.audioCodec = audioCodec;
  17571. this.videoCodec = videoCodec;
  17572. this.initSegmentData = initSegmentData;
  17573. this.duration = duration;
  17574. this.defaultInitPts = defaultInitPts || null;
  17575. };
  17576. var TransmuxState = function TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange) {
  17577. this.discontinuity = void 0;
  17578. this.contiguous = void 0;
  17579. this.accurateTimeOffset = void 0;
  17580. this.trackSwitch = void 0;
  17581. this.timeOffset = void 0;
  17582. this.initSegmentChange = void 0;
  17583. this.discontinuity = discontinuity;
  17584. this.contiguous = contiguous;
  17585. this.accurateTimeOffset = accurateTimeOffset;
  17586. this.trackSwitch = trackSwitch;
  17587. this.timeOffset = timeOffset;
  17588. this.initSegmentChange = initSegmentChange;
  17589. };
  17590. var eventemitter3 = {exports: {}};
  17591. (function (module) {
  17592. var has = Object.prototype.hasOwnProperty
  17593. , prefix = '~';
  17594. /**
  17595. * Constructor to create a storage for our `EE` objects.
  17596. * An `Events` instance is a plain object whose properties are event names.
  17597. *
  17598. * @constructor
  17599. * @private
  17600. */
  17601. function Events() {}
  17602. //
  17603. // We try to not inherit from `Object.prototype`. In some engines creating an
  17604. // instance in this way is faster than calling `Object.create(null)` directly.
  17605. // If `Object.create(null)` is not supported we prefix the event names with a
  17606. // character to make sure that the built-in object properties are not
  17607. // overridden or used as an attack vector.
  17608. //
  17609. if (Object.create) {
  17610. Events.prototype = Object.create(null);
  17611. //
  17612. // This hack is needed because the `__proto__` property is still inherited in
  17613. // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  17614. //
  17615. if (!new Events().__proto__) prefix = false;
  17616. }
  17617. /**
  17618. * Representation of a single event listener.
  17619. *
  17620. * @param {Function} fn The listener function.
  17621. * @param {*} context The context to invoke the listener with.
  17622. * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
  17623. * @constructor
  17624. * @private
  17625. */
  17626. function EE(fn, context, once) {
  17627. this.fn = fn;
  17628. this.context = context;
  17629. this.once = once || false;
  17630. }
  17631. /**
  17632. * Add a listener for a given event.
  17633. *
  17634. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  17635. * @param {(String|Symbol)} event The event name.
  17636. * @param {Function} fn The listener function.
  17637. * @param {*} context The context to invoke the listener with.
  17638. * @param {Boolean} once Specify if the listener is a one-time listener.
  17639. * @returns {EventEmitter}
  17640. * @private
  17641. */
  17642. function addListener(emitter, event, fn, context, once) {
  17643. if (typeof fn !== 'function') {
  17644. throw new TypeError('The listener must be a function');
  17645. }
  17646. var listener = new EE(fn, context || emitter, once)
  17647. , evt = prefix ? prefix + event : event;
  17648. if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
  17649. else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
  17650. else emitter._events[evt] = [emitter._events[evt], listener];
  17651. return emitter;
  17652. }
  17653. /**
  17654. * Clear event by name.
  17655. *
  17656. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  17657. * @param {(String|Symbol)} evt The Event name.
  17658. * @private
  17659. */
  17660. function clearEvent(emitter, evt) {
  17661. if (--emitter._eventsCount === 0) emitter._events = new Events();
  17662. else delete emitter._events[evt];
  17663. }
  17664. /**
  17665. * Minimal `EventEmitter` interface that is molded against the Node.js
  17666. * `EventEmitter` interface.
  17667. *
  17668. * @constructor
  17669. * @public
  17670. */
  17671. function EventEmitter() {
  17672. this._events = new Events();
  17673. this._eventsCount = 0;
  17674. }
  17675. /**
  17676. * Return an array listing the events for which the emitter has registered
  17677. * listeners.
  17678. *
  17679. * @returns {Array}
  17680. * @public
  17681. */
  17682. EventEmitter.prototype.eventNames = function eventNames() {
  17683. var names = []
  17684. , events
  17685. , name;
  17686. if (this._eventsCount === 0) return names;
  17687. for (name in (events = this._events)) {
  17688. if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
  17689. }
  17690. if (Object.getOwnPropertySymbols) {
  17691. return names.concat(Object.getOwnPropertySymbols(events));
  17692. }
  17693. return names;
  17694. };
  17695. /**
  17696. * Return the listeners registered for a given event.
  17697. *
  17698. * @param {(String|Symbol)} event The event name.
  17699. * @returns {Array} The registered listeners.
  17700. * @public
  17701. */
  17702. EventEmitter.prototype.listeners = function listeners(event) {
  17703. var evt = prefix ? prefix + event : event
  17704. , handlers = this._events[evt];
  17705. if (!handlers) return [];
  17706. if (handlers.fn) return [handlers.fn];
  17707. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  17708. ee[i] = handlers[i].fn;
  17709. }
  17710. return ee;
  17711. };
  17712. /**
  17713. * Return the number of listeners listening to a given event.
  17714. *
  17715. * @param {(String|Symbol)} event The event name.
  17716. * @returns {Number} The number of listeners.
  17717. * @public
  17718. */
  17719. EventEmitter.prototype.listenerCount = function listenerCount(event) {
  17720. var evt = prefix ? prefix + event : event
  17721. , listeners = this._events[evt];
  17722. if (!listeners) return 0;
  17723. if (listeners.fn) return 1;
  17724. return listeners.length;
  17725. };
  17726. /**
  17727. * Calls each of the listeners registered for a given event.
  17728. *
  17729. * @param {(String|Symbol)} event The event name.
  17730. * @returns {Boolean} `true` if the event had listeners, else `false`.
  17731. * @public
  17732. */
  17733. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  17734. var evt = prefix ? prefix + event : event;
  17735. if (!this._events[evt]) return false;
  17736. var listeners = this._events[evt]
  17737. , len = arguments.length
  17738. , args
  17739. , i;
  17740. if (listeners.fn) {
  17741. if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  17742. switch (len) {
  17743. case 1: return listeners.fn.call(listeners.context), true;
  17744. case 2: return listeners.fn.call(listeners.context, a1), true;
  17745. case 3: return listeners.fn.call(listeners.context, a1, a2), true;
  17746. case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
  17747. case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  17748. case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  17749. }
  17750. for (i = 1, args = new Array(len -1); i < len; i++) {
  17751. args[i - 1] = arguments[i];
  17752. }
  17753. listeners.fn.apply(listeners.context, args);
  17754. } else {
  17755. var length = listeners.length
  17756. , j;
  17757. for (i = 0; i < length; i++) {
  17758. if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  17759. switch (len) {
  17760. case 1: listeners[i].fn.call(listeners[i].context); break;
  17761. case 2: listeners[i].fn.call(listeners[i].context, a1); break;
  17762. case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
  17763. case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
  17764. default:
  17765. if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
  17766. args[j - 1] = arguments[j];
  17767. }
  17768. listeners[i].fn.apply(listeners[i].context, args);
  17769. }
  17770. }
  17771. }
  17772. return true;
  17773. };
  17774. /**
  17775. * Add a listener for a given event.
  17776. *
  17777. * @param {(String|Symbol)} event The event name.
  17778. * @param {Function} fn The listener function.
  17779. * @param {*} [context=this] The context to invoke the listener with.
  17780. * @returns {EventEmitter} `this`.
  17781. * @public
  17782. */
  17783. EventEmitter.prototype.on = function on(event, fn, context) {
  17784. return addListener(this, event, fn, context, false);
  17785. };
  17786. /**
  17787. * Add a one-time listener for a given event.
  17788. *
  17789. * @param {(String|Symbol)} event The event name.
  17790. * @param {Function} fn The listener function.
  17791. * @param {*} [context=this] The context to invoke the listener with.
  17792. * @returns {EventEmitter} `this`.
  17793. * @public
  17794. */
  17795. EventEmitter.prototype.once = function once(event, fn, context) {
  17796. return addListener(this, event, fn, context, true);
  17797. };
  17798. /**
  17799. * Remove the listeners of a given event.
  17800. *
  17801. * @param {(String|Symbol)} event The event name.
  17802. * @param {Function} fn Only remove the listeners that match this function.
  17803. * @param {*} context Only remove the listeners that have this context.
  17804. * @param {Boolean} once Only remove one-time listeners.
  17805. * @returns {EventEmitter} `this`.
  17806. * @public
  17807. */
  17808. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  17809. var evt = prefix ? prefix + event : event;
  17810. if (!this._events[evt]) return this;
  17811. if (!fn) {
  17812. clearEvent(this, evt);
  17813. return this;
  17814. }
  17815. var listeners = this._events[evt];
  17816. if (listeners.fn) {
  17817. if (
  17818. listeners.fn === fn &&
  17819. (!once || listeners.once) &&
  17820. (!context || listeners.context === context)
  17821. ) {
  17822. clearEvent(this, evt);
  17823. }
  17824. } else {
  17825. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  17826. if (
  17827. listeners[i].fn !== fn ||
  17828. (once && !listeners[i].once) ||
  17829. (context && listeners[i].context !== context)
  17830. ) {
  17831. events.push(listeners[i]);
  17832. }
  17833. }
  17834. //
  17835. // Reset the array, or remove it completely if we have no more listeners.
  17836. //
  17837. if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
  17838. else clearEvent(this, evt);
  17839. }
  17840. return this;
  17841. };
  17842. /**
  17843. * Remove all listeners, or those of the specified event.
  17844. *
  17845. * @param {(String|Symbol)} [event] The event name.
  17846. * @returns {EventEmitter} `this`.
  17847. * @public
  17848. */
  17849. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  17850. var evt;
  17851. if (event) {
  17852. evt = prefix ? prefix + event : event;
  17853. if (this._events[evt]) clearEvent(this, evt);
  17854. } else {
  17855. this._events = new Events();
  17856. this._eventsCount = 0;
  17857. }
  17858. return this;
  17859. };
  17860. //
  17861. // Alias methods names because people roll like that.
  17862. //
  17863. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  17864. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  17865. //
  17866. // Expose the prefix.
  17867. //
  17868. EventEmitter.prefixed = prefix;
  17869. //
  17870. // Allow `EventEmitter` to be imported as module namespace.
  17871. //
  17872. EventEmitter.EventEmitter = EventEmitter;
  17873. //
  17874. // Expose the module.
  17875. //
  17876. {
  17877. module.exports = EventEmitter;
  17878. }
  17879. } (eventemitter3));
  17880. var eventemitter3Exports = eventemitter3.exports;
  17881. var EventEmitter = /*@__PURE__*/getDefaultExportFromCjs(eventemitter3Exports);
  17882. if (typeof __IN_WORKER__ !== 'undefined' && __IN_WORKER__) {
  17883. startWorker(self);
  17884. }
  17885. function startWorker(self) {
  17886. var observer = new EventEmitter();
  17887. var forwardMessage = function forwardMessage(ev, data) {
  17888. self.postMessage({
  17889. event: ev,
  17890. data: data
  17891. });
  17892. };
  17893. // forward events to main thread
  17894. observer.on(Events.FRAG_DECRYPTED, forwardMessage);
  17895. observer.on(Events.ERROR, forwardMessage);
  17896. // forward logger events to main thread
  17897. var forwardWorkerLogs = function forwardWorkerLogs() {
  17898. var _loop = function _loop(logFn) {
  17899. var func = function func(message) {
  17900. forwardMessage('workerLog', {
  17901. logType: logFn,
  17902. message: message
  17903. });
  17904. };
  17905. logger[logFn] = func;
  17906. };
  17907. for (var logFn in logger) {
  17908. _loop(logFn);
  17909. }
  17910. };
  17911. self.addEventListener('message', function (ev) {
  17912. var data = ev.data;
  17913. switch (data.cmd) {
  17914. case 'init':
  17915. {
  17916. var config = JSON.parse(data.config);
  17917. self.transmuxer = new Transmuxer(observer, data.typeSupported, config, '', data.id);
  17918. enableLogs(config.debug, data.id);
  17919. forwardWorkerLogs();
  17920. forwardMessage('init', null);
  17921. break;
  17922. }
  17923. case 'configure':
  17924. {
  17925. self.transmuxer.configure(data.config);
  17926. break;
  17927. }
  17928. case 'demux':
  17929. {
  17930. var transmuxResult = self.transmuxer.push(data.data, data.decryptdata, data.chunkMeta, data.state);
  17931. if (isPromise(transmuxResult)) {
  17932. self.transmuxer.async = true;
  17933. transmuxResult.then(function (data) {
  17934. emitTransmuxComplete(self, data);
  17935. }).catch(function (error) {
  17936. forwardMessage(Events.ERROR, {
  17937. type: ErrorTypes.MEDIA_ERROR,
  17938. details: ErrorDetails.FRAG_PARSING_ERROR,
  17939. chunkMeta: data.chunkMeta,
  17940. fatal: false,
  17941. error: error,
  17942. err: error,
  17943. reason: "transmuxer-worker push error"
  17944. });
  17945. });
  17946. } else {
  17947. self.transmuxer.async = false;
  17948. emitTransmuxComplete(self, transmuxResult);
  17949. }
  17950. break;
  17951. }
  17952. case 'flush':
  17953. {
  17954. var id = data.chunkMeta;
  17955. var _transmuxResult = self.transmuxer.flush(id);
  17956. var asyncFlush = isPromise(_transmuxResult);
  17957. if (asyncFlush || self.transmuxer.async) {
  17958. if (!isPromise(_transmuxResult)) {
  17959. _transmuxResult = Promise.resolve(_transmuxResult);
  17960. }
  17961. _transmuxResult.then(function (results) {
  17962. handleFlushResult(self, results, id);
  17963. }).catch(function (error) {
  17964. forwardMessage(Events.ERROR, {
  17965. type: ErrorTypes.MEDIA_ERROR,
  17966. details: ErrorDetails.FRAG_PARSING_ERROR,
  17967. chunkMeta: data.chunkMeta,
  17968. fatal: false,
  17969. error: error,
  17970. err: error,
  17971. reason: "transmuxer-worker flush error"
  17972. });
  17973. });
  17974. } else {
  17975. handleFlushResult(self, _transmuxResult, id);
  17976. }
  17977. break;
  17978. }
  17979. }
  17980. });
  17981. }
  17982. function emitTransmuxComplete(self, transmuxResult) {
  17983. if (isEmptyResult(transmuxResult.remuxResult)) {
  17984. return false;
  17985. }
  17986. var transferable = [];
  17987. var _transmuxResult$remux = transmuxResult.remuxResult,
  17988. audio = _transmuxResult$remux.audio,
  17989. video = _transmuxResult$remux.video;
  17990. if (audio) {
  17991. addToTransferable(transferable, audio);
  17992. }
  17993. if (video) {
  17994. addToTransferable(transferable, video);
  17995. }
  17996. self.postMessage({
  17997. event: 'transmuxComplete',
  17998. data: transmuxResult
  17999. }, transferable);
  18000. return true;
  18001. }
  18002. // Converts data to a transferable object https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast)
  18003. // in order to minimize message passing overhead
  18004. function addToTransferable(transferable, track) {
  18005. if (track.data1) {
  18006. transferable.push(track.data1.buffer);
  18007. }
  18008. if (track.data2) {
  18009. transferable.push(track.data2.buffer);
  18010. }
  18011. }
  18012. function handleFlushResult(self, results, chunkMeta) {
  18013. var parsed = results.reduce(function (parsed, result) {
  18014. return emitTransmuxComplete(self, result) || parsed;
  18015. }, false);
  18016. if (!parsed) {
  18017. // Emit at least one "transmuxComplete" message even if media is not found to update stream-controller state to PARSING
  18018. self.postMessage({
  18019. event: 'transmuxComplete',
  18020. data: results[0]
  18021. });
  18022. }
  18023. self.postMessage({
  18024. event: 'flush',
  18025. data: chunkMeta
  18026. });
  18027. }
  18028. function isEmptyResult(remuxResult) {
  18029. return !remuxResult.audio && !remuxResult.video && !remuxResult.text && !remuxResult.id3 && !remuxResult.initSegment;
  18030. }
  18031. // ensure the worker ends up in the bundle
  18032. // If the worker should not be included this gets aliased to empty.js
  18033. function hasUMDWorker() {
  18034. return typeof __HLS_WORKER_BUNDLE__ === 'function';
  18035. }
  18036. function injectWorker() {
  18037. var blob = new self.Blob(["var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(" + __HLS_WORKER_BUNDLE__.toString() + ")(true);"], {
  18038. type: 'text/javascript'
  18039. });
  18040. var objectURL = self.URL.createObjectURL(blob);
  18041. var worker = new self.Worker(objectURL);
  18042. return {
  18043. worker: worker,
  18044. objectURL: objectURL
  18045. };
  18046. }
  18047. function loadWorker(path) {
  18048. var scriptURL = new self.URL(path, self.location.href).href;
  18049. var worker = new self.Worker(scriptURL);
  18050. return {
  18051. worker: worker,
  18052. scriptURL: scriptURL
  18053. };
  18054. }
  18055. var TransmuxerInterface = /*#__PURE__*/function () {
  18056. function TransmuxerInterface(hls, id, onTransmuxComplete, onFlush) {
  18057. var _this = this;
  18058. this.error = null;
  18059. this.hls = void 0;
  18060. this.id = void 0;
  18061. this.observer = void 0;
  18062. this.frag = null;
  18063. this.part = null;
  18064. this.useWorker = void 0;
  18065. this.workerContext = null;
  18066. this.onwmsg = void 0;
  18067. this.transmuxer = null;
  18068. this.onTransmuxComplete = void 0;
  18069. this.onFlush = void 0;
  18070. var config = hls.config;
  18071. this.hls = hls;
  18072. this.id = id;
  18073. this.useWorker = !!config.enableWorker;
  18074. this.onTransmuxComplete = onTransmuxComplete;
  18075. this.onFlush = onFlush;
  18076. var forwardMessage = function forwardMessage(ev, data) {
  18077. data = data || {};
  18078. data.frag = _this.frag;
  18079. data.id = _this.id;
  18080. if (ev === Events.ERROR) {
  18081. _this.error = data.error;
  18082. }
  18083. _this.hls.trigger(ev, data);
  18084. };
  18085. // forward events to main thread
  18086. this.observer = new EventEmitter();
  18087. this.observer.on(Events.FRAG_DECRYPTED, forwardMessage);
  18088. this.observer.on(Events.ERROR, forwardMessage);
  18089. var MediaSource = getMediaSource(config.preferManagedMediaSource) || {
  18090. isTypeSupported: function isTypeSupported() {
  18091. return false;
  18092. }
  18093. };
  18094. var m2tsTypeSupported = {
  18095. mpeg: MediaSource.isTypeSupported('audio/mpeg'),
  18096. mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"'),
  18097. ac3: false
  18098. };
  18099. if (this.useWorker && typeof Worker !== 'undefined') {
  18100. var canCreateWorker = config.workerPath || hasUMDWorker();
  18101. if (canCreateWorker) {
  18102. try {
  18103. if (config.workerPath) {
  18104. logger.log("loading Web Worker " + config.workerPath + " for \"" + id + "\"");
  18105. this.workerContext = loadWorker(config.workerPath);
  18106. } else {
  18107. logger.log("injecting Web Worker for \"" + id + "\"");
  18108. this.workerContext = injectWorker();
  18109. }
  18110. this.onwmsg = function (event) {
  18111. return _this.onWorkerMessage(event);
  18112. };
  18113. var worker = this.workerContext.worker;
  18114. worker.addEventListener('message', this.onwmsg);
  18115. worker.onerror = function (event) {
  18116. var error = new Error(event.message + " (" + event.filename + ":" + event.lineno + ")");
  18117. config.enableWorker = false;
  18118. logger.warn("Error in \"" + id + "\" Web Worker, fallback to inline");
  18119. _this.hls.trigger(Events.ERROR, {
  18120. type: ErrorTypes.OTHER_ERROR,
  18121. details: ErrorDetails.INTERNAL_EXCEPTION,
  18122. fatal: false,
  18123. event: 'demuxerWorker',
  18124. error: error
  18125. });
  18126. };
  18127. worker.postMessage({
  18128. cmd: 'init',
  18129. typeSupported: m2tsTypeSupported,
  18130. vendor: '',
  18131. id: id,
  18132. config: JSON.stringify(config)
  18133. });
  18134. } catch (err) {
  18135. logger.warn("Error setting up \"" + id + "\" Web Worker, fallback to inline", err);
  18136. this.resetWorker();
  18137. this.error = null;
  18138. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, '', id);
  18139. }
  18140. return;
  18141. }
  18142. }
  18143. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, '', id);
  18144. }
  18145. var _proto = TransmuxerInterface.prototype;
  18146. _proto.resetWorker = function resetWorker() {
  18147. if (this.workerContext) {
  18148. var _this$workerContext = this.workerContext,
  18149. worker = _this$workerContext.worker,
  18150. objectURL = _this$workerContext.objectURL;
  18151. if (objectURL) {
  18152. // revoke the Object URL that was used to create transmuxer worker, so as not to leak it
  18153. self.URL.revokeObjectURL(objectURL);
  18154. }
  18155. worker.removeEventListener('message', this.onwmsg);
  18156. worker.onerror = null;
  18157. worker.terminate();
  18158. this.workerContext = null;
  18159. }
  18160. };
  18161. _proto.destroy = function destroy() {
  18162. if (this.workerContext) {
  18163. this.resetWorker();
  18164. this.onwmsg = undefined;
  18165. } else {
  18166. var transmuxer = this.transmuxer;
  18167. if (transmuxer) {
  18168. transmuxer.destroy();
  18169. this.transmuxer = null;
  18170. }
  18171. }
  18172. var observer = this.observer;
  18173. if (observer) {
  18174. observer.removeAllListeners();
  18175. }
  18176. this.frag = null;
  18177. // @ts-ignore
  18178. this.observer = null;
  18179. // @ts-ignore
  18180. this.hls = null;
  18181. };
  18182. _proto.push = function push(data, initSegmentData, audioCodec, videoCodec, frag, part, duration, accurateTimeOffset, chunkMeta, defaultInitPTS) {
  18183. var _frag$initSegment,
  18184. _lastFrag$initSegment,
  18185. _this2 = this;
  18186. chunkMeta.transmuxing.start = self.performance.now();
  18187. var transmuxer = this.transmuxer;
  18188. var timeOffset = part ? part.start : frag.start;
  18189. // TODO: push "clear-lead" decrypt data for unencrypted fragments in streams with encrypted ones
  18190. var decryptdata = frag.decryptdata;
  18191. var lastFrag = this.frag;
  18192. var discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
  18193. var trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level);
  18194. var snDiff = lastFrag ? chunkMeta.sn - lastFrag.sn : -1;
  18195. var partDiff = this.part ? chunkMeta.part - this.part.index : -1;
  18196. var progressive = snDiff === 0 && chunkMeta.id > 1 && chunkMeta.id === (lastFrag == null ? void 0 : lastFrag.stats.chunkCount);
  18197. var contiguous = !trackSwitch && (snDiff === 1 || snDiff === 0 && (partDiff === 1 || progressive && partDiff <= 0));
  18198. var now = self.performance.now();
  18199. if (trackSwitch || snDiff || frag.stats.parsing.start === 0) {
  18200. frag.stats.parsing.start = now;
  18201. }
  18202. if (part && (partDiff || !contiguous)) {
  18203. part.stats.parsing.start = now;
  18204. }
  18205. var initSegmentChange = !(lastFrag && ((_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.url) === ((_lastFrag$initSegment = lastFrag.initSegment) == null ? void 0 : _lastFrag$initSegment.url));
  18206. var state = new TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange);
  18207. if (!contiguous || discontinuity || initSegmentChange) {
  18208. logger.log("[transmuxer-interface, " + frag.type + "]: Starting new transmux session for sn: " + chunkMeta.sn + " p: " + chunkMeta.part + " level: " + chunkMeta.level + " id: " + chunkMeta.id + "\n discontinuity: " + discontinuity + "\n trackSwitch: " + trackSwitch + "\n contiguous: " + contiguous + "\n accurateTimeOffset: " + accurateTimeOffset + "\n timeOffset: " + timeOffset + "\n initSegmentChange: " + initSegmentChange);
  18209. var config = new TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPTS);
  18210. this.configureTransmuxer(config);
  18211. }
  18212. this.frag = frag;
  18213. this.part = part;
  18214. // Frags with sn of 'initSegment' are not transmuxed
  18215. if (this.workerContext) {
  18216. // post fragment payload as transferable objects for ArrayBuffer (no copy)
  18217. this.workerContext.worker.postMessage({
  18218. cmd: 'demux',
  18219. data: data,
  18220. decryptdata: decryptdata,
  18221. chunkMeta: chunkMeta,
  18222. state: state
  18223. }, data instanceof ArrayBuffer ? [data] : []);
  18224. } else if (transmuxer) {
  18225. var _transmuxResult = transmuxer.push(data, decryptdata, chunkMeta, state);
  18226. if (isPromise(_transmuxResult)) {
  18227. transmuxer.async = true;
  18228. _transmuxResult.then(function (data) {
  18229. _this2.handleTransmuxComplete(data);
  18230. }).catch(function (error) {
  18231. _this2.transmuxerError(error, chunkMeta, 'transmuxer-interface push error');
  18232. });
  18233. } else {
  18234. transmuxer.async = false;
  18235. this.handleTransmuxComplete(_transmuxResult);
  18236. }
  18237. }
  18238. };
  18239. _proto.flush = function flush(chunkMeta) {
  18240. var _this3 = this;
  18241. chunkMeta.transmuxing.start = self.performance.now();
  18242. var transmuxer = this.transmuxer;
  18243. if (this.workerContext) {
  18244. this.workerContext.worker.postMessage({
  18245. cmd: 'flush',
  18246. chunkMeta: chunkMeta
  18247. });
  18248. } else if (transmuxer) {
  18249. var _transmuxResult2 = transmuxer.flush(chunkMeta);
  18250. var asyncFlush = isPromise(_transmuxResult2);
  18251. if (asyncFlush || transmuxer.async) {
  18252. if (!isPromise(_transmuxResult2)) {
  18253. _transmuxResult2 = Promise.resolve(_transmuxResult2);
  18254. }
  18255. _transmuxResult2.then(function (data) {
  18256. _this3.handleFlushResult(data, chunkMeta);
  18257. }).catch(function (error) {
  18258. _this3.transmuxerError(error, chunkMeta, 'transmuxer-interface flush error');
  18259. });
  18260. } else {
  18261. this.handleFlushResult(_transmuxResult2, chunkMeta);
  18262. }
  18263. }
  18264. };
  18265. _proto.transmuxerError = function transmuxerError(error, chunkMeta, reason) {
  18266. if (!this.hls) {
  18267. return;
  18268. }
  18269. this.error = error;
  18270. this.hls.trigger(Events.ERROR, {
  18271. type: ErrorTypes.MEDIA_ERROR,
  18272. details: ErrorDetails.FRAG_PARSING_ERROR,
  18273. chunkMeta: chunkMeta,
  18274. frag: this.frag || undefined,
  18275. fatal: false,
  18276. error: error,
  18277. err: error,
  18278. reason: reason
  18279. });
  18280. };
  18281. _proto.handleFlushResult = function handleFlushResult(results, chunkMeta) {
  18282. var _this4 = this;
  18283. results.forEach(function (result) {
  18284. _this4.handleTransmuxComplete(result);
  18285. });
  18286. this.onFlush(chunkMeta);
  18287. };
  18288. _proto.onWorkerMessage = function onWorkerMessage(event) {
  18289. var data = event.data;
  18290. if (!(data != null && data.event)) {
  18291. logger.warn("worker message received with no " + (data ? 'event name' : 'data'));
  18292. return;
  18293. }
  18294. var hls = this.hls;
  18295. if (!this.hls) {
  18296. return;
  18297. }
  18298. switch (data.event) {
  18299. case 'init':
  18300. {
  18301. var _this$workerContext2;
  18302. var objectURL = (_this$workerContext2 = this.workerContext) == null ? void 0 : _this$workerContext2.objectURL;
  18303. if (objectURL) {
  18304. // revoke the Object URL that was used to create transmuxer worker, so as not to leak it
  18305. self.URL.revokeObjectURL(objectURL);
  18306. }
  18307. break;
  18308. }
  18309. case 'transmuxComplete':
  18310. {
  18311. this.handleTransmuxComplete(data.data);
  18312. break;
  18313. }
  18314. case 'flush':
  18315. {
  18316. this.onFlush(data.data);
  18317. break;
  18318. }
  18319. // pass logs from the worker thread to the main logger
  18320. case 'workerLog':
  18321. if (logger[data.data.logType]) {
  18322. logger[data.data.logType](data.data.message);
  18323. }
  18324. break;
  18325. default:
  18326. {
  18327. data.data = data.data || {};
  18328. data.data.frag = this.frag;
  18329. data.data.id = this.id;
  18330. hls.trigger(data.event, data.data);
  18331. break;
  18332. }
  18333. }
  18334. };
  18335. _proto.configureTransmuxer = function configureTransmuxer(config) {
  18336. var transmuxer = this.transmuxer;
  18337. if (this.workerContext) {
  18338. this.workerContext.worker.postMessage({
  18339. cmd: 'configure',
  18340. config: config
  18341. });
  18342. } else if (transmuxer) {
  18343. transmuxer.configure(config);
  18344. }
  18345. };
  18346. _proto.handleTransmuxComplete = function handleTransmuxComplete(result) {
  18347. result.chunkMeta.transmuxing.end = self.performance.now();
  18348. this.onTransmuxComplete(result);
  18349. };
  18350. return TransmuxerInterface;
  18351. }();
  18352. var STALL_MINIMUM_DURATION_MS = 250;
  18353. var MAX_START_GAP_JUMP = 2.0;
  18354. var SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;
  18355. var SKIP_BUFFER_RANGE_START = 0.05;
  18356. var GapController = /*#__PURE__*/function () {
  18357. function GapController(config, media, fragmentTracker, hls) {
  18358. this.config = void 0;
  18359. this.media = null;
  18360. this.fragmentTracker = void 0;
  18361. this.hls = void 0;
  18362. this.nudgeRetry = 0;
  18363. this.stallReported = false;
  18364. this.stalled = null;
  18365. this.moved = false;
  18366. this.seeking = false;
  18367. this.config = config;
  18368. this.media = media;
  18369. this.fragmentTracker = fragmentTracker;
  18370. this.hls = hls;
  18371. }
  18372. var _proto = GapController.prototype;
  18373. _proto.destroy = function destroy() {
  18374. this.media = null;
  18375. // @ts-ignore
  18376. this.hls = this.fragmentTracker = null;
  18377. }
  18378. /**
  18379. * Checks if the playhead is stuck within a gap, and if so, attempts to free it.
  18380. * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).
  18381. *
  18382. * @param lastCurrentTime - Previously read playhead position
  18383. */;
  18384. _proto.poll = function poll(lastCurrentTime, activeFrag) {
  18385. var config = this.config,
  18386. media = this.media,
  18387. stalled = this.stalled;
  18388. if (media === null) {
  18389. return;
  18390. }
  18391. var currentTime = media.currentTime,
  18392. seeking = media.seeking;
  18393. var seeked = this.seeking && !seeking;
  18394. var beginSeek = !this.seeking && seeking;
  18395. this.seeking = seeking;
  18396. // The playhead is moving, no-op
  18397. if (currentTime !== lastCurrentTime) {
  18398. this.moved = true;
  18399. if (!seeking) {
  18400. this.nudgeRetry = 0;
  18401. }
  18402. if (stalled !== null) {
  18403. // The playhead is now moving, but was previously stalled
  18404. if (this.stallReported) {
  18405. var _stalledDuration = self.performance.now() - stalled;
  18406. logger.warn("playback not stuck anymore @" + currentTime + ", after " + Math.round(_stalledDuration) + "ms");
  18407. this.stallReported = false;
  18408. }
  18409. this.stalled = null;
  18410. }
  18411. return;
  18412. }
  18413. // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek
  18414. if (beginSeek || seeked) {
  18415. this.stalled = null;
  18416. return;
  18417. }
  18418. // The playhead should not be moving
  18419. if (media.paused && !seeking || media.ended || media.playbackRate === 0 || !BufferHelper.getBuffered(media).length) {
  18420. this.nudgeRetry = 0;
  18421. return;
  18422. }
  18423. var bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  18424. var nextStart = bufferInfo.nextStart || 0;
  18425. if (seeking) {
  18426. // Waiting for seeking in a buffered range to complete
  18427. var hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP;
  18428. // Next buffered range is too far ahead to jump to while still seeking
  18429. var noBufferGap = !nextStart || activeFrag && activeFrag.start <= currentTime || nextStart - currentTime > MAX_START_GAP_JUMP && !this.fragmentTracker.getPartialFragment(currentTime);
  18430. if (hasEnoughBuffer || noBufferGap) {
  18431. return;
  18432. }
  18433. // Reset moved state when seeking to a point in or before a gap
  18434. this.moved = false;
  18435. }
  18436. // Skip start gaps if we haven't played, but the last poll detected the start of a stall
  18437. // The addition poll gives the browser a chance to jump the gap for us
  18438. if (!this.moved && this.stalled !== null) {
  18439. var _level$details;
  18440. // There is no playable buffer (seeked, waiting for buffer)
  18441. var isBuffered = bufferInfo.len > 0;
  18442. if (!isBuffered && !nextStart) {
  18443. return;
  18444. }
  18445. // Jump start gaps within jump threshold
  18446. var startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime;
  18447. // When joining a live stream with audio tracks, account for live playlist window sliding by allowing
  18448. // a larger jump over start gaps caused by the audio-stream-controller buffering a start fragment
  18449. // that begins over 1 target duration after the video start position.
  18450. var level = this.hls.levels ? this.hls.levels[this.hls.currentLevel] : null;
  18451. var isLive = level == null ? void 0 : (_level$details = level.details) == null ? void 0 : _level$details.live;
  18452. var maxStartGapJump = isLive ? level.details.targetduration * 2 : MAX_START_GAP_JUMP;
  18453. var partialOrGap = this.fragmentTracker.getPartialFragment(currentTime);
  18454. if (startJump > 0 && (startJump <= maxStartGapJump || partialOrGap)) {
  18455. if (!media.paused) {
  18456. this._trySkipBufferHole(partialOrGap);
  18457. }
  18458. return;
  18459. }
  18460. }
  18461. // Start tracking stall time
  18462. var tnow = self.performance.now();
  18463. if (stalled === null) {
  18464. this.stalled = tnow;
  18465. return;
  18466. }
  18467. var stalledDuration = tnow - stalled;
  18468. if (!seeking && stalledDuration >= STALL_MINIMUM_DURATION_MS) {
  18469. // Report stalling after trying to fix
  18470. this._reportStall(bufferInfo);
  18471. if (!this.media) {
  18472. return;
  18473. }
  18474. }
  18475. var bufferedWithHoles = BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);
  18476. this._tryFixBufferStall(bufferedWithHoles, stalledDuration);
  18477. }
  18478. /**
  18479. * Detects and attempts to fix known buffer stalling issues.
  18480. * @param bufferInfo - The properties of the current buffer.
  18481. * @param stalledDurationMs - The amount of time Hls.js has been stalling for.
  18482. * @private
  18483. */;
  18484. _proto._tryFixBufferStall = function _tryFixBufferStall(bufferInfo, stalledDurationMs) {
  18485. var config = this.config,
  18486. fragmentTracker = this.fragmentTracker,
  18487. media = this.media;
  18488. if (media === null) {
  18489. return;
  18490. }
  18491. var currentTime = media.currentTime;
  18492. var partial = fragmentTracker.getPartialFragment(currentTime);
  18493. if (partial) {
  18494. // Try to skip over the buffer hole caused by a partial fragment
  18495. // This method isn't limited by the size of the gap between buffered ranges
  18496. var targetTime = this._trySkipBufferHole(partial);
  18497. // we return here in this case, meaning
  18498. // the branch below only executes when we haven't seeked to a new position
  18499. if (targetTime || !this.media) {
  18500. return;
  18501. }
  18502. }
  18503. // if we haven't had to skip over a buffer hole of a partial fragment
  18504. // we may just have to "nudge" the playlist as the browser decoding/rendering engine
  18505. // needs to cross some sort of threshold covering all source-buffers content
  18506. // to start playing properly.
  18507. if ((bufferInfo.len > config.maxBufferHole || bufferInfo.nextStart && bufferInfo.nextStart - currentTime < config.maxBufferHole) && stalledDurationMs > config.highBufferWatchdogPeriod * 1000) {
  18508. logger.warn('Trying to nudge playhead over buffer-hole');
  18509. // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds
  18510. // We only try to jump the hole if it's under the configured size
  18511. // Reset stalled so to rearm watchdog timer
  18512. this.stalled = null;
  18513. this._tryNudgeBuffer();
  18514. }
  18515. }
  18516. /**
  18517. * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.
  18518. * @param bufferLen - The playhead distance from the end of the current buffer segment.
  18519. * @private
  18520. */;
  18521. _proto._reportStall = function _reportStall(bufferInfo) {
  18522. var hls = this.hls,
  18523. media = this.media,
  18524. stallReported = this.stallReported;
  18525. if (!stallReported && media) {
  18526. // Report stalled error once
  18527. this.stallReported = true;
  18528. var error = new Error("Playback stalling at @" + media.currentTime + " due to low buffer (" + JSON.stringify(bufferInfo) + ")");
  18529. logger.warn(error.message);
  18530. hls.trigger(Events.ERROR, {
  18531. type: ErrorTypes.MEDIA_ERROR,
  18532. details: ErrorDetails.BUFFER_STALLED_ERROR,
  18533. fatal: false,
  18534. error: error,
  18535. buffer: bufferInfo.len
  18536. });
  18537. }
  18538. }
  18539. /**
  18540. * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
  18541. * @param partial - The partial fragment found at the current time (where playback is stalling).
  18542. * @private
  18543. */;
  18544. _proto._trySkipBufferHole = function _trySkipBufferHole(partial) {
  18545. var config = this.config,
  18546. hls = this.hls,
  18547. media = this.media;
  18548. if (media === null) {
  18549. return 0;
  18550. }
  18551. // Check if currentTime is between unbuffered regions of partial fragments
  18552. var currentTime = media.currentTime;
  18553. var bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  18554. var startTime = currentTime < bufferInfo.start ? bufferInfo.start : bufferInfo.nextStart;
  18555. if (startTime) {
  18556. var bufferStarved = bufferInfo.len <= config.maxBufferHole;
  18557. var waiting = bufferInfo.len > 0 && bufferInfo.len < 1 && media.readyState < 3;
  18558. var gapLength = startTime - currentTime;
  18559. if (gapLength > 0 && (bufferStarved || waiting)) {
  18560. // Only allow large gaps to be skipped if it is a start gap, or all fragments in skip range are partial
  18561. if (gapLength > config.maxBufferHole) {
  18562. var fragmentTracker = this.fragmentTracker;
  18563. var startGap = false;
  18564. if (currentTime === 0) {
  18565. var startFrag = fragmentTracker.getAppendedFrag(0, PlaylistLevelType.MAIN);
  18566. if (startFrag && startTime < startFrag.end) {
  18567. startGap = true;
  18568. }
  18569. }
  18570. if (!startGap) {
  18571. var startProvisioned = partial || fragmentTracker.getAppendedFrag(currentTime, PlaylistLevelType.MAIN);
  18572. if (startProvisioned) {
  18573. var moreToLoad = false;
  18574. var pos = startProvisioned.end;
  18575. while (pos < startTime) {
  18576. var provisioned = fragmentTracker.getPartialFragment(pos);
  18577. if (provisioned) {
  18578. pos += provisioned.duration;
  18579. } else {
  18580. moreToLoad = true;
  18581. break;
  18582. }
  18583. }
  18584. if (moreToLoad) {
  18585. return 0;
  18586. }
  18587. }
  18588. }
  18589. }
  18590. var targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);
  18591. logger.warn("skipping hole, adjusting currentTime from " + currentTime + " to " + targetTime);
  18592. this.moved = true;
  18593. this.stalled = null;
  18594. media.currentTime = targetTime;
  18595. if (partial && !partial.gap) {
  18596. var error = new Error("fragment loaded with buffer holes, seeking from " + currentTime + " to " + targetTime);
  18597. hls.trigger(Events.ERROR, {
  18598. type: ErrorTypes.MEDIA_ERROR,
  18599. details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,
  18600. fatal: false,
  18601. error: error,
  18602. reason: error.message,
  18603. frag: partial
  18604. });
  18605. }
  18606. return targetTime;
  18607. }
  18608. }
  18609. return 0;
  18610. }
  18611. /**
  18612. * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
  18613. * @private
  18614. */;
  18615. _proto._tryNudgeBuffer = function _tryNudgeBuffer() {
  18616. var config = this.config,
  18617. hls = this.hls,
  18618. media = this.media,
  18619. nudgeRetry = this.nudgeRetry;
  18620. if (media === null) {
  18621. return;
  18622. }
  18623. var currentTime = media.currentTime;
  18624. this.nudgeRetry++;
  18625. if (nudgeRetry < config.nudgeMaxRetry) {
  18626. var targetTime = currentTime + (nudgeRetry + 1) * config.nudgeOffset;
  18627. // playback stalled in buffered area ... let's nudge currentTime to try to overcome this
  18628. var error = new Error("Nudging 'currentTime' from " + currentTime + " to " + targetTime);
  18629. logger.warn(error.message);
  18630. media.currentTime = targetTime;
  18631. hls.trigger(Events.ERROR, {
  18632. type: ErrorTypes.MEDIA_ERROR,
  18633. details: ErrorDetails.BUFFER_NUDGE_ON_STALL,
  18634. error: error,
  18635. fatal: false
  18636. });
  18637. } else {
  18638. var _error = new Error("Playhead still not moving while enough data buffered @" + currentTime + " after " + config.nudgeMaxRetry + " nudges");
  18639. logger.error(_error.message);
  18640. hls.trigger(Events.ERROR, {
  18641. type: ErrorTypes.MEDIA_ERROR,
  18642. details: ErrorDetails.BUFFER_STALLED_ERROR,
  18643. error: _error,
  18644. fatal: true
  18645. });
  18646. }
  18647. };
  18648. return GapController;
  18649. }();
  18650. var TICK_INTERVAL = 100; // how often to tick in ms
  18651. var StreamController = /*#__PURE__*/function (_BaseStreamController) {
  18652. _inheritsLoose(StreamController, _BaseStreamController);
  18653. function StreamController(hls, fragmentTracker, keyLoader) {
  18654. var _this;
  18655. _this = _BaseStreamController.call(this, hls, fragmentTracker, keyLoader, '[stream-controller]', PlaylistLevelType.MAIN) || this;
  18656. _this.audioCodecSwap = false;
  18657. _this.gapController = null;
  18658. _this.level = -1;
  18659. _this._forceStartLoad = false;
  18660. _this.altAudio = false;
  18661. _this.audioOnly = false;
  18662. _this.fragPlaying = null;
  18663. _this.onvplaying = null;
  18664. _this.onvseeked = null;
  18665. _this.fragLastKbps = 0;
  18666. _this.couldBacktrack = false;
  18667. _this.backtrackFragment = null;
  18668. _this.audioCodecSwitch = false;
  18669. _this.videoBuffer = null;
  18670. _this._registerListeners();
  18671. return _this;
  18672. }
  18673. var _proto = StreamController.prototype;
  18674. _proto._registerListeners = function _registerListeners() {
  18675. var hls = this.hls;
  18676. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  18677. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  18678. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  18679. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  18680. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  18681. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  18682. hls.on(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  18683. hls.on(Events.ERROR, this.onError, this);
  18684. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  18685. hls.on(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  18686. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  18687. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  18688. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  18689. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  18690. };
  18691. _proto._unregisterListeners = function _unregisterListeners() {
  18692. var hls = this.hls;
  18693. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  18694. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  18695. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  18696. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  18697. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  18698. hls.off(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  18699. hls.off(Events.ERROR, this.onError, this);
  18700. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  18701. hls.off(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  18702. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  18703. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  18704. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  18705. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  18706. };
  18707. _proto.onHandlerDestroying = function onHandlerDestroying() {
  18708. this._unregisterListeners();
  18709. _BaseStreamController.prototype.onHandlerDestroying.call(this);
  18710. };
  18711. _proto.startLoad = function startLoad(startPosition) {
  18712. if (this.levels) {
  18713. var lastCurrentTime = this.lastCurrentTime,
  18714. hls = this.hls;
  18715. this.stopLoad();
  18716. this.setInterval(TICK_INTERVAL);
  18717. this.level = -1;
  18718. if (!this.startFragRequested) {
  18719. // determine load level
  18720. var startLevel = hls.startLevel;
  18721. if (startLevel === -1) {
  18722. if (hls.config.testBandwidth && this.levels.length > 1) {
  18723. // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
  18724. startLevel = 0;
  18725. this.bitrateTest = true;
  18726. } else {
  18727. startLevel = hls.firstAutoLevel;
  18728. }
  18729. }
  18730. // set new level to playlist loader : this will trigger start level load
  18731. // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
  18732. hls.nextLoadLevel = startLevel;
  18733. this.level = hls.loadLevel;
  18734. this.loadedmetadata = false;
  18735. }
  18736. // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime
  18737. if (lastCurrentTime > 0 && startPosition === -1) {
  18738. this.log("Override startPosition with lastCurrentTime @" + lastCurrentTime.toFixed(3));
  18739. startPosition = lastCurrentTime;
  18740. }
  18741. this.state = State.IDLE;
  18742. this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
  18743. this.tick();
  18744. } else {
  18745. this._forceStartLoad = true;
  18746. this.state = State.STOPPED;
  18747. }
  18748. };
  18749. _proto.stopLoad = function stopLoad() {
  18750. this._forceStartLoad = false;
  18751. _BaseStreamController.prototype.stopLoad.call(this);
  18752. };
  18753. _proto.doTick = function doTick() {
  18754. switch (this.state) {
  18755. case State.WAITING_LEVEL:
  18756. {
  18757. var levels = this.levels,
  18758. level = this.level;
  18759. var currentLevel = levels == null ? void 0 : levels[level];
  18760. var details = currentLevel == null ? void 0 : currentLevel.details;
  18761. if (details && (!details.live || this.levelLastLoaded === currentLevel)) {
  18762. if (this.waitForCdnTuneIn(details)) {
  18763. break;
  18764. }
  18765. this.state = State.IDLE;
  18766. break;
  18767. } else if (this.hls.nextLoadLevel !== this.level) {
  18768. this.state = State.IDLE;
  18769. break;
  18770. }
  18771. break;
  18772. }
  18773. case State.FRAG_LOADING_WAITING_RETRY:
  18774. {
  18775. var _this$media;
  18776. var now = self.performance.now();
  18777. var retryDate = this.retryDate;
  18778. // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  18779. if (!retryDate || now >= retryDate || (_this$media = this.media) != null && _this$media.seeking) {
  18780. var _levels = this.levels,
  18781. _level = this.level;
  18782. var _currentLevel = _levels == null ? void 0 : _levels[_level];
  18783. this.resetStartWhenNotLoaded(_currentLevel || null);
  18784. this.state = State.IDLE;
  18785. }
  18786. }
  18787. break;
  18788. }
  18789. if (this.state === State.IDLE) {
  18790. this.doTickIdle();
  18791. }
  18792. this.onTickEnd();
  18793. };
  18794. _proto.onTickEnd = function onTickEnd() {
  18795. _BaseStreamController.prototype.onTickEnd.call(this);
  18796. this.checkBuffer();
  18797. this.checkFragmentChanged();
  18798. };
  18799. _proto.doTickIdle = function doTickIdle() {
  18800. var hls = this.hls,
  18801. levelLastLoaded = this.levelLastLoaded,
  18802. levels = this.levels,
  18803. media = this.media;
  18804. // if start level not parsed yet OR
  18805. // if video not attached AND start fragment already requested OR start frag prefetch not enabled
  18806. // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment
  18807. if (levelLastLoaded === null || !media && (this.startFragRequested || !hls.config.startFragPrefetch)) {
  18808. return;
  18809. }
  18810. // If the "main" level is audio-only but we are loading an alternate track in the same group, do not load anything
  18811. if (this.altAudio && this.audioOnly) {
  18812. return;
  18813. }
  18814. var level = hls.nextLoadLevel;
  18815. if (!(levels != null && levels[level])) {
  18816. return;
  18817. }
  18818. var levelInfo = levels[level];
  18819. // if buffer length is less than maxBufLen try to load a new fragment
  18820. var bufferInfo = this.getMainFwdBufferInfo();
  18821. if (bufferInfo === null) {
  18822. return;
  18823. }
  18824. var lastDetails = this.getLevelDetails();
  18825. if (lastDetails && this._streamEnded(bufferInfo, lastDetails)) {
  18826. var data = {};
  18827. if (this.altAudio) {
  18828. data.type = 'video';
  18829. }
  18830. this.hls.trigger(Events.BUFFER_EOS, data);
  18831. this.state = State.ENDED;
  18832. return;
  18833. }
  18834. // set next load level : this will trigger a playlist load if needed
  18835. if (hls.loadLevel !== level && hls.manualLevel === -1) {
  18836. this.log("Adapting to level " + level + " from level " + this.level);
  18837. }
  18838. this.level = hls.nextLoadLevel = level;
  18839. var levelDetails = levelInfo.details;
  18840. // if level info not retrieved yet, switch state and wait for level retrieval
  18841. // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
  18842. // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
  18843. if (!levelDetails || this.state === State.WAITING_LEVEL || levelDetails.live && this.levelLastLoaded !== levelInfo) {
  18844. this.level = level;
  18845. this.state = State.WAITING_LEVEL;
  18846. return;
  18847. }
  18848. var bufferLen = bufferInfo.len;
  18849. // 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
  18850. var maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate);
  18851. // Stay idle if we are still with buffer margins
  18852. if (bufferLen >= maxBufLen) {
  18853. return;
  18854. }
  18855. if (this.backtrackFragment && this.backtrackFragment.start > bufferInfo.end) {
  18856. this.backtrackFragment = null;
  18857. }
  18858. var targetBufferTime = this.backtrackFragment ? this.backtrackFragment.start : bufferInfo.end;
  18859. var frag = this.getNextFragment(targetBufferTime, levelDetails);
  18860. // Avoid backtracking by loading an earlier segment in streams with segments that do not start with a key frame (flagged by `couldBacktrack`)
  18861. if (this.couldBacktrack && !this.fragPrevious && frag && frag.sn !== 'initSegment' && this.fragmentTracker.getState(frag) !== FragmentState.OK) {
  18862. var _this$backtrackFragme;
  18863. var backtrackSn = ((_this$backtrackFragme = this.backtrackFragment) != null ? _this$backtrackFragme : frag).sn;
  18864. var fragIdx = backtrackSn - levelDetails.startSN;
  18865. var backtrackFrag = levelDetails.fragments[fragIdx - 1];
  18866. if (backtrackFrag && frag.cc === backtrackFrag.cc) {
  18867. frag = backtrackFrag;
  18868. this.fragmentTracker.removeFragment(backtrackFrag);
  18869. }
  18870. } else if (this.backtrackFragment && bufferInfo.len) {
  18871. this.backtrackFragment = null;
  18872. }
  18873. // Avoid loop loading by using nextLoadPosition set for backtracking and skipping consecutive GAP tags
  18874. if (frag && this.isLoopLoading(frag, targetBufferTime)) {
  18875. var gapStart = frag.gap;
  18876. if (!gapStart) {
  18877. // Cleanup the fragment tracker before trying to find the next unbuffered fragment
  18878. var type = this.audioOnly && !this.altAudio ? ElementaryStreamTypes.AUDIO : ElementaryStreamTypes.VIDEO;
  18879. var mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  18880. if (mediaBuffer) {
  18881. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  18882. }
  18883. }
  18884. frag = this.getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen);
  18885. }
  18886. if (!frag) {
  18887. return;
  18888. }
  18889. if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) {
  18890. frag = frag.initSegment;
  18891. }
  18892. this.loadFragment(frag, levelInfo, targetBufferTime);
  18893. };
  18894. _proto.loadFragment = function loadFragment(frag, level, targetBufferTime) {
  18895. // Check if fragment is not loaded
  18896. var fragState = this.fragmentTracker.getState(frag);
  18897. this.fragCurrent = frag;
  18898. if (fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
  18899. if (frag.sn === 'initSegment') {
  18900. this._loadInitSegment(frag, level);
  18901. } else if (this.bitrateTest) {
  18902. this.log("Fragment " + frag.sn + " of level " + frag.level + " is being downloaded to test bitrate and will not be buffered");
  18903. this._loadBitrateTestFrag(frag, level);
  18904. } else {
  18905. this.startFragRequested = true;
  18906. _BaseStreamController.prototype.loadFragment.call(this, frag, level, targetBufferTime);
  18907. }
  18908. } else {
  18909. this.clearTrackerIfNeeded(frag);
  18910. }
  18911. };
  18912. _proto.getBufferedFrag = function getBufferedFrag(position) {
  18913. return this.fragmentTracker.getBufferedFrag(position, PlaylistLevelType.MAIN);
  18914. };
  18915. _proto.followingBufferedFrag = function followingBufferedFrag(frag) {
  18916. if (frag) {
  18917. // try to get range of next fragment (500ms after this range)
  18918. return this.getBufferedFrag(frag.end + 0.5);
  18919. }
  18920. return null;
  18921. }
  18922. /*
  18923. on immediate level switch :
  18924. - pause playback if playing
  18925. - cancel any pending load request
  18926. - and trigger a buffer flush
  18927. */;
  18928. _proto.immediateLevelSwitch = function immediateLevelSwitch() {
  18929. this.abortCurrentFrag();
  18930. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  18931. }
  18932. /**
  18933. * try to switch ASAP without breaking video playback:
  18934. * in order to ensure smooth but quick level switching,
  18935. * we need to find the next flushable buffer range
  18936. * we should take into account new segment fetch time
  18937. */;
  18938. _proto.nextLevelSwitch = function nextLevelSwitch() {
  18939. var levels = this.levels,
  18940. media = this.media;
  18941. // ensure that media is defined and that metadata are available (to retrieve currentTime)
  18942. if (media != null && media.readyState) {
  18943. var fetchdelay;
  18944. var fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
  18945. if (fragPlayingCurrent && fragPlayingCurrent.start > 1) {
  18946. // flush buffer preceding current fragment (flush until current fragment start offset)
  18947. // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
  18948. this.flushMainBuffer(0, fragPlayingCurrent.start - 1);
  18949. }
  18950. var levelDetails = this.getLevelDetails();
  18951. if (levelDetails != null && levelDetails.live) {
  18952. var bufferInfo = this.getMainFwdBufferInfo();
  18953. // Do not flush in live stream with low buffer
  18954. if (!bufferInfo || bufferInfo.len < levelDetails.targetduration * 2) {
  18955. return;
  18956. }
  18957. }
  18958. if (!media.paused && levels) {
  18959. // add a safety delay of 1s
  18960. var nextLevelId = this.hls.nextLoadLevel;
  18961. var nextLevel = levels[nextLevelId];
  18962. var fragLastKbps = this.fragLastKbps;
  18963. if (fragLastKbps && this.fragCurrent) {
  18964. fetchdelay = this.fragCurrent.duration * nextLevel.maxBitrate / (1000 * fragLastKbps) + 1;
  18965. } else {
  18966. fetchdelay = 0;
  18967. }
  18968. } else {
  18969. fetchdelay = 0;
  18970. }
  18971. // this.log('fetchdelay:'+fetchdelay);
  18972. // find buffer range that will be reached once new fragment will be fetched
  18973. var bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
  18974. if (bufferedFrag) {
  18975. // we can flush buffer range following this one without stalling playback
  18976. var nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);
  18977. if (nextBufferedFrag) {
  18978. // if we are here, we can also cancel any loading/demuxing in progress, as they are useless
  18979. this.abortCurrentFrag();
  18980. // start flush position is in next buffered frag. Leave some padding for non-independent segments and smoother playback.
  18981. var maxStart = nextBufferedFrag.maxStartPTS ? nextBufferedFrag.maxStartPTS : nextBufferedFrag.start;
  18982. var fragDuration = nextBufferedFrag.duration;
  18983. 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)));
  18984. this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);
  18985. }
  18986. }
  18987. }
  18988. };
  18989. _proto.abortCurrentFrag = function abortCurrentFrag() {
  18990. var fragCurrent = this.fragCurrent;
  18991. this.fragCurrent = null;
  18992. this.backtrackFragment = null;
  18993. if (fragCurrent) {
  18994. fragCurrent.abortRequests();
  18995. this.fragmentTracker.removeFragment(fragCurrent);
  18996. }
  18997. switch (this.state) {
  18998. case State.KEY_LOADING:
  18999. case State.FRAG_LOADING:
  19000. case State.FRAG_LOADING_WAITING_RETRY:
  19001. case State.PARSING:
  19002. case State.PARSED:
  19003. this.state = State.IDLE;
  19004. break;
  19005. }
  19006. this.nextLoadPosition = this.getLoadPosition();
  19007. };
  19008. _proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset) {
  19009. _BaseStreamController.prototype.flushMainBuffer.call(this, startOffset, endOffset, this.altAudio ? 'video' : null);
  19010. };
  19011. _proto.onMediaAttached = function onMediaAttached(event, data) {
  19012. _BaseStreamController.prototype.onMediaAttached.call(this, event, data);
  19013. var media = data.media;
  19014. this.onvplaying = this.onMediaPlaying.bind(this);
  19015. this.onvseeked = this.onMediaSeeked.bind(this);
  19016. media.addEventListener('playing', this.onvplaying);
  19017. media.addEventListener('seeked', this.onvseeked);
  19018. this.gapController = new GapController(this.config, media, this.fragmentTracker, this.hls);
  19019. };
  19020. _proto.onMediaDetaching = function onMediaDetaching() {
  19021. var media = this.media;
  19022. if (media && this.onvplaying && this.onvseeked) {
  19023. media.removeEventListener('playing', this.onvplaying);
  19024. media.removeEventListener('seeked', this.onvseeked);
  19025. this.onvplaying = this.onvseeked = null;
  19026. this.videoBuffer = null;
  19027. }
  19028. this.fragPlaying = null;
  19029. if (this.gapController) {
  19030. this.gapController.destroy();
  19031. this.gapController = null;
  19032. }
  19033. _BaseStreamController.prototype.onMediaDetaching.call(this);
  19034. };
  19035. _proto.onMediaPlaying = function onMediaPlaying() {
  19036. // tick to speed up FRAG_CHANGED triggering
  19037. this.tick();
  19038. };
  19039. _proto.onMediaSeeked = function onMediaSeeked() {
  19040. var media = this.media;
  19041. var currentTime = media ? media.currentTime : null;
  19042. if (isFiniteNumber(currentTime)) {
  19043. this.log("Media seeked to " + currentTime.toFixed(3));
  19044. }
  19045. // If seeked was issued before buffer was appended do not tick immediately
  19046. var bufferInfo = this.getMainFwdBufferInfo();
  19047. if (bufferInfo === null || bufferInfo.len === 0) {
  19048. this.warn("Main forward buffer length on \"seeked\" event " + (bufferInfo ? bufferInfo.len : 'empty') + ")");
  19049. return;
  19050. }
  19051. // tick to speed up FRAG_CHANGED triggering
  19052. this.tick();
  19053. };
  19054. _proto.onManifestLoading = function onManifestLoading() {
  19055. // reset buffer on manifest loading
  19056. this.log('Trigger BUFFER_RESET');
  19057. this.hls.trigger(Events.BUFFER_RESET, undefined);
  19058. this.fragmentTracker.removeAllFragments();
  19059. this.couldBacktrack = false;
  19060. this.startPosition = this.lastCurrentTime = this.fragLastKbps = 0;
  19061. this.levels = this.fragPlaying = this.backtrackFragment = this.levelLastLoaded = null;
  19062. this.altAudio = this.audioOnly = this.startFragRequested = false;
  19063. };
  19064. _proto.onManifestParsed = function onManifestParsed(event, data) {
  19065. // detect if we have different kind of audio codecs used amongst playlists
  19066. var aac = false;
  19067. var heaac = false;
  19068. data.levels.forEach(function (level) {
  19069. var codec = level.audioCodec;
  19070. if (codec) {
  19071. aac = aac || codec.indexOf('mp4a.40.2') !== -1;
  19072. heaac = heaac || codec.indexOf('mp4a.40.5') !== -1;
  19073. }
  19074. });
  19075. this.audioCodecSwitch = aac && heaac && !changeTypeSupported();
  19076. if (this.audioCodecSwitch) {
  19077. this.log('Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
  19078. }
  19079. this.levels = data.levels;
  19080. this.startFragRequested = false;
  19081. };
  19082. _proto.onLevelLoading = function onLevelLoading(event, data) {
  19083. var levels = this.levels;
  19084. if (!levels || this.state !== State.IDLE) {
  19085. return;
  19086. }
  19087. var level = levels[data.level];
  19088. if (!level.details || level.details.live && this.levelLastLoaded !== level || this.waitForCdnTuneIn(level.details)) {
  19089. this.state = State.WAITING_LEVEL;
  19090. }
  19091. };
  19092. _proto.onLevelLoaded = function onLevelLoaded(event, data) {
  19093. var _curLevel$details;
  19094. var levels = this.levels;
  19095. var newLevelId = data.level;
  19096. var newDetails = data.details;
  19097. var duration = newDetails.totalduration;
  19098. if (!levels) {
  19099. this.warn("Levels were reset while loading level " + newLevelId);
  19100. return;
  19101. }
  19102. this.log("Level " + newLevelId + " loaded [" + newDetails.startSN + "," + newDetails.endSN + "]" + (newDetails.lastPartSn ? "[part-" + newDetails.lastPartSn + "-" + newDetails.lastPartIndex + "]" : '') + ", cc [" + newDetails.startCC + ", " + newDetails.endCC + "] duration:" + duration);
  19103. var curLevel = levels[newLevelId];
  19104. var fragCurrent = this.fragCurrent;
  19105. if (fragCurrent && (this.state === State.FRAG_LOADING || this.state === State.FRAG_LOADING_WAITING_RETRY)) {
  19106. if (fragCurrent.level !== data.level && fragCurrent.loader) {
  19107. this.abortCurrentFrag();
  19108. }
  19109. }
  19110. var sliding = 0;
  19111. if (newDetails.live || (_curLevel$details = curLevel.details) != null && _curLevel$details.live) {
  19112. var _this$levelLastLoaded;
  19113. this.checkLiveUpdate(newDetails);
  19114. if (newDetails.deltaUpdateFailed) {
  19115. return;
  19116. }
  19117. sliding = this.alignPlaylists(newDetails, curLevel.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  19118. }
  19119. // override level info
  19120. curLevel.details = newDetails;
  19121. this.levelLastLoaded = curLevel;
  19122. this.hls.trigger(Events.LEVEL_UPDATED, {
  19123. details: newDetails,
  19124. level: newLevelId
  19125. });
  19126. // only switch back to IDLE state if we were waiting for level to start downloading a new fragment
  19127. if (this.state === State.WAITING_LEVEL) {
  19128. if (this.waitForCdnTuneIn(newDetails)) {
  19129. // Wait for Low-Latency CDN Tune-in
  19130. return;
  19131. }
  19132. this.state = State.IDLE;
  19133. }
  19134. if (!this.startFragRequested) {
  19135. this.setStartPosition(newDetails, sliding);
  19136. } else if (newDetails.live) {
  19137. this.synchronizeToLiveEdge(newDetails);
  19138. }
  19139. // trigger handler right now
  19140. this.tick();
  19141. };
  19142. _proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(data) {
  19143. var _frag$initSegment;
  19144. var frag = data.frag,
  19145. part = data.part,
  19146. payload = data.payload;
  19147. var levels = this.levels;
  19148. if (!levels) {
  19149. this.warn("Levels were reset while fragment load was in progress. Fragment " + frag.sn + " of level " + frag.level + " will not be buffered");
  19150. return;
  19151. }
  19152. var currentLevel = levels[frag.level];
  19153. var details = currentLevel.details;
  19154. if (!details) {
  19155. this.warn("Dropping fragment " + frag.sn + " of level " + frag.level + " after level details were reset");
  19156. this.fragmentTracker.removeFragment(frag);
  19157. return;
  19158. }
  19159. var videoCodec = currentLevel.videoCodec;
  19160. // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
  19161. var accurateTimeOffset = details.PTSKnown || !details.live;
  19162. var initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data;
  19163. var audioCodec = this._getAudioCodec(currentLevel);
  19164. // transmux the MPEG-TS data to ISO-BMFF segments
  19165. // this.log(`Transmuxing ${frag.sn} of [${details.startSN} ,${details.endSN}],level ${frag.level}, cc ${frag.cc}`);
  19166. var transmuxer = this.transmuxer = this.transmuxer || new TransmuxerInterface(this.hls, PlaylistLevelType.MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
  19167. var partIndex = part ? part.index : -1;
  19168. var partial = partIndex !== -1;
  19169. var chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
  19170. var initPTS = this.initPTS[frag.cc];
  19171. transmuxer.push(payload, initSegmentData, audioCodec, videoCodec, frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
  19172. };
  19173. _proto.onAudioTrackSwitching = function onAudioTrackSwitching(event, data) {
  19174. // if any URL found on new audio track, it is an alternate audio track
  19175. var fromAltAudio = this.altAudio;
  19176. var altAudio = !!data.url;
  19177. // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered
  19178. // don't do anything if we switch to alt audio: audio stream controller is handling it.
  19179. // we will just have to change buffer scheduling on audioTrackSwitched
  19180. if (!altAudio) {
  19181. if (this.mediaBuffer !== this.media) {
  19182. this.log('Switching on main audio, use media.buffered to schedule main fragment loading');
  19183. this.mediaBuffer = this.media;
  19184. var fragCurrent = this.fragCurrent;
  19185. // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch
  19186. if (fragCurrent) {
  19187. this.log('Switching to main audio track, cancel main fragment load');
  19188. fragCurrent.abortRequests();
  19189. this.fragmentTracker.removeFragment(fragCurrent);
  19190. }
  19191. // destroy transmuxer to force init segment generation (following audio switch)
  19192. this.resetTransmuxer();
  19193. // switch to IDLE state to load new fragment
  19194. this.resetLoadingState();
  19195. } else if (this.audioOnly) {
  19196. // Reset audio transmuxer so when switching back to main audio we're not still appending where we left off
  19197. this.resetTransmuxer();
  19198. }
  19199. var hls = this.hls;
  19200. // If switching from alt to main audio, flush all audio and trigger track switched
  19201. if (fromAltAudio) {
  19202. hls.trigger(Events.BUFFER_FLUSHING, {
  19203. startOffset: 0,
  19204. endOffset: Number.POSITIVE_INFINITY,
  19205. type: null
  19206. });
  19207. this.fragmentTracker.removeAllFragments();
  19208. }
  19209. hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);
  19210. }
  19211. };
  19212. _proto.onAudioTrackSwitched = function onAudioTrackSwitched(event, data) {
  19213. var trackId = data.id;
  19214. var altAudio = !!this.hls.audioTracks[trackId].url;
  19215. if (altAudio) {
  19216. var videoBuffer = this.videoBuffer;
  19217. // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered
  19218. if (videoBuffer && this.mediaBuffer !== videoBuffer) {
  19219. this.log('Switching on alternate audio, use video.buffered to schedule main fragment loading');
  19220. this.mediaBuffer = videoBuffer;
  19221. }
  19222. }
  19223. this.altAudio = altAudio;
  19224. this.tick();
  19225. };
  19226. _proto.onBufferCreated = function onBufferCreated(event, data) {
  19227. var tracks = data.tracks;
  19228. var mediaTrack;
  19229. var name;
  19230. var alternate = false;
  19231. for (var type in tracks) {
  19232. var track = tracks[type];
  19233. if (track.id === 'main') {
  19234. name = type;
  19235. mediaTrack = track;
  19236. // keep video source buffer reference
  19237. if (type === 'video') {
  19238. var videoTrack = tracks[type];
  19239. if (videoTrack) {
  19240. this.videoBuffer = videoTrack.buffer;
  19241. }
  19242. }
  19243. } else {
  19244. alternate = true;
  19245. }
  19246. }
  19247. if (alternate && mediaTrack) {
  19248. this.log("Alternate track found, use " + name + ".buffered to schedule main fragment loading");
  19249. this.mediaBuffer = mediaTrack.buffer;
  19250. } else {
  19251. this.mediaBuffer = this.media;
  19252. }
  19253. };
  19254. _proto.onFragBuffered = function onFragBuffered(event, data) {
  19255. var frag = data.frag,
  19256. part = data.part;
  19257. if (frag && frag.type !== PlaylistLevelType.MAIN) {
  19258. return;
  19259. }
  19260. if (this.fragContextChanged(frag)) {
  19261. // If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion
  19262. // Avoid setting state back to IDLE, since that will interfere with a level switch
  19263. this.warn("Fragment " + frag.sn + (part ? ' p: ' + part.index : '') + " of level " + frag.level + " finished buffering, but was aborted. state: " + this.state);
  19264. if (this.state === State.PARSED) {
  19265. this.state = State.IDLE;
  19266. }
  19267. return;
  19268. }
  19269. var stats = part ? part.stats : frag.stats;
  19270. this.fragLastKbps = Math.round(8 * stats.total / (stats.buffering.end - stats.loading.first));
  19271. if (frag.sn !== 'initSegment') {
  19272. this.fragPrevious = frag;
  19273. }
  19274. this.fragBufferedComplete(frag, part);
  19275. };
  19276. _proto.onError = function onError(event, data) {
  19277. var _data$context;
  19278. if (data.fatal) {
  19279. this.state = State.ERROR;
  19280. return;
  19281. }
  19282. switch (data.details) {
  19283. case ErrorDetails.FRAG_GAP:
  19284. case ErrorDetails.FRAG_PARSING_ERROR:
  19285. case ErrorDetails.FRAG_DECRYPT_ERROR:
  19286. case ErrorDetails.FRAG_LOAD_ERROR:
  19287. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  19288. case ErrorDetails.KEY_LOAD_ERROR:
  19289. case ErrorDetails.KEY_LOAD_TIMEOUT:
  19290. this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN, data);
  19291. break;
  19292. case ErrorDetails.LEVEL_LOAD_ERROR:
  19293. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  19294. case ErrorDetails.LEVEL_PARSING_ERROR:
  19295. // in case of non fatal error while loading level, if level controller is not retrying to load level, switch back to IDLE
  19296. if (!data.levelRetry && this.state === State.WAITING_LEVEL && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.LEVEL) {
  19297. this.state = State.IDLE;
  19298. }
  19299. break;
  19300. case ErrorDetails.BUFFER_APPEND_ERROR:
  19301. case ErrorDetails.BUFFER_FULL_ERROR:
  19302. if (!data.parent || data.parent !== 'main') {
  19303. return;
  19304. }
  19305. if (data.details === ErrorDetails.BUFFER_APPEND_ERROR) {
  19306. this.resetLoadingState();
  19307. return;
  19308. }
  19309. if (this.reduceLengthAndFlushBuffer(data)) {
  19310. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  19311. }
  19312. break;
  19313. case ErrorDetails.INTERNAL_EXCEPTION:
  19314. this.recoverWorkerError(data);
  19315. break;
  19316. }
  19317. }
  19318. // Checks the health of the buffer and attempts to resolve playback stalls.
  19319. ;
  19320. _proto.checkBuffer = function checkBuffer() {
  19321. var media = this.media,
  19322. gapController = this.gapController;
  19323. if (!media || !gapController || !media.readyState) {
  19324. // Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)
  19325. return;
  19326. }
  19327. if (this.loadedmetadata || !BufferHelper.getBuffered(media).length) {
  19328. // Resolve gaps using the main buffer, whose ranges are the intersections of the A/V sourcebuffers
  19329. var activeFrag = this.state !== State.IDLE ? this.fragCurrent : null;
  19330. gapController.poll(this.lastCurrentTime, activeFrag);
  19331. }
  19332. this.lastCurrentTime = media.currentTime;
  19333. };
  19334. _proto.onFragLoadEmergencyAborted = function onFragLoadEmergencyAborted() {
  19335. this.state = State.IDLE;
  19336. // if loadedmetadata is not set, it means that we are emergency switch down on first frag
  19337. // in that case, reset startFragRequested flag
  19338. if (!this.loadedmetadata) {
  19339. this.startFragRequested = false;
  19340. this.nextLoadPosition = this.startPosition;
  19341. }
  19342. this.tickImmediate();
  19343. };
  19344. _proto.onBufferFlushed = function onBufferFlushed(event, _ref) {
  19345. var type = _ref.type;
  19346. if (type !== ElementaryStreamTypes.AUDIO || this.audioOnly && !this.altAudio) {
  19347. var mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  19348. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  19349. this.tick();
  19350. }
  19351. };
  19352. _proto.onLevelsUpdated = function onLevelsUpdated(event, data) {
  19353. if (this.level > -1 && this.fragCurrent) {
  19354. this.level = this.fragCurrent.level;
  19355. }
  19356. this.levels = data.levels;
  19357. };
  19358. _proto.swapAudioCodec = function swapAudioCodec() {
  19359. this.audioCodecSwap = !this.audioCodecSwap;
  19360. }
  19361. /**
  19362. * Seeks to the set startPosition if not equal to the mediaElement's current time.
  19363. */;
  19364. _proto.seekToStartPos = function seekToStartPos() {
  19365. var media = this.media;
  19366. if (!media) {
  19367. return;
  19368. }
  19369. var currentTime = media.currentTime;
  19370. var startPosition = this.startPosition;
  19371. // only adjust currentTime if different from startPosition or if startPosition not buffered
  19372. // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered
  19373. if (startPosition >= 0 && currentTime < startPosition) {
  19374. if (media.seeking) {
  19375. this.log("could not seek to " + startPosition + ", already seeking at " + currentTime);
  19376. return;
  19377. }
  19378. var buffered = BufferHelper.getBuffered(media);
  19379. var bufferStart = buffered.length ? buffered.start(0) : 0;
  19380. var delta = bufferStart - startPosition;
  19381. if (delta > 0 && (delta < this.config.maxBufferHole || delta < this.config.maxFragLookUpTolerance)) {
  19382. this.log("adjusting start position by " + delta + " to match buffer start");
  19383. startPosition += delta;
  19384. this.startPosition = startPosition;
  19385. }
  19386. this.log("seek to target start position " + startPosition + " from current time " + currentTime);
  19387. media.currentTime = startPosition;
  19388. }
  19389. };
  19390. _proto._getAudioCodec = function _getAudioCodec(currentLevel) {
  19391. var audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
  19392. if (this.audioCodecSwap && audioCodec) {
  19393. this.log('Swapping audio codec');
  19394. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  19395. audioCodec = 'mp4a.40.2';
  19396. } else {
  19397. audioCodec = 'mp4a.40.5';
  19398. }
  19399. }
  19400. return audioCodec;
  19401. };
  19402. _proto._loadBitrateTestFrag = function _loadBitrateTestFrag(frag, level) {
  19403. var _this2 = this;
  19404. frag.bitrateTest = true;
  19405. this._doFragLoad(frag, level).then(function (data) {
  19406. var hls = _this2.hls;
  19407. if (!data || _this2.fragContextChanged(frag)) {
  19408. return;
  19409. }
  19410. level.fragmentError = 0;
  19411. _this2.state = State.IDLE;
  19412. _this2.startFragRequested = false;
  19413. _this2.bitrateTest = false;
  19414. var stats = frag.stats;
  19415. // Bitrate tests fragments are neither parsed nor buffered
  19416. stats.parsing.start = stats.parsing.end = stats.buffering.start = stats.buffering.end = self.performance.now();
  19417. hls.trigger(Events.FRAG_LOADED, data);
  19418. frag.bitrateTest = false;
  19419. });
  19420. };
  19421. _proto._handleTransmuxComplete = function _handleTransmuxComplete(transmuxResult) {
  19422. var _id3$samples;
  19423. var id = 'main';
  19424. var hls = this.hls;
  19425. var remuxResult = transmuxResult.remuxResult,
  19426. chunkMeta = transmuxResult.chunkMeta;
  19427. var context = this.getCurrentContext(chunkMeta);
  19428. if (!context) {
  19429. this.resetWhenMissingContext(chunkMeta);
  19430. return;
  19431. }
  19432. var frag = context.frag,
  19433. part = context.part,
  19434. level = context.level;
  19435. var video = remuxResult.video,
  19436. text = remuxResult.text,
  19437. id3 = remuxResult.id3,
  19438. initSegment = remuxResult.initSegment;
  19439. var details = level.details;
  19440. // The audio-stream-controller handles audio buffering if Hls.js is playing an alternate audio track
  19441. var audio = this.altAudio ? undefined : remuxResult.audio;
  19442. // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.
  19443. // If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.
  19444. if (this.fragContextChanged(frag)) {
  19445. this.fragmentTracker.removeFragment(frag);
  19446. return;
  19447. }
  19448. this.state = State.PARSING;
  19449. if (initSegment) {
  19450. if (initSegment != null && initSegment.tracks) {
  19451. var mapFragment = frag.initSegment || frag;
  19452. this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta);
  19453. hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {
  19454. frag: mapFragment,
  19455. id: id,
  19456. tracks: initSegment.tracks
  19457. });
  19458. }
  19459. // This would be nice if Number.isFinite acted as a typeguard, but it doesn't. See: https://github.com/Microsoft/TypeScript/issues/10038
  19460. var initPTS = initSegment.initPTS;
  19461. var timescale = initSegment.timescale;
  19462. if (isFiniteNumber(initPTS)) {
  19463. this.initPTS[frag.cc] = {
  19464. baseTime: initPTS,
  19465. timescale: timescale
  19466. };
  19467. hls.trigger(Events.INIT_PTS_FOUND, {
  19468. frag: frag,
  19469. id: id,
  19470. initPTS: initPTS,
  19471. timescale: timescale
  19472. });
  19473. }
  19474. }
  19475. // Avoid buffering if backtracking this fragment
  19476. if (video && details && frag.sn !== 'initSegment') {
  19477. var prevFrag = details.fragments[frag.sn - 1 - details.startSN];
  19478. var isFirstFragment = frag.sn === details.startSN;
  19479. var isFirstInDiscontinuity = !prevFrag || frag.cc > prevFrag.cc;
  19480. if (remuxResult.independent !== false) {
  19481. var startPTS = video.startPTS,
  19482. endPTS = video.endPTS,
  19483. startDTS = video.startDTS,
  19484. endDTS = video.endDTS;
  19485. if (part) {
  19486. part.elementaryStreams[video.type] = {
  19487. startPTS: startPTS,
  19488. endPTS: endPTS,
  19489. startDTS: startDTS,
  19490. endDTS: endDTS
  19491. };
  19492. } else {
  19493. if (video.firstKeyFrame && video.independent && chunkMeta.id === 1 && !isFirstInDiscontinuity) {
  19494. this.couldBacktrack = true;
  19495. }
  19496. if (video.dropped && video.independent) {
  19497. // Backtrack if dropped frames create a gap after currentTime
  19498. var bufferInfo = this.getMainFwdBufferInfo();
  19499. var targetBufferTime = (bufferInfo ? bufferInfo.end : this.getLoadPosition()) + this.config.maxBufferHole;
  19500. var startTime = video.firstKeyFramePTS ? video.firstKeyFramePTS : startPTS;
  19501. if (!isFirstFragment && targetBufferTime < startTime - this.config.maxBufferHole && !isFirstInDiscontinuity) {
  19502. this.backtrack(frag);
  19503. return;
  19504. } else if (isFirstInDiscontinuity) {
  19505. // Mark segment with a gap to avoid loop loading
  19506. frag.gap = true;
  19507. }
  19508. // Set video stream start to fragment start so that truncated samples do not distort the timeline, and mark it partial
  19509. frag.setElementaryStreamInfo(video.type, frag.start, endPTS, frag.start, endDTS, true);
  19510. } else if (isFirstFragment && startPTS > MAX_START_GAP_JUMP) {
  19511. // Mark segment with a gap to skip large start gap
  19512. frag.gap = true;
  19513. }
  19514. }
  19515. frag.setElementaryStreamInfo(video.type, startPTS, endPTS, startDTS, endDTS);
  19516. if (this.backtrackFragment) {
  19517. this.backtrackFragment = frag;
  19518. }
  19519. this.bufferFragmentData(video, frag, part, chunkMeta, isFirstFragment || isFirstInDiscontinuity);
  19520. } else if (isFirstFragment || isFirstInDiscontinuity) {
  19521. // Mark segment with a gap to avoid loop loading
  19522. frag.gap = true;
  19523. } else {
  19524. this.backtrack(frag);
  19525. return;
  19526. }
  19527. }
  19528. if (audio) {
  19529. var _startPTS = audio.startPTS,
  19530. _endPTS = audio.endPTS,
  19531. _startDTS = audio.startDTS,
  19532. _endDTS = audio.endDTS;
  19533. if (part) {
  19534. part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {
  19535. startPTS: _startPTS,
  19536. endPTS: _endPTS,
  19537. startDTS: _startDTS,
  19538. endDTS: _endDTS
  19539. };
  19540. }
  19541. frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, _startPTS, _endPTS, _startDTS, _endDTS);
  19542. this.bufferFragmentData(audio, frag, part, chunkMeta);
  19543. }
  19544. if (details && id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) {
  19545. var emittedID3 = {
  19546. id: id,
  19547. frag: frag,
  19548. details: details,
  19549. samples: id3.samples
  19550. };
  19551. hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);
  19552. }
  19553. if (details && text) {
  19554. var emittedText = {
  19555. id: id,
  19556. frag: frag,
  19557. details: details,
  19558. samples: text.samples
  19559. };
  19560. hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);
  19561. }
  19562. };
  19563. _proto._bufferInitSegment = function _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
  19564. var _this3 = this;
  19565. if (this.state !== State.PARSING) {
  19566. return;
  19567. }
  19568. this.audioOnly = !!tracks.audio && !tracks.video;
  19569. // if audio track is expected to come from audio stream controller, discard any coming from main
  19570. if (this.altAudio && !this.audioOnly) {
  19571. delete tracks.audio;
  19572. }
  19573. // include levelCodec in audio and video tracks
  19574. var audio = tracks.audio,
  19575. video = tracks.video,
  19576. audiovideo = tracks.audiovideo;
  19577. if (audio) {
  19578. var audioCodec = currentLevel.audioCodec;
  19579. var ua = navigator.userAgent.toLowerCase();
  19580. if (this.audioCodecSwitch) {
  19581. if (audioCodec) {
  19582. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  19583. audioCodec = 'mp4a.40.2';
  19584. } else {
  19585. audioCodec = 'mp4a.40.5';
  19586. }
  19587. }
  19588. // In the case that AAC and HE-AAC audio codecs are signalled in manifest,
  19589. // force HE-AAC, as it seems that most browsers prefers it.
  19590. // don't force HE-AAC if mono stream, or in Firefox
  19591. var audioMetadata = audio.metadata;
  19592. if (audioMetadata && 'channelCount' in audioMetadata && (audioMetadata.channelCount || 1) !== 1 && ua.indexOf('firefox') === -1) {
  19593. audioCodec = 'mp4a.40.5';
  19594. }
  19595. }
  19596. // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise
  19597. if (audioCodec && audioCodec.indexOf('mp4a.40.5') !== -1 && ua.indexOf('android') !== -1 && audio.container !== 'audio/mpeg') {
  19598. // Exclude mpeg audio
  19599. audioCodec = 'mp4a.40.2';
  19600. this.log("Android: force audio codec to " + audioCodec);
  19601. }
  19602. if (currentLevel.audioCodec && currentLevel.audioCodec !== audioCodec) {
  19603. this.log("Swapping manifest audio codec \"" + currentLevel.audioCodec + "\" for \"" + audioCodec + "\"");
  19604. }
  19605. audio.levelCodec = audioCodec;
  19606. audio.id = 'main';
  19607. this.log("Init audio buffer, container:" + audio.container + ", codecs[selected/level/parsed]=[" + (audioCodec || '') + "/" + (currentLevel.audioCodec || '') + "/" + audio.codec + "]");
  19608. }
  19609. if (video) {
  19610. video.levelCodec = currentLevel.videoCodec;
  19611. video.id = 'main';
  19612. this.log("Init video buffer, container:" + video.container + ", codecs[level/parsed]=[" + (currentLevel.videoCodec || '') + "/" + video.codec + "]");
  19613. }
  19614. if (audiovideo) {
  19615. this.log("Init audiovideo buffer, container:" + audiovideo.container + ", codecs[level/parsed]=[" + currentLevel.codecs + "/" + audiovideo.codec + "]");
  19616. }
  19617. this.hls.trigger(Events.BUFFER_CODECS, tracks);
  19618. // loop through tracks that are going to be provided to bufferController
  19619. Object.keys(tracks).forEach(function (trackName) {
  19620. var track = tracks[trackName];
  19621. var initSegment = track.initSegment;
  19622. if (initSegment != null && initSegment.byteLength) {
  19623. _this3.hls.trigger(Events.BUFFER_APPENDING, {
  19624. type: trackName,
  19625. data: initSegment,
  19626. frag: frag,
  19627. part: null,
  19628. chunkMeta: chunkMeta,
  19629. parent: frag.type
  19630. });
  19631. }
  19632. });
  19633. // trigger handler right now
  19634. this.tickImmediate();
  19635. };
  19636. _proto.getMainFwdBufferInfo = function getMainFwdBufferInfo() {
  19637. return this.getFwdBufferInfo(this.mediaBuffer ? this.mediaBuffer : this.media, PlaylistLevelType.MAIN);
  19638. };
  19639. _proto.backtrack = function backtrack(frag) {
  19640. this.couldBacktrack = true;
  19641. // Causes findFragments to backtrack through fragments to find the keyframe
  19642. this.backtrackFragment = frag;
  19643. this.resetTransmuxer();
  19644. this.flushBufferGap(frag);
  19645. this.fragmentTracker.removeFragment(frag);
  19646. this.fragPrevious = null;
  19647. this.nextLoadPosition = frag.start;
  19648. this.state = State.IDLE;
  19649. };
  19650. _proto.checkFragmentChanged = function checkFragmentChanged() {
  19651. var video = this.media;
  19652. var fragPlayingCurrent = null;
  19653. if (video && video.readyState > 1 && video.seeking === false) {
  19654. var currentTime = video.currentTime;
  19655. /* if video element is in seeked state, currentTime can only increase.
  19656. (assuming that playback rate is positive ...)
  19657. As sometimes currentTime jumps back to zero after a
  19658. media decode error, check this, to avoid seeking back to
  19659. wrong position after a media decode error
  19660. */
  19661. if (BufferHelper.isBuffered(video, currentTime)) {
  19662. fragPlayingCurrent = this.getAppendedFrag(currentTime);
  19663. } else if (BufferHelper.isBuffered(video, currentTime + 0.1)) {
  19664. /* ensure that FRAG_CHANGED event is triggered at startup,
  19665. when first video frame is displayed and playback is paused.
  19666. add a tolerance of 100ms, in case current position is not buffered,
  19667. check if current pos+100ms is buffered and use that buffer range
  19668. for FRAG_CHANGED event reporting */
  19669. fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1);
  19670. }
  19671. if (fragPlayingCurrent) {
  19672. this.backtrackFragment = null;
  19673. var fragPlaying = this.fragPlaying;
  19674. var fragCurrentLevel = fragPlayingCurrent.level;
  19675. if (!fragPlaying || fragPlayingCurrent.sn !== fragPlaying.sn || fragPlaying.level !== fragCurrentLevel) {
  19676. this.fragPlaying = fragPlayingCurrent;
  19677. this.hls.trigger(Events.FRAG_CHANGED, {
  19678. frag: fragPlayingCurrent
  19679. });
  19680. if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) {
  19681. this.hls.trigger(Events.LEVEL_SWITCHED, {
  19682. level: fragCurrentLevel
  19683. });
  19684. }
  19685. }
  19686. }
  19687. }
  19688. };
  19689. _createClass(StreamController, [{
  19690. key: "nextLevel",
  19691. get: function get() {
  19692. var frag = this.nextBufferedFrag;
  19693. if (frag) {
  19694. return frag.level;
  19695. }
  19696. return -1;
  19697. }
  19698. }, {
  19699. key: "currentFrag",
  19700. get: function get() {
  19701. var media = this.media;
  19702. if (media) {
  19703. return this.fragPlaying || this.getAppendedFrag(media.currentTime);
  19704. }
  19705. return null;
  19706. }
  19707. }, {
  19708. key: "currentProgramDateTime",
  19709. get: function get() {
  19710. var media = this.media;
  19711. if (media) {
  19712. var currentTime = media.currentTime;
  19713. var frag = this.currentFrag;
  19714. if (frag && isFiniteNumber(currentTime) && isFiniteNumber(frag.programDateTime)) {
  19715. var epocMs = frag.programDateTime + (currentTime - frag.start) * 1000;
  19716. return new Date(epocMs);
  19717. }
  19718. }
  19719. return null;
  19720. }
  19721. }, {
  19722. key: "currentLevel",
  19723. get: function get() {
  19724. var frag = this.currentFrag;
  19725. if (frag) {
  19726. return frag.level;
  19727. }
  19728. return -1;
  19729. }
  19730. }, {
  19731. key: "nextBufferedFrag",
  19732. get: function get() {
  19733. var frag = this.currentFrag;
  19734. if (frag) {
  19735. return this.followingBufferedFrag(frag);
  19736. }
  19737. return null;
  19738. }
  19739. }, {
  19740. key: "forceStartLoad",
  19741. get: function get() {
  19742. return this._forceStartLoad;
  19743. }
  19744. }]);
  19745. return StreamController;
  19746. }(BaseStreamController);
  19747. /**
  19748. * The `Hls` class is the core of the HLS.js library used to instantiate player instances.
  19749. * @public
  19750. */
  19751. var Hls = /*#__PURE__*/function () {
  19752. /**
  19753. * Check if the required MediaSource Extensions are available.
  19754. */
  19755. Hls.isMSESupported = function isMSESupported$1() {
  19756. return isMSESupported();
  19757. }
  19758. /**
  19759. * Check if MediaSource Extensions are available and isTypeSupported checks pass for any baseline codecs.
  19760. */;
  19761. Hls.isSupported = function isSupported$1() {
  19762. return isSupported();
  19763. }
  19764. /**
  19765. * Get the MediaSource global used for MSE playback (ManagedMediaSource, MediaSource, or WebKitMediaSource).
  19766. */;
  19767. Hls.getMediaSource = function getMediaSource$1() {
  19768. return getMediaSource();
  19769. };
  19770. /**
  19771. * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
  19772. * @param userConfig - Configuration options applied over `Hls.DefaultConfig`
  19773. */
  19774. function Hls(userConfig) {
  19775. if (userConfig === void 0) {
  19776. userConfig = {};
  19777. }
  19778. /**
  19779. * The runtime configuration used by the player. At instantiation this is combination of `hls.userConfig` merged over `Hls.DefaultConfig`.
  19780. */
  19781. this.config = void 0;
  19782. /**
  19783. * The configuration object provided on player instantiation.
  19784. */
  19785. this.userConfig = void 0;
  19786. this.coreComponents = void 0;
  19787. this.networkControllers = void 0;
  19788. this.started = false;
  19789. this._emitter = new EventEmitter();
  19790. this._autoLevelCapping = -1;
  19791. this._maxHdcpLevel = null;
  19792. this.abrController = void 0;
  19793. this.bufferController = void 0;
  19794. this.capLevelController = void 0;
  19795. this.latencyController = void 0;
  19796. this.levelController = void 0;
  19797. this.streamController = void 0;
  19798. this.audioTrackController = void 0;
  19799. this.subtitleTrackController = void 0;
  19800. this.emeController = void 0;
  19801. this.cmcdController = void 0;
  19802. this._media = null;
  19803. this.url = null;
  19804. this.triggeringException = void 0;
  19805. enableLogs(userConfig.debug || false, 'Hls instance');
  19806. var config = this.config = mergeConfig(Hls.DefaultConfig, userConfig);
  19807. this.userConfig = userConfig;
  19808. if (config.progressive) {
  19809. enableStreamingMode(config);
  19810. }
  19811. // core controllers and network loaders
  19812. var ConfigAbrController = config.abrController,
  19813. ConfigBufferController = config.bufferController,
  19814. ConfigCapLevelController = config.capLevelController,
  19815. ConfigErrorController = config.errorController,
  19816. ConfigFpsController = config.fpsController;
  19817. var errorController = new ConfigErrorController(this);
  19818. var abrController = this.abrController = new ConfigAbrController(this);
  19819. var bufferController = this.bufferController = new ConfigBufferController(this);
  19820. var capLevelController = this.capLevelController = new ConfigCapLevelController(this);
  19821. var fpsController = new ConfigFpsController(this);
  19822. var playListLoader = new PlaylistLoader(this);
  19823. var id3TrackController = new ID3TrackController(this);
  19824. var ConfigContentSteeringController = config.contentSteeringController;
  19825. // ConentSteeringController is defined before LevelController to receive Multivariant Playlist events first
  19826. var contentSteering = ConfigContentSteeringController ? new ConfigContentSteeringController(this) : null;
  19827. var levelController = this.levelController = new LevelController(this, contentSteering);
  19828. // FragmentTracker must be defined before StreamController because the order of event handling is important
  19829. var fragmentTracker = new FragmentTracker(this);
  19830. var keyLoader = new KeyLoader(this.config);
  19831. var streamController = this.streamController = new StreamController(this, fragmentTracker, keyLoader);
  19832. // Cap level controller uses streamController to flush the buffer
  19833. capLevelController.setStreamController(streamController);
  19834. // fpsController uses streamController to switch when frames are being dropped
  19835. fpsController.setStreamController(streamController);
  19836. var networkControllers = [playListLoader, levelController, streamController];
  19837. if (contentSteering) {
  19838. networkControllers.splice(1, 0, contentSteering);
  19839. }
  19840. this.networkControllers = networkControllers;
  19841. var coreComponents = [abrController, bufferController, capLevelController, fpsController, id3TrackController, fragmentTracker];
  19842. this.audioTrackController = this.createController(config.audioTrackController, networkControllers);
  19843. var AudioStreamControllerClass = config.audioStreamController;
  19844. if (AudioStreamControllerClass) {
  19845. networkControllers.push(new AudioStreamControllerClass(this, fragmentTracker, keyLoader));
  19846. }
  19847. // subtitleTrackController must be defined before subtitleStreamController because the order of event handling is important
  19848. this.subtitleTrackController = this.createController(config.subtitleTrackController, networkControllers);
  19849. var SubtitleStreamControllerClass = config.subtitleStreamController;
  19850. if (SubtitleStreamControllerClass) {
  19851. networkControllers.push(new SubtitleStreamControllerClass(this, fragmentTracker, keyLoader));
  19852. }
  19853. this.createController(config.timelineController, coreComponents);
  19854. keyLoader.emeController = this.emeController = this.createController(config.emeController, coreComponents);
  19855. this.cmcdController = this.createController(config.cmcdController, coreComponents);
  19856. this.latencyController = this.createController(LatencyController, coreComponents);
  19857. this.coreComponents = coreComponents;
  19858. // Error controller handles errors before and after all other controllers
  19859. // This listener will be invoked after all other controllers error listeners
  19860. networkControllers.push(errorController);
  19861. var onErrorOut = errorController.onErrorOut;
  19862. if (typeof onErrorOut === 'function') {
  19863. this.on(Events.ERROR, onErrorOut, errorController);
  19864. }
  19865. }
  19866. var _proto = Hls.prototype;
  19867. _proto.createController = function createController(ControllerClass, components) {
  19868. if (ControllerClass) {
  19869. var controllerInstance = new ControllerClass(this);
  19870. if (components) {
  19871. components.push(controllerInstance);
  19872. }
  19873. return controllerInstance;
  19874. }
  19875. return null;
  19876. }
  19877. // Delegate the EventEmitter through the public API of Hls.js
  19878. ;
  19879. _proto.on = function on(event, listener, context) {
  19880. if (context === void 0) {
  19881. context = this;
  19882. }
  19883. this._emitter.on(event, listener, context);
  19884. };
  19885. _proto.once = function once(event, listener, context) {
  19886. if (context === void 0) {
  19887. context = this;
  19888. }
  19889. this._emitter.once(event, listener, context);
  19890. };
  19891. _proto.removeAllListeners = function removeAllListeners(event) {
  19892. this._emitter.removeAllListeners(event);
  19893. };
  19894. _proto.off = function off(event, listener, context, once) {
  19895. if (context === void 0) {
  19896. context = this;
  19897. }
  19898. this._emitter.off(event, listener, context, once);
  19899. };
  19900. _proto.listeners = function listeners(event) {
  19901. return this._emitter.listeners(event);
  19902. };
  19903. _proto.emit = function emit(event, name, eventObject) {
  19904. return this._emitter.emit(event, name, eventObject);
  19905. };
  19906. _proto.trigger = function trigger(event, eventObject) {
  19907. if (this.config.debug) {
  19908. return this.emit(event, event, eventObject);
  19909. } else {
  19910. try {
  19911. return this.emit(event, event, eventObject);
  19912. } catch (error) {
  19913. logger.error('An internal error happened while handling event ' + event + '. Error message: "' + error.message + '". Here is a stacktrace:', error);
  19914. // Prevent recursion in error event handlers that throw #5497
  19915. if (!this.triggeringException) {
  19916. this.triggeringException = true;
  19917. var fatal = event === Events.ERROR;
  19918. this.trigger(Events.ERROR, {
  19919. type: ErrorTypes.OTHER_ERROR,
  19920. details: ErrorDetails.INTERNAL_EXCEPTION,
  19921. fatal: fatal,
  19922. event: event,
  19923. error: error
  19924. });
  19925. this.triggeringException = false;
  19926. }
  19927. }
  19928. }
  19929. return false;
  19930. };
  19931. _proto.listenerCount = function listenerCount(event) {
  19932. return this._emitter.listenerCount(event);
  19933. }
  19934. /**
  19935. * Dispose of the instance
  19936. */;
  19937. _proto.destroy = function destroy() {
  19938. logger.log('destroy');
  19939. this.trigger(Events.DESTROYING, undefined);
  19940. this.detachMedia();
  19941. this.removeAllListeners();
  19942. this._autoLevelCapping = -1;
  19943. this.url = null;
  19944. this.networkControllers.forEach(function (component) {
  19945. return component.destroy();
  19946. });
  19947. this.networkControllers.length = 0;
  19948. this.coreComponents.forEach(function (component) {
  19949. return component.destroy();
  19950. });
  19951. this.coreComponents.length = 0;
  19952. // Remove any references that could be held in config options or callbacks
  19953. var config = this.config;
  19954. config.xhrSetup = config.fetchSetup = undefined;
  19955. // @ts-ignore
  19956. this.userConfig = null;
  19957. }
  19958. /**
  19959. * Attaches Hls.js to a media element
  19960. */;
  19961. _proto.attachMedia = function attachMedia(media) {
  19962. logger.log('attachMedia');
  19963. this._media = media;
  19964. this.trigger(Events.MEDIA_ATTACHING, {
  19965. media: media
  19966. });
  19967. }
  19968. /**
  19969. * Detach Hls.js from the media
  19970. */;
  19971. _proto.detachMedia = function detachMedia() {
  19972. logger.log('detachMedia');
  19973. this.trigger(Events.MEDIA_DETACHING, undefined);
  19974. this._media = null;
  19975. }
  19976. /**
  19977. * Set the source URL. Can be relative or absolute.
  19978. */;
  19979. _proto.loadSource = function loadSource(url) {
  19980. this.stopLoad();
  19981. var media = this.media;
  19982. var loadedSource = this.url;
  19983. var loadingSource = this.url = urlToolkitExports.buildAbsoluteURL(self.location.href, url, {
  19984. alwaysNormalize: true
  19985. });
  19986. this._autoLevelCapping = -1;
  19987. this._maxHdcpLevel = null;
  19988. logger.log("loadSource:" + loadingSource);
  19989. if (media && loadedSource && (loadedSource !== loadingSource || this.bufferController.hasSourceTypes())) {
  19990. this.detachMedia();
  19991. this.attachMedia(media);
  19992. }
  19993. // when attaching to a source URL, trigger a playlist load
  19994. this.trigger(Events.MANIFEST_LOADING, {
  19995. url: url
  19996. });
  19997. }
  19998. /**
  19999. * Start loading data from the stream source.
  20000. * Depending on default config, client starts loading automatically when a source is set.
  20001. *
  20002. * @param startPosition - Set the start position to stream from.
  20003. * Defaults to -1 (None: starts from earliest point)
  20004. */;
  20005. _proto.startLoad = function startLoad(startPosition) {
  20006. if (startPosition === void 0) {
  20007. startPosition = -1;
  20008. }
  20009. logger.log("startLoad(" + startPosition + ")");
  20010. this.started = true;
  20011. this.networkControllers.forEach(function (controller) {
  20012. controller.startLoad(startPosition);
  20013. });
  20014. }
  20015. /**
  20016. * Stop loading of any stream data.
  20017. */;
  20018. _proto.stopLoad = function stopLoad() {
  20019. logger.log('stopLoad');
  20020. this.started = false;
  20021. this.networkControllers.forEach(function (controller) {
  20022. controller.stopLoad();
  20023. });
  20024. }
  20025. /**
  20026. * Resumes stream controller segment loading if previously started.
  20027. */;
  20028. _proto.resumeBuffering = function resumeBuffering() {
  20029. if (this.started) {
  20030. this.networkControllers.forEach(function (controller) {
  20031. if ('fragmentLoader' in controller) {
  20032. controller.startLoad(-1);
  20033. }
  20034. });
  20035. }
  20036. }
  20037. /**
  20038. * Stops stream controller segment loading without changing 'started' state like stopLoad().
  20039. * This allows for media buffering to be paused without interupting playlist loading.
  20040. */;
  20041. _proto.pauseBuffering = function pauseBuffering() {
  20042. this.networkControllers.forEach(function (controller) {
  20043. if ('fragmentLoader' in controller) {
  20044. controller.stopLoad();
  20045. }
  20046. });
  20047. }
  20048. /**
  20049. * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
  20050. */;
  20051. _proto.swapAudioCodec = function swapAudioCodec() {
  20052. logger.log('swapAudioCodec');
  20053. this.streamController.swapAudioCodec();
  20054. }
  20055. /**
  20056. * When the media-element fails, this allows to detach and then re-attach it
  20057. * as one call (convenience method).
  20058. *
  20059. * Automatic recovery of media-errors by this process is configurable.
  20060. */;
  20061. _proto.recoverMediaError = function recoverMediaError() {
  20062. logger.log('recoverMediaError');
  20063. var media = this._media;
  20064. this.detachMedia();
  20065. if (media) {
  20066. this.attachMedia(media);
  20067. }
  20068. };
  20069. _proto.removeLevel = function removeLevel(levelIndex) {
  20070. this.levelController.removeLevel(levelIndex);
  20071. }
  20072. /**
  20073. * @returns an array of levels (variants) sorted by HDCP-LEVEL, RESOLUTION (height), FRAME-RATE, CODECS, VIDEO-RANGE, and BANDWIDTH
  20074. */;
  20075. /**
  20076. * Find and select the best matching audio track, making a level switch when a Group change is necessary.
  20077. * Updates `hls.config.audioPreference`. Returns the selected track, or null when no matching track is found.
  20078. */
  20079. _proto.setAudioOption = function setAudioOption(audioOption) {
  20080. var _this$audioTrackContr;
  20081. return (_this$audioTrackContr = this.audioTrackController) == null ? void 0 : _this$audioTrackContr.setAudioOption(audioOption);
  20082. }
  20083. /**
  20084. * Find and select the best matching subtitle track, making a level switch when a Group change is necessary.
  20085. * Updates `hls.config.subtitlePreference`. Returns the selected track, or null when no matching track is found.
  20086. */;
  20087. _proto.setSubtitleOption = function setSubtitleOption(subtitleOption) {
  20088. var _this$subtitleTrackCo;
  20089. (_this$subtitleTrackCo = this.subtitleTrackController) == null ? void 0 : _this$subtitleTrackCo.setSubtitleOption(subtitleOption);
  20090. return null;
  20091. }
  20092. /**
  20093. * Get the complete list of audio tracks across all media groups
  20094. */;
  20095. _createClass(Hls, [{
  20096. key: "levels",
  20097. get: function get() {
  20098. var levels = this.levelController.levels;
  20099. return levels ? levels : [];
  20100. }
  20101. /**
  20102. * Index of quality level (variant) currently played
  20103. */
  20104. }, {
  20105. key: "currentLevel",
  20106. get: function get() {
  20107. return this.streamController.currentLevel;
  20108. }
  20109. /**
  20110. * 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.
  20111. */,
  20112. set: function set(newLevel) {
  20113. logger.log("set currentLevel:" + newLevel);
  20114. this.levelController.manualLevel = newLevel;
  20115. this.streamController.immediateLevelSwitch();
  20116. }
  20117. /**
  20118. * Index of next quality level loaded as scheduled by stream controller.
  20119. */
  20120. }, {
  20121. key: "nextLevel",
  20122. get: function get() {
  20123. return this.streamController.nextLevel;
  20124. }
  20125. /**
  20126. * Set quality level index for next loaded data.
  20127. * This will switch the video quality asap, without interrupting playback.
  20128. * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
  20129. * @param newLevel - Pass -1 for automatic level selection
  20130. */,
  20131. set: function set(newLevel) {
  20132. logger.log("set nextLevel:" + newLevel);
  20133. this.levelController.manualLevel = newLevel;
  20134. this.streamController.nextLevelSwitch();
  20135. }
  20136. /**
  20137. * Return the quality level of the currently or last (of none is loaded currently) segment
  20138. */
  20139. }, {
  20140. key: "loadLevel",
  20141. get: function get() {
  20142. return this.levelController.level;
  20143. }
  20144. /**
  20145. * Set quality level index for next loaded data in a conservative way.
  20146. * This will switch the quality without flushing, but interrupt current loading.
  20147. * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
  20148. * @param newLevel - Pass -1 for automatic level selection
  20149. */,
  20150. set: function set(newLevel) {
  20151. logger.log("set loadLevel:" + newLevel);
  20152. this.levelController.manualLevel = newLevel;
  20153. }
  20154. /**
  20155. * get next quality level loaded
  20156. */
  20157. }, {
  20158. key: "nextLoadLevel",
  20159. get: function get() {
  20160. return this.levelController.nextLoadLevel;
  20161. }
  20162. /**
  20163. * Set quality level of next loaded segment in a fully "non-destructive" way.
  20164. * Same as `loadLevel` but will wait for next switch (until current loading is done).
  20165. */,
  20166. set: function set(level) {
  20167. this.levelController.nextLoadLevel = level;
  20168. }
  20169. /**
  20170. * Return "first level": like a default level, if not set,
  20171. * falls back to index of first level referenced in manifest
  20172. */
  20173. }, {
  20174. key: "firstLevel",
  20175. get: function get() {
  20176. return Math.max(this.levelController.firstLevel, this.minAutoLevel);
  20177. }
  20178. /**
  20179. * Sets "first-level", see getter.
  20180. */,
  20181. set: function set(newLevel) {
  20182. logger.log("set firstLevel:" + newLevel);
  20183. this.levelController.firstLevel = newLevel;
  20184. }
  20185. /**
  20186. * Return the desired start level for the first fragment that will be loaded.
  20187. * The default value of -1 indicates automatic start level selection.
  20188. * Setting hls.nextAutoLevel without setting a startLevel will result in
  20189. * the nextAutoLevel value being used for one fragment load.
  20190. */
  20191. }, {
  20192. key: "startLevel",
  20193. get: function get() {
  20194. var startLevel = this.levelController.startLevel;
  20195. if (startLevel === -1 && this.abrController.forcedAutoLevel > -1) {
  20196. return this.abrController.forcedAutoLevel;
  20197. }
  20198. return startLevel;
  20199. }
  20200. /**
  20201. * set start level (level of first fragment that will be played back)
  20202. * if not overrided by user, first level appearing in manifest will be used as start level
  20203. * if -1 : automatic start level selection, playback will start from level matching download bandwidth
  20204. * (determined from download of first segment)
  20205. */,
  20206. set: function set(newLevel) {
  20207. logger.log("set startLevel:" + newLevel);
  20208. // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel
  20209. if (newLevel !== -1) {
  20210. newLevel = Math.max(newLevel, this.minAutoLevel);
  20211. }
  20212. this.levelController.startLevel = newLevel;
  20213. }
  20214. /**
  20215. * Whether level capping is enabled.
  20216. * Default value is set via `config.capLevelToPlayerSize`.
  20217. */
  20218. }, {
  20219. key: "capLevelToPlayerSize",
  20220. get: function get() {
  20221. return this.config.capLevelToPlayerSize;
  20222. }
  20223. /**
  20224. * Enables or disables level capping. If disabled after previously enabled, `nextLevelSwitch` will be immediately called.
  20225. */,
  20226. set: function set(shouldStartCapping) {
  20227. var newCapLevelToPlayerSize = !!shouldStartCapping;
  20228. if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {
  20229. if (newCapLevelToPlayerSize) {
  20230. this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size.
  20231. } else {
  20232. this.capLevelController.stopCapping();
  20233. this.autoLevelCapping = -1;
  20234. this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap.
  20235. }
  20236. this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;
  20237. }
  20238. }
  20239. /**
  20240. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  20241. */
  20242. }, {
  20243. key: "autoLevelCapping",
  20244. get: function get() {
  20245. return this._autoLevelCapping;
  20246. }
  20247. /**
  20248. * Returns the current bandwidth estimate in bits per second, when available. Otherwise, `NaN` is returned.
  20249. */,
  20250. set:
  20251. /**
  20252. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  20253. */
  20254. function set(newLevel) {
  20255. if (this._autoLevelCapping !== newLevel) {
  20256. logger.log("set autoLevelCapping:" + newLevel);
  20257. this._autoLevelCapping = newLevel;
  20258. this.levelController.checkMaxAutoUpdated();
  20259. }
  20260. }
  20261. }, {
  20262. key: "bandwidthEstimate",
  20263. get: function get() {
  20264. var bwEstimator = this.abrController.bwEstimator;
  20265. if (!bwEstimator) {
  20266. return NaN;
  20267. }
  20268. return bwEstimator.getEstimate();
  20269. },
  20270. set: function set(abrEwmaDefaultEstimate) {
  20271. this.abrController.resetEstimator(abrEwmaDefaultEstimate);
  20272. }
  20273. /**
  20274. * get time to first byte estimate
  20275. * @type {number}
  20276. */
  20277. }, {
  20278. key: "ttfbEstimate",
  20279. get: function get() {
  20280. var bwEstimator = this.abrController.bwEstimator;
  20281. if (!bwEstimator) {
  20282. return NaN;
  20283. }
  20284. return bwEstimator.getEstimateTTFB();
  20285. }
  20286. }, {
  20287. key: "maxHdcpLevel",
  20288. get: function get() {
  20289. return this._maxHdcpLevel;
  20290. },
  20291. set: function set(value) {
  20292. if (isHdcpLevel(value) && this._maxHdcpLevel !== value) {
  20293. this._maxHdcpLevel = value;
  20294. this.levelController.checkMaxAutoUpdated();
  20295. }
  20296. }
  20297. /**
  20298. * True when automatic level selection enabled
  20299. */
  20300. }, {
  20301. key: "autoLevelEnabled",
  20302. get: function get() {
  20303. return this.levelController.manualLevel === -1;
  20304. }
  20305. /**
  20306. * Level set manually (if any)
  20307. */
  20308. }, {
  20309. key: "manualLevel",
  20310. get: function get() {
  20311. return this.levelController.manualLevel;
  20312. }
  20313. /**
  20314. * min level selectable in auto mode according to config.minAutoBitrate
  20315. */
  20316. }, {
  20317. key: "minAutoLevel",
  20318. get: function get() {
  20319. var levels = this.levels,
  20320. minAutoBitrate = this.config.minAutoBitrate;
  20321. if (!levels) return 0;
  20322. var len = levels.length;
  20323. for (var i = 0; i < len; i++) {
  20324. if (levels[i].maxBitrate >= minAutoBitrate) {
  20325. return i;
  20326. }
  20327. }
  20328. return 0;
  20329. }
  20330. /**
  20331. * max level selectable in auto mode according to autoLevelCapping
  20332. */
  20333. }, {
  20334. key: "maxAutoLevel",
  20335. get: function get() {
  20336. var levels = this.levels,
  20337. autoLevelCapping = this.autoLevelCapping,
  20338. maxHdcpLevel = this.maxHdcpLevel;
  20339. var maxAutoLevel;
  20340. if (autoLevelCapping === -1 && levels != null && levels.length) {
  20341. maxAutoLevel = levels.length - 1;
  20342. } else {
  20343. maxAutoLevel = autoLevelCapping;
  20344. }
  20345. if (maxHdcpLevel) {
  20346. for (var i = maxAutoLevel; i--;) {
  20347. var hdcpLevel = levels[i].attrs['HDCP-LEVEL'];
  20348. if (hdcpLevel && hdcpLevel <= maxHdcpLevel) {
  20349. return i;
  20350. }
  20351. }
  20352. }
  20353. return maxAutoLevel;
  20354. }
  20355. }, {
  20356. key: "firstAutoLevel",
  20357. get: function get() {
  20358. return this.abrController.firstAutoLevel;
  20359. }
  20360. /**
  20361. * next automatically selected quality level
  20362. */
  20363. }, {
  20364. key: "nextAutoLevel",
  20365. get: function get() {
  20366. return this.abrController.nextAutoLevel;
  20367. }
  20368. /**
  20369. * this setter is used to force next auto level.
  20370. * this is useful to force a switch down in auto mode:
  20371. * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
  20372. * forced value is valid for one fragment. upon successful frag loading at forced level,
  20373. * this value will be resetted to -1 by ABR controller.
  20374. */,
  20375. set: function set(nextLevel) {
  20376. this.abrController.nextAutoLevel = nextLevel;
  20377. }
  20378. /**
  20379. * get the datetime value relative to media.currentTime for the active level Program Date Time if present
  20380. */
  20381. }, {
  20382. key: "playingDate",
  20383. get: function get() {
  20384. return this.streamController.currentProgramDateTime;
  20385. }
  20386. }, {
  20387. key: "mainForwardBufferInfo",
  20388. get: function get() {
  20389. return this.streamController.getMainFwdBufferInfo();
  20390. }
  20391. }, {
  20392. key: "allAudioTracks",
  20393. get: function get() {
  20394. var audioTrackController = this.audioTrackController;
  20395. return audioTrackController ? audioTrackController.allAudioTracks : [];
  20396. }
  20397. /**
  20398. * Get the list of selectable audio tracks
  20399. */
  20400. }, {
  20401. key: "audioTracks",
  20402. get: function get() {
  20403. var audioTrackController = this.audioTrackController;
  20404. return audioTrackController ? audioTrackController.audioTracks : [];
  20405. }
  20406. /**
  20407. * index of the selected audio track (index in audio track lists)
  20408. */
  20409. }, {
  20410. key: "audioTrack",
  20411. get: function get() {
  20412. var audioTrackController = this.audioTrackController;
  20413. return audioTrackController ? audioTrackController.audioTrack : -1;
  20414. }
  20415. /**
  20416. * selects an audio track, based on its index in audio track lists
  20417. */,
  20418. set: function set(audioTrackId) {
  20419. var audioTrackController = this.audioTrackController;
  20420. if (audioTrackController) {
  20421. audioTrackController.audioTrack = audioTrackId;
  20422. }
  20423. }
  20424. /**
  20425. * get the complete list of subtitle tracks across all media groups
  20426. */
  20427. }, {
  20428. key: "allSubtitleTracks",
  20429. get: function get() {
  20430. var subtitleTrackController = this.subtitleTrackController;
  20431. return subtitleTrackController ? subtitleTrackController.allSubtitleTracks : [];
  20432. }
  20433. /**
  20434. * get alternate subtitle tracks list from playlist
  20435. */
  20436. }, {
  20437. key: "subtitleTracks",
  20438. get: function get() {
  20439. var subtitleTrackController = this.subtitleTrackController;
  20440. return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
  20441. }
  20442. /**
  20443. * index of the selected subtitle track (index in subtitle track lists)
  20444. */
  20445. }, {
  20446. key: "subtitleTrack",
  20447. get: function get() {
  20448. var subtitleTrackController = this.subtitleTrackController;
  20449. return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
  20450. },
  20451. set:
  20452. /**
  20453. * select an subtitle track, based on its index in subtitle track lists
  20454. */
  20455. function set(subtitleTrackId) {
  20456. var subtitleTrackController = this.subtitleTrackController;
  20457. if (subtitleTrackController) {
  20458. subtitleTrackController.subtitleTrack = subtitleTrackId;
  20459. }
  20460. }
  20461. /**
  20462. * Whether subtitle display is enabled or not
  20463. */
  20464. }, {
  20465. key: "media",
  20466. get: function get() {
  20467. return this._media;
  20468. }
  20469. }, {
  20470. key: "subtitleDisplay",
  20471. get: function get() {
  20472. var subtitleTrackController = this.subtitleTrackController;
  20473. return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
  20474. }
  20475. /**
  20476. * Enable/disable subtitle display rendering
  20477. */,
  20478. set: function set(value) {
  20479. var subtitleTrackController = this.subtitleTrackController;
  20480. if (subtitleTrackController) {
  20481. subtitleTrackController.subtitleDisplay = value;
  20482. }
  20483. }
  20484. /**
  20485. * get mode for Low-Latency HLS loading
  20486. */
  20487. }, {
  20488. key: "lowLatencyMode",
  20489. get: function get() {
  20490. return this.config.lowLatencyMode;
  20491. }
  20492. /**
  20493. * Enable/disable Low-Latency HLS part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK.
  20494. */,
  20495. set: function set(mode) {
  20496. this.config.lowLatencyMode = mode;
  20497. }
  20498. /**
  20499. * Position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```hls.config.liveSyncDuration```)
  20500. * @returns null prior to loading live Playlist
  20501. */
  20502. }, {
  20503. key: "liveSyncPosition",
  20504. get: function get() {
  20505. return this.latencyController.liveSyncPosition;
  20506. }
  20507. /**
  20508. * Estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced)
  20509. * @returns 0 before first playlist is loaded
  20510. */
  20511. }, {
  20512. key: "latency",
  20513. get: function get() {
  20514. return this.latencyController.latency;
  20515. }
  20516. /**
  20517. * maximum distance from the edge before the player seeks forward to ```hls.liveSyncPosition```
  20518. * configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration```
  20519. * @returns 0 before first playlist is loaded
  20520. */
  20521. }, {
  20522. key: "maxLatency",
  20523. get: function get() {
  20524. return this.latencyController.maxLatency;
  20525. }
  20526. /**
  20527. * target distance from the edge as calculated by the latency controller
  20528. */
  20529. }, {
  20530. key: "targetLatency",
  20531. get: function get() {
  20532. return this.latencyController.targetLatency;
  20533. }
  20534. /**
  20535. * the rate at which the edge of the current live playlist is advancing or 1 if there is none
  20536. */
  20537. }, {
  20538. key: "drift",
  20539. get: function get() {
  20540. return this.latencyController.drift;
  20541. }
  20542. /**
  20543. * set to true when startLoad is called before MANIFEST_PARSED event
  20544. */
  20545. }, {
  20546. key: "forceStartLoad",
  20547. get: function get() {
  20548. return this.streamController.forceStartLoad;
  20549. }
  20550. }], [{
  20551. key: "version",
  20552. get:
  20553. /**
  20554. * Get the video-dev/hls.js package version.
  20555. */
  20556. function get() {
  20557. return "1.5.15";
  20558. }
  20559. }, {
  20560. key: "Events",
  20561. get: function get() {
  20562. return Events;
  20563. }
  20564. }, {
  20565. key: "ErrorTypes",
  20566. get: function get() {
  20567. return ErrorTypes;
  20568. }
  20569. }, {
  20570. key: "ErrorDetails",
  20571. get: function get() {
  20572. return ErrorDetails;
  20573. }
  20574. /**
  20575. * Get the default configuration applied to new instances.
  20576. */
  20577. }, {
  20578. key: "DefaultConfig",
  20579. get: function get() {
  20580. if (!Hls.defaultConfig) {
  20581. return hlsDefaultConfig;
  20582. }
  20583. return Hls.defaultConfig;
  20584. }
  20585. /**
  20586. * Replace the default configuration applied to new instances.
  20587. */,
  20588. set: function set(defaultConfig) {
  20589. Hls.defaultConfig = defaultConfig;
  20590. }
  20591. }]);
  20592. return Hls;
  20593. }();
  20594. Hls.defaultConfig = void 0;
  20595. return Hls;
  20596. }));
  20597. })(false);
  20598. //# sourceMappingURL=hls.light.js.map