hls.light.js 807 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109
  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.11");
  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. logger.error("[eme] missing 'schm' box");
  1930. return null;
  1931. }
  1932. /**
  1933. * Determine the base media decode start time, in seconds, for an MP4
  1934. * fragment. If multiple fragments are specified, the earliest time is
  1935. * returned.
  1936. *
  1937. * The base media decode time can be parsed from track fragment
  1938. * metadata:
  1939. * ```
  1940. * moof > traf > tfdt.baseMediaDecodeTime
  1941. * ```
  1942. * It requires the timescale value from the mdhd to interpret.
  1943. *
  1944. * @param initData - a hash of track type to timescale values
  1945. * @param fmp4 - the bytes of the mp4 fragment
  1946. * @returns the earliest base media decode start time for the
  1947. * fragment, in seconds
  1948. */
  1949. function getStartDTS(initData, fmp4) {
  1950. // we need info from two children of each track fragment box
  1951. return findBox(fmp4, ['moof', 'traf']).reduce(function (result, traf) {
  1952. var tfdt = findBox(traf, ['tfdt'])[0];
  1953. var version = tfdt[0];
  1954. var start = findBox(traf, ['tfhd']).reduce(function (result, tfhd) {
  1955. // get the track id from the tfhd
  1956. var id = readUint32(tfhd, 4);
  1957. var track = initData[id];
  1958. if (track) {
  1959. var baseTime = readUint32(tfdt, 4);
  1960. if (version === 1) {
  1961. // If value is too large, assume signed 64-bit. Negative track fragment decode times are invalid, but they exist in the wild.
  1962. // This prevents large values from being used for initPTS, which can cause playlist sync issues.
  1963. // https://github.com/video-dev/hls.js/issues/5303
  1964. if (baseTime === UINT32_MAX$1) {
  1965. logger.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time");
  1966. return result;
  1967. }
  1968. baseTime *= UINT32_MAX$1 + 1;
  1969. baseTime += readUint32(tfdt, 8);
  1970. }
  1971. // assume a 90kHz clock if no timescale was specified
  1972. var scale = track.timescale || 90e3;
  1973. // convert base time to seconds
  1974. var startTime = baseTime / scale;
  1975. if (isFiniteNumber(startTime) && (result === null || startTime < result)) {
  1976. return startTime;
  1977. }
  1978. }
  1979. return result;
  1980. }, null);
  1981. if (start !== null && isFiniteNumber(start) && (result === null || start < result)) {
  1982. return start;
  1983. }
  1984. return result;
  1985. }, null);
  1986. }
  1987. /*
  1988. For Reference:
  1989. aligned(8) class TrackFragmentHeaderBox
  1990. extends FullBox(‘tfhd’, 0, tf_flags){
  1991. unsigned int(32) track_ID;
  1992. // all the following are optional fields
  1993. unsigned int(64) base_data_offset;
  1994. unsigned int(32) sample_description_index;
  1995. unsigned int(32) default_sample_duration;
  1996. unsigned int(32) default_sample_size;
  1997. unsigned int(32) default_sample_flags
  1998. }
  1999. */
  2000. function getDuration(data, initData) {
  2001. var rawDuration = 0;
  2002. var videoDuration = 0;
  2003. var audioDuration = 0;
  2004. var trafs = findBox(data, ['moof', 'traf']);
  2005. for (var i = 0; i < trafs.length; i++) {
  2006. var traf = trafs[i];
  2007. // There is only one tfhd & trun per traf
  2008. // This is true for CMAF style content, and we should perhaps check the ftyp
  2009. // and only look for a single trun then, but for ISOBMFF we should check
  2010. // for multiple track runs.
  2011. var tfhd = findBox(traf, ['tfhd'])[0];
  2012. // get the track id from the tfhd
  2013. var id = readUint32(tfhd, 4);
  2014. var track = initData[id];
  2015. if (!track) {
  2016. continue;
  2017. }
  2018. var trackDefault = track.default;
  2019. var tfhdFlags = readUint32(tfhd, 0) | (trackDefault == null ? void 0 : trackDefault.flags);
  2020. var sampleDuration = trackDefault == null ? void 0 : trackDefault.duration;
  2021. if (tfhdFlags & 0x000008) {
  2022. // 0x000008 indicates the presence of the default_sample_duration field
  2023. if (tfhdFlags & 0x000002) {
  2024. // 0x000002 indicates the presence of the sample_description_index field, which precedes default_sample_duration
  2025. // If present, the default_sample_duration exists at byte offset 12
  2026. sampleDuration = readUint32(tfhd, 12);
  2027. } else {
  2028. // Otherwise, the duration is at byte offset 8
  2029. sampleDuration = readUint32(tfhd, 8);
  2030. }
  2031. }
  2032. // assume a 90kHz clock if no timescale was specified
  2033. var timescale = track.timescale || 90e3;
  2034. var truns = findBox(traf, ['trun']);
  2035. for (var j = 0; j < truns.length; j++) {
  2036. rawDuration = computeRawDurationFromSamples(truns[j]);
  2037. if (!rawDuration && sampleDuration) {
  2038. var sampleCount = readUint32(truns[j], 4);
  2039. rawDuration = sampleDuration * sampleCount;
  2040. }
  2041. if (track.type === ElementaryStreamTypes.VIDEO) {
  2042. videoDuration += rawDuration / timescale;
  2043. } else if (track.type === ElementaryStreamTypes.AUDIO) {
  2044. audioDuration += rawDuration / timescale;
  2045. }
  2046. }
  2047. }
  2048. if (videoDuration === 0 && audioDuration === 0) {
  2049. // If duration samples are not available in the traf use sidx subsegment_duration
  2050. var sidxMinStart = Infinity;
  2051. var sidxMaxEnd = 0;
  2052. var sidxDuration = 0;
  2053. var sidxs = findBox(data, ['sidx']);
  2054. for (var _i2 = 0; _i2 < sidxs.length; _i2++) {
  2055. var sidx = parseSegmentIndex(sidxs[_i2]);
  2056. if (sidx != null && sidx.references) {
  2057. sidxMinStart = Math.min(sidxMinStart, sidx.earliestPresentationTime / sidx.timescale);
  2058. var subSegmentDuration = sidx.references.reduce(function (dur, ref) {
  2059. return dur + ref.info.duration || 0;
  2060. }, 0);
  2061. sidxMaxEnd = Math.max(sidxMaxEnd, subSegmentDuration + sidx.earliestPresentationTime / sidx.timescale);
  2062. sidxDuration = sidxMaxEnd - sidxMinStart;
  2063. }
  2064. }
  2065. if (sidxDuration && isFiniteNumber(sidxDuration)) {
  2066. return sidxDuration;
  2067. }
  2068. }
  2069. if (videoDuration) {
  2070. return videoDuration;
  2071. }
  2072. return audioDuration;
  2073. }
  2074. /*
  2075. For Reference:
  2076. aligned(8) class TrackRunBox
  2077. extends FullBox(‘trun’, version, tr_flags) {
  2078. unsigned int(32) sample_count;
  2079. // the following are optional fields
  2080. signed int(32) data_offset;
  2081. unsigned int(32) first_sample_flags;
  2082. // all fields in the following array are optional
  2083. {
  2084. unsigned int(32) sample_duration;
  2085. unsigned int(32) sample_size;
  2086. unsigned int(32) sample_flags
  2087. if (version == 0)
  2088. { unsigned int(32)
  2089. else
  2090. { signed int(32)
  2091. }[ sample_count ]
  2092. }
  2093. */
  2094. function computeRawDurationFromSamples(trun) {
  2095. var flags = readUint32(trun, 0);
  2096. // Flags are at offset 0, non-optional sample_count is at offset 4. Therefore we start 8 bytes in.
  2097. // Each field is an int32, which is 4 bytes
  2098. var offset = 8;
  2099. // data-offset-present flag
  2100. if (flags & 0x000001) {
  2101. offset += 4;
  2102. }
  2103. // first-sample-flags-present flag
  2104. if (flags & 0x000004) {
  2105. offset += 4;
  2106. }
  2107. var duration = 0;
  2108. var sampleCount = readUint32(trun, 4);
  2109. for (var i = 0; i < sampleCount; i++) {
  2110. // sample-duration-present flag
  2111. if (flags & 0x000100) {
  2112. var sampleDuration = readUint32(trun, offset);
  2113. duration += sampleDuration;
  2114. offset += 4;
  2115. }
  2116. // sample-size-present flag
  2117. if (flags & 0x000200) {
  2118. offset += 4;
  2119. }
  2120. // sample-flags-present flag
  2121. if (flags & 0x000400) {
  2122. offset += 4;
  2123. }
  2124. // sample-composition-time-offsets-present flag
  2125. if (flags & 0x000800) {
  2126. offset += 4;
  2127. }
  2128. }
  2129. return duration;
  2130. }
  2131. function offsetStartDTS(initData, fmp4, timeOffset) {
  2132. findBox(fmp4, ['moof', 'traf']).forEach(function (traf) {
  2133. findBox(traf, ['tfhd']).forEach(function (tfhd) {
  2134. // get the track id from the tfhd
  2135. var id = readUint32(tfhd, 4);
  2136. var track = initData[id];
  2137. if (!track) {
  2138. return;
  2139. }
  2140. // assume a 90kHz clock if no timescale was specified
  2141. var timescale = track.timescale || 90e3;
  2142. // get the base media decode time from the tfdt
  2143. findBox(traf, ['tfdt']).forEach(function (tfdt) {
  2144. var version = tfdt[0];
  2145. var offset = timeOffset * timescale;
  2146. if (offset) {
  2147. var baseMediaDecodeTime = readUint32(tfdt, 4);
  2148. if (version === 0) {
  2149. baseMediaDecodeTime -= offset;
  2150. baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);
  2151. writeUint32(tfdt, 4, baseMediaDecodeTime);
  2152. } else {
  2153. baseMediaDecodeTime *= Math.pow(2, 32);
  2154. baseMediaDecodeTime += readUint32(tfdt, 8);
  2155. baseMediaDecodeTime -= offset;
  2156. baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);
  2157. var upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX$1 + 1));
  2158. var lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX$1 + 1));
  2159. writeUint32(tfdt, 4, upper);
  2160. writeUint32(tfdt, 8, lower);
  2161. }
  2162. }
  2163. });
  2164. });
  2165. });
  2166. }
  2167. // TODO: Check if the last moof+mdat pair is part of the valid range
  2168. function segmentValidRange(data) {
  2169. var segmentedRange = {
  2170. valid: null,
  2171. remainder: null
  2172. };
  2173. var moofs = findBox(data, ['moof']);
  2174. if (moofs.length < 2) {
  2175. segmentedRange.remainder = data;
  2176. return segmentedRange;
  2177. }
  2178. var last = moofs[moofs.length - 1];
  2179. // Offset by 8 bytes; findBox offsets the start by as much
  2180. segmentedRange.valid = sliceUint8(data, 0, last.byteOffset - 8);
  2181. segmentedRange.remainder = sliceUint8(data, last.byteOffset - 8);
  2182. return segmentedRange;
  2183. }
  2184. function appendUint8Array(data1, data2) {
  2185. var temp = new Uint8Array(data1.length + data2.length);
  2186. temp.set(data1);
  2187. temp.set(data2, data1.length);
  2188. return temp;
  2189. }
  2190. function parseSamples(timeOffset, track) {
  2191. var seiSamples = [];
  2192. var videoData = track.samples;
  2193. var timescale = track.timescale;
  2194. var trackId = track.id;
  2195. var isHEVCFlavor = false;
  2196. var moofs = findBox(videoData, ['moof']);
  2197. moofs.map(function (moof) {
  2198. var moofOffset = moof.byteOffset - 8;
  2199. var trafs = findBox(moof, ['traf']);
  2200. trafs.map(function (traf) {
  2201. // get the base media decode time from the tfdt
  2202. var baseTime = findBox(traf, ['tfdt']).map(function (tfdt) {
  2203. var version = tfdt[0];
  2204. var result = readUint32(tfdt, 4);
  2205. if (version === 1) {
  2206. result *= Math.pow(2, 32);
  2207. result += readUint32(tfdt, 8);
  2208. }
  2209. return result / timescale;
  2210. })[0];
  2211. if (baseTime !== undefined) {
  2212. timeOffset = baseTime;
  2213. }
  2214. return findBox(traf, ['tfhd']).map(function (tfhd) {
  2215. var id = readUint32(tfhd, 4);
  2216. var tfhdFlags = readUint32(tfhd, 0) & 0xffffff;
  2217. var baseDataOffsetPresent = (tfhdFlags & 0x000001) !== 0;
  2218. var sampleDescriptionIndexPresent = (tfhdFlags & 0x000002) !== 0;
  2219. var defaultSampleDurationPresent = (tfhdFlags & 0x000008) !== 0;
  2220. var defaultSampleDuration = 0;
  2221. var defaultSampleSizePresent = (tfhdFlags & 0x000010) !== 0;
  2222. var defaultSampleSize = 0;
  2223. var defaultSampleFlagsPresent = (tfhdFlags & 0x000020) !== 0;
  2224. var tfhdOffset = 8;
  2225. if (id === trackId) {
  2226. if (baseDataOffsetPresent) {
  2227. tfhdOffset += 8;
  2228. }
  2229. if (sampleDescriptionIndexPresent) {
  2230. tfhdOffset += 4;
  2231. }
  2232. if (defaultSampleDurationPresent) {
  2233. defaultSampleDuration = readUint32(tfhd, tfhdOffset);
  2234. tfhdOffset += 4;
  2235. }
  2236. if (defaultSampleSizePresent) {
  2237. defaultSampleSize = readUint32(tfhd, tfhdOffset);
  2238. tfhdOffset += 4;
  2239. }
  2240. if (defaultSampleFlagsPresent) {
  2241. tfhdOffset += 4;
  2242. }
  2243. if (track.type === 'video') {
  2244. isHEVCFlavor = isHEVC(track.codec);
  2245. }
  2246. findBox(traf, ['trun']).map(function (trun) {
  2247. var version = trun[0];
  2248. var flags = readUint32(trun, 0) & 0xffffff;
  2249. var dataOffsetPresent = (flags & 0x000001) !== 0;
  2250. var dataOffset = 0;
  2251. var firstSampleFlagsPresent = (flags & 0x000004) !== 0;
  2252. var sampleDurationPresent = (flags & 0x000100) !== 0;
  2253. var sampleDuration = 0;
  2254. var sampleSizePresent = (flags & 0x000200) !== 0;
  2255. var sampleSize = 0;
  2256. var sampleFlagsPresent = (flags & 0x000400) !== 0;
  2257. var sampleCompositionOffsetsPresent = (flags & 0x000800) !== 0;
  2258. var compositionOffset = 0;
  2259. var sampleCount = readUint32(trun, 4);
  2260. var trunOffset = 8; // past version, flags, and sample count
  2261. if (dataOffsetPresent) {
  2262. dataOffset = readUint32(trun, trunOffset);
  2263. trunOffset += 4;
  2264. }
  2265. if (firstSampleFlagsPresent) {
  2266. trunOffset += 4;
  2267. }
  2268. var sampleOffset = dataOffset + moofOffset;
  2269. for (var ix = 0; ix < sampleCount; ix++) {
  2270. if (sampleDurationPresent) {
  2271. sampleDuration = readUint32(trun, trunOffset);
  2272. trunOffset += 4;
  2273. } else {
  2274. sampleDuration = defaultSampleDuration;
  2275. }
  2276. if (sampleSizePresent) {
  2277. sampleSize = readUint32(trun, trunOffset);
  2278. trunOffset += 4;
  2279. } else {
  2280. sampleSize = defaultSampleSize;
  2281. }
  2282. if (sampleFlagsPresent) {
  2283. trunOffset += 4;
  2284. }
  2285. if (sampleCompositionOffsetsPresent) {
  2286. if (version === 0) {
  2287. compositionOffset = readUint32(trun, trunOffset);
  2288. } else {
  2289. compositionOffset = readSint32(trun, trunOffset);
  2290. }
  2291. trunOffset += 4;
  2292. }
  2293. if (track.type === ElementaryStreamTypes.VIDEO) {
  2294. var naluTotalSize = 0;
  2295. while (naluTotalSize < sampleSize) {
  2296. var naluSize = readUint32(videoData, sampleOffset);
  2297. sampleOffset += 4;
  2298. if (isSEIMessage(isHEVCFlavor, videoData[sampleOffset])) {
  2299. var data = videoData.subarray(sampleOffset, sampleOffset + naluSize);
  2300. parseSEIMessageFromNALu(data, isHEVCFlavor ? 2 : 1, timeOffset + compositionOffset / timescale, seiSamples);
  2301. }
  2302. sampleOffset += naluSize;
  2303. naluTotalSize += naluSize + 4;
  2304. }
  2305. }
  2306. timeOffset += sampleDuration / timescale;
  2307. }
  2308. });
  2309. }
  2310. });
  2311. });
  2312. });
  2313. return seiSamples;
  2314. }
  2315. function isHEVC(codec) {
  2316. if (!codec) {
  2317. return false;
  2318. }
  2319. var delimit = codec.indexOf('.');
  2320. var baseCodec = delimit < 0 ? codec : codec.substring(0, delimit);
  2321. return baseCodec === 'hvc1' || baseCodec === 'hev1' ||
  2322. // Dolby Vision
  2323. baseCodec === 'dvh1' || baseCodec === 'dvhe';
  2324. }
  2325. function isSEIMessage(isHEVCFlavor, naluHeader) {
  2326. if (isHEVCFlavor) {
  2327. var naluType = naluHeader >> 1 & 0x3f;
  2328. return naluType === 39 || naluType === 40;
  2329. } else {
  2330. var _naluType = naluHeader & 0x1f;
  2331. return _naluType === 6;
  2332. }
  2333. }
  2334. function parseSEIMessageFromNALu(unescapedData, headerSize, pts, samples) {
  2335. var data = discardEPB(unescapedData);
  2336. var seiPtr = 0;
  2337. // skip nal header
  2338. seiPtr += headerSize;
  2339. var payloadType = 0;
  2340. var payloadSize = 0;
  2341. var b = 0;
  2342. while (seiPtr < data.length) {
  2343. payloadType = 0;
  2344. do {
  2345. if (seiPtr >= data.length) {
  2346. break;
  2347. }
  2348. b = data[seiPtr++];
  2349. payloadType += b;
  2350. } while (b === 0xff);
  2351. // Parse payload size.
  2352. payloadSize = 0;
  2353. do {
  2354. if (seiPtr >= data.length) {
  2355. break;
  2356. }
  2357. b = data[seiPtr++];
  2358. payloadSize += b;
  2359. } while (b === 0xff);
  2360. var leftOver = data.length - seiPtr;
  2361. // Create a variable to process the payload
  2362. var payPtr = seiPtr;
  2363. // Increment the seiPtr to the end of the payload
  2364. if (payloadSize < leftOver) {
  2365. seiPtr += payloadSize;
  2366. } else if (payloadSize > leftOver) {
  2367. // Some type of corruption has happened?
  2368. logger.error("Malformed SEI payload. " + payloadSize + " is too small, only " + leftOver + " bytes left to parse.");
  2369. // We might be able to parse some data, but let's be safe and ignore it.
  2370. break;
  2371. }
  2372. if (payloadType === 4) {
  2373. var countryCode = data[payPtr++];
  2374. if (countryCode === 181) {
  2375. var providerCode = readUint16(data, payPtr);
  2376. payPtr += 2;
  2377. if (providerCode === 49) {
  2378. var userStructure = readUint32(data, payPtr);
  2379. payPtr += 4;
  2380. if (userStructure === 0x47413934) {
  2381. var userDataType = data[payPtr++];
  2382. // Raw CEA-608 bytes wrapped in CEA-708 packet
  2383. if (userDataType === 3) {
  2384. var firstByte = data[payPtr++];
  2385. var totalCCs = 0x1f & firstByte;
  2386. var enabled = 0x40 & firstByte;
  2387. var totalBytes = enabled ? 2 + totalCCs * 3 : 0;
  2388. var byteArray = new Uint8Array(totalBytes);
  2389. if (enabled) {
  2390. byteArray[0] = firstByte;
  2391. for (var i = 1; i < totalBytes; i++) {
  2392. byteArray[i] = data[payPtr++];
  2393. }
  2394. }
  2395. samples.push({
  2396. type: userDataType,
  2397. payloadType: payloadType,
  2398. pts: pts,
  2399. bytes: byteArray
  2400. });
  2401. }
  2402. }
  2403. }
  2404. }
  2405. } else if (payloadType === 5) {
  2406. if (payloadSize > 16) {
  2407. var uuidStrArray = [];
  2408. for (var _i3 = 0; _i3 < 16; _i3++) {
  2409. var _b = data[payPtr++].toString(16);
  2410. uuidStrArray.push(_b.length == 1 ? '0' + _b : _b);
  2411. if (_i3 === 3 || _i3 === 5 || _i3 === 7 || _i3 === 9) {
  2412. uuidStrArray.push('-');
  2413. }
  2414. }
  2415. var length = payloadSize - 16;
  2416. var userDataBytes = new Uint8Array(length);
  2417. for (var _i4 = 0; _i4 < length; _i4++) {
  2418. userDataBytes[_i4] = data[payPtr++];
  2419. }
  2420. samples.push({
  2421. payloadType: payloadType,
  2422. pts: pts,
  2423. uuid: uuidStrArray.join(''),
  2424. userData: utf8ArrayToStr(userDataBytes),
  2425. userDataBytes: userDataBytes
  2426. });
  2427. }
  2428. }
  2429. }
  2430. }
  2431. /**
  2432. * remove Emulation Prevention bytes from a RBSP
  2433. */
  2434. function discardEPB(data) {
  2435. var length = data.byteLength;
  2436. var EPBPositions = [];
  2437. var i = 1;
  2438. // Find all `Emulation Prevention Bytes`
  2439. while (i < length - 2) {
  2440. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  2441. EPBPositions.push(i + 2);
  2442. i += 2;
  2443. } else {
  2444. i++;
  2445. }
  2446. }
  2447. // If no Emulation Prevention Bytes were found just return the original
  2448. // array
  2449. if (EPBPositions.length === 0) {
  2450. return data;
  2451. }
  2452. // Create a new array to hold the NAL unit data
  2453. var newLength = length - EPBPositions.length;
  2454. var newData = new Uint8Array(newLength);
  2455. var sourceIndex = 0;
  2456. for (i = 0; i < newLength; sourceIndex++, i++) {
  2457. if (sourceIndex === EPBPositions[0]) {
  2458. // Skip this byte
  2459. sourceIndex++;
  2460. // Remove this position index
  2461. EPBPositions.shift();
  2462. }
  2463. newData[i] = data[sourceIndex];
  2464. }
  2465. return newData;
  2466. }
  2467. function parseEmsg(data) {
  2468. var version = data[0];
  2469. var schemeIdUri = '';
  2470. var value = '';
  2471. var timeScale = 0;
  2472. var presentationTimeDelta = 0;
  2473. var presentationTime = 0;
  2474. var eventDuration = 0;
  2475. var id = 0;
  2476. var offset = 0;
  2477. if (version === 0) {
  2478. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2479. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2480. offset += 1;
  2481. }
  2482. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2483. offset += 1;
  2484. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2485. value += bin2str(data.subarray(offset, offset + 1));
  2486. offset += 1;
  2487. }
  2488. value += bin2str(data.subarray(offset, offset + 1));
  2489. offset += 1;
  2490. timeScale = readUint32(data, 12);
  2491. presentationTimeDelta = readUint32(data, 16);
  2492. eventDuration = readUint32(data, 20);
  2493. id = readUint32(data, 24);
  2494. offset = 28;
  2495. } else if (version === 1) {
  2496. offset += 4;
  2497. timeScale = readUint32(data, offset);
  2498. offset += 4;
  2499. var leftPresentationTime = readUint32(data, offset);
  2500. offset += 4;
  2501. var rightPresentationTime = readUint32(data, offset);
  2502. offset += 4;
  2503. presentationTime = Math.pow(2, 32) * leftPresentationTime + rightPresentationTime;
  2504. if (!isSafeInteger(presentationTime)) {
  2505. presentationTime = Number.MAX_SAFE_INTEGER;
  2506. logger.warn('Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box');
  2507. }
  2508. eventDuration = readUint32(data, offset);
  2509. offset += 4;
  2510. id = readUint32(data, offset);
  2511. offset += 4;
  2512. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2513. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2514. offset += 1;
  2515. }
  2516. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2517. offset += 1;
  2518. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2519. value += bin2str(data.subarray(offset, offset + 1));
  2520. offset += 1;
  2521. }
  2522. value += bin2str(data.subarray(offset, offset + 1));
  2523. offset += 1;
  2524. }
  2525. var payload = data.subarray(offset, data.byteLength);
  2526. return {
  2527. schemeIdUri: schemeIdUri,
  2528. value: value,
  2529. timeScale: timeScale,
  2530. presentationTime: presentationTime,
  2531. presentationTimeDelta: presentationTimeDelta,
  2532. eventDuration: eventDuration,
  2533. id: id,
  2534. payload: payload
  2535. };
  2536. }
  2537. var LevelKey = /*#__PURE__*/function () {
  2538. LevelKey.clearKeyUriToKeyIdMap = function clearKeyUriToKeyIdMap() {
  2539. };
  2540. function LevelKey(method, uri, format, formatversions, iv) {
  2541. if (formatversions === void 0) {
  2542. formatversions = [1];
  2543. }
  2544. if (iv === void 0) {
  2545. iv = null;
  2546. }
  2547. this.uri = void 0;
  2548. this.method = void 0;
  2549. this.keyFormat = void 0;
  2550. this.keyFormatVersions = void 0;
  2551. this.encrypted = void 0;
  2552. this.isCommonEncryption = void 0;
  2553. this.iv = null;
  2554. this.key = null;
  2555. this.keyId = null;
  2556. this.pssh = null;
  2557. this.method = method;
  2558. this.uri = uri;
  2559. this.keyFormat = format;
  2560. this.keyFormatVersions = formatversions;
  2561. this.iv = iv;
  2562. this.encrypted = method ? method !== 'NONE' : false;
  2563. this.isCommonEncryption = this.encrypted && method !== 'AES-128';
  2564. }
  2565. var _proto = LevelKey.prototype;
  2566. _proto.isSupported = function isSupported() {
  2567. // If it's Segment encryption or No encryption, just select that key system
  2568. if (this.method) {
  2569. if (this.method === 'AES-128' || this.method === 'NONE') {
  2570. return true;
  2571. }
  2572. if (this.keyFormat === 'identity') {
  2573. // Maintain support for clear SAMPLE-AES with MPEG-3 TS
  2574. return this.method === 'SAMPLE-AES';
  2575. }
  2576. }
  2577. return false;
  2578. };
  2579. _proto.getDecryptData = function getDecryptData(sn) {
  2580. if (!this.encrypted || !this.uri) {
  2581. return null;
  2582. }
  2583. if (this.method === 'AES-128' && this.uri && !this.iv) {
  2584. if (typeof sn !== 'number') {
  2585. // We are fetching decryption data for a initialization segment
  2586. // If the segment was encrypted with AES-128
  2587. // It must have an IV defined. We cannot substitute the Segment Number in.
  2588. if (this.method === 'AES-128' && !this.iv) {
  2589. logger.warn("missing IV for initialization segment with method=\"" + this.method + "\" - compliance issue");
  2590. }
  2591. // Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation.
  2592. sn = 0;
  2593. }
  2594. var iv = createInitializationVector(sn);
  2595. var decryptdata = new LevelKey(this.method, this.uri, 'identity', this.keyFormatVersions, iv);
  2596. return decryptdata;
  2597. }
  2598. {
  2599. return this;
  2600. }
  2601. };
  2602. return LevelKey;
  2603. }();
  2604. function createInitializationVector(segmentNumber) {
  2605. var uint8View = new Uint8Array(16);
  2606. for (var i = 12; i < 16; i++) {
  2607. uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff;
  2608. }
  2609. return uint8View;
  2610. }
  2611. /**
  2612. * MediaSource helper
  2613. */
  2614. function getMediaSource(preferManagedMediaSource) {
  2615. if (preferManagedMediaSource === void 0) {
  2616. preferManagedMediaSource = true;
  2617. }
  2618. if (typeof self === 'undefined') return undefined;
  2619. var mms = (preferManagedMediaSource || !self.MediaSource) && self.ManagedMediaSource;
  2620. return mms || self.MediaSource || self.WebKitMediaSource;
  2621. }
  2622. function isManagedMediaSource(source) {
  2623. return typeof self !== 'undefined' && source === self.ManagedMediaSource;
  2624. }
  2625. // from http://mp4ra.org/codecs.html
  2626. // values indicate codec selection preference (lower is higher priority)
  2627. var sampleEntryCodesISO = {
  2628. audio: {
  2629. a3ds: 1,
  2630. 'ac-3': 0.95,
  2631. 'ac-4': 1,
  2632. alac: 0.9,
  2633. alaw: 1,
  2634. dra1: 1,
  2635. 'dts+': 1,
  2636. 'dts-': 1,
  2637. dtsc: 1,
  2638. dtse: 1,
  2639. dtsh: 1,
  2640. 'ec-3': 0.9,
  2641. enca: 1,
  2642. fLaC: 0.9,
  2643. // MP4-RA listed codec entry for FLAC
  2644. flac: 0.9,
  2645. // legacy browser codec name for FLAC
  2646. FLAC: 0.9,
  2647. // some manifests may list "FLAC" with Apple's tools
  2648. g719: 1,
  2649. g726: 1,
  2650. m4ae: 1,
  2651. mha1: 1,
  2652. mha2: 1,
  2653. mhm1: 1,
  2654. mhm2: 1,
  2655. mlpa: 1,
  2656. mp4a: 1,
  2657. 'raw ': 1,
  2658. Opus: 1,
  2659. opus: 1,
  2660. // browsers expect this to be lowercase despite MP4RA says 'Opus'
  2661. samr: 1,
  2662. sawb: 1,
  2663. sawp: 1,
  2664. sevc: 1,
  2665. sqcp: 1,
  2666. ssmv: 1,
  2667. twos: 1,
  2668. ulaw: 1
  2669. },
  2670. video: {
  2671. avc1: 1,
  2672. avc2: 1,
  2673. avc3: 1,
  2674. avc4: 1,
  2675. avcp: 1,
  2676. av01: 0.8,
  2677. drac: 1,
  2678. dva1: 1,
  2679. dvav: 1,
  2680. dvh1: 0.7,
  2681. dvhe: 0.7,
  2682. encv: 1,
  2683. hev1: 0.75,
  2684. hvc1: 0.75,
  2685. mjp2: 1,
  2686. mp4v: 1,
  2687. mvc1: 1,
  2688. mvc2: 1,
  2689. mvc3: 1,
  2690. mvc4: 1,
  2691. resv: 1,
  2692. rv60: 1,
  2693. s263: 1,
  2694. svc1: 1,
  2695. svc2: 1,
  2696. 'vc-1': 1,
  2697. vp08: 1,
  2698. vp09: 0.9
  2699. },
  2700. text: {
  2701. stpp: 1,
  2702. wvtt: 1
  2703. }
  2704. };
  2705. function isCodecType(codec, type) {
  2706. var typeCodes = sampleEntryCodesISO[type];
  2707. return !!typeCodes && !!typeCodes[codec.slice(0, 4)];
  2708. }
  2709. function areCodecsMediaSourceSupported(codecs, type, preferManagedMediaSource) {
  2710. if (preferManagedMediaSource === void 0) {
  2711. preferManagedMediaSource = true;
  2712. }
  2713. return !codecs.split(',').some(function (codec) {
  2714. return !isCodecMediaSourceSupported(codec, type, preferManagedMediaSource);
  2715. });
  2716. }
  2717. function isCodecMediaSourceSupported(codec, type, preferManagedMediaSource) {
  2718. var _MediaSource$isTypeSu;
  2719. if (preferManagedMediaSource === void 0) {
  2720. preferManagedMediaSource = true;
  2721. }
  2722. var MediaSource = getMediaSource(preferManagedMediaSource);
  2723. return (_MediaSource$isTypeSu = MediaSource == null ? void 0 : MediaSource.isTypeSupported(mimeTypeForCodec(codec, type))) != null ? _MediaSource$isTypeSu : false;
  2724. }
  2725. function mimeTypeForCodec(codec, type) {
  2726. return type + "/mp4;codecs=\"" + codec + "\"";
  2727. }
  2728. function videoCodecPreferenceValue(videoCodec) {
  2729. if (videoCodec) {
  2730. var fourCC = videoCodec.substring(0, 4);
  2731. return sampleEntryCodesISO.video[fourCC];
  2732. }
  2733. return 2;
  2734. }
  2735. function codecsSetSelectionPreferenceValue(codecSet) {
  2736. return codecSet.split(',').reduce(function (num, fourCC) {
  2737. var preferenceValue = sampleEntryCodesISO.video[fourCC];
  2738. if (preferenceValue) {
  2739. return (preferenceValue * 2 + num) / (num ? 3 : 2);
  2740. }
  2741. return (sampleEntryCodesISO.audio[fourCC] + num) / (num ? 2 : 1);
  2742. }, 0);
  2743. }
  2744. var CODEC_COMPATIBLE_NAMES = {};
  2745. function getCodecCompatibleNameLower(lowerCaseCodec, preferManagedMediaSource) {
  2746. if (preferManagedMediaSource === void 0) {
  2747. preferManagedMediaSource = true;
  2748. }
  2749. if (CODEC_COMPATIBLE_NAMES[lowerCaseCodec]) {
  2750. return CODEC_COMPATIBLE_NAMES[lowerCaseCodec];
  2751. }
  2752. // Idealy fLaC and Opus would be first (spec-compliant) but
  2753. // some browsers will report that fLaC is supported then fail.
  2754. // see: https://bugs.chromium.org/p/chromium/issues/detail?id=1422728
  2755. var codecsToCheck = {
  2756. flac: ['flac', 'fLaC', 'FLAC'],
  2757. opus: ['opus', 'Opus']
  2758. }[lowerCaseCodec];
  2759. for (var i = 0; i < codecsToCheck.length; i++) {
  2760. if (isCodecMediaSourceSupported(codecsToCheck[i], 'audio', preferManagedMediaSource)) {
  2761. CODEC_COMPATIBLE_NAMES[lowerCaseCodec] = codecsToCheck[i];
  2762. return codecsToCheck[i];
  2763. }
  2764. }
  2765. return lowerCaseCodec;
  2766. }
  2767. var AUDIO_CODEC_REGEXP = /flac|opus/i;
  2768. function getCodecCompatibleName(codec, preferManagedMediaSource) {
  2769. if (preferManagedMediaSource === void 0) {
  2770. preferManagedMediaSource = true;
  2771. }
  2772. return codec.replace(AUDIO_CODEC_REGEXP, function (m) {
  2773. return getCodecCompatibleNameLower(m.toLowerCase(), preferManagedMediaSource);
  2774. });
  2775. }
  2776. function pickMostCompleteCodecName(parsedCodec, levelCodec) {
  2777. // Parsing of mp4a codecs strings in mp4-tools from media is incomplete as of d8c6c7a
  2778. // so use level codec is parsed codec is unavailable or incomplete
  2779. if (parsedCodec && parsedCodec !== 'mp4a') {
  2780. return parsedCodec;
  2781. }
  2782. return levelCodec ? levelCodec.split(',')[0] : levelCodec;
  2783. }
  2784. function convertAVC1ToAVCOTI(codec) {
  2785. // Convert avc1 codec string from RFC-4281 to RFC-6381 for MediaSource.isTypeSupported
  2786. var avcdata = codec.split('.');
  2787. if (avcdata.length > 2) {
  2788. var result = avcdata.shift() + '.';
  2789. result += parseInt(avcdata.shift()).toString(16);
  2790. result += ('000' + parseInt(avcdata.shift()).toString(16)).slice(-4);
  2791. return result;
  2792. }
  2793. return codec;
  2794. }
  2795. 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;
  2796. var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
  2797. var IS_MEDIA_PLAYLIST = /^#EXT(?:INF|-X-TARGETDURATION):/m; // Handle empty Media Playlist (first EXTINF not signaled, but TARGETDURATION present)
  2798. var LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,
  2799. // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
  2800. /(?!#) *(\S[^\r\n]*)/.source,
  2801. // segment URI, group 3 => the URI (note newline is not eaten)
  2802. /#EXT-X-BYTERANGE:*(.+)/.source,
  2803. // next segment's byterange, group 4 => range spec (x@y)
  2804. /#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,
  2805. // next segment's program date/time group 5 => the datetime spec
  2806. /#.*/.source // All other non-segment oriented tags will match with all groups empty
  2807. ].join('|'), 'g');
  2808. 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('|'));
  2809. var M3U8Parser = /*#__PURE__*/function () {
  2810. function M3U8Parser() {}
  2811. M3U8Parser.findGroup = function findGroup(groups, mediaGroupId) {
  2812. for (var i = 0; i < groups.length; i++) {
  2813. var group = groups[i];
  2814. if (group.id === mediaGroupId) {
  2815. return group;
  2816. }
  2817. }
  2818. };
  2819. M3U8Parser.resolve = function resolve(url, baseUrl) {
  2820. return urlToolkitExports.buildAbsoluteURL(baseUrl, url, {
  2821. alwaysNormalize: true
  2822. });
  2823. };
  2824. M3U8Parser.isMediaPlaylist = function isMediaPlaylist(str) {
  2825. return IS_MEDIA_PLAYLIST.test(str);
  2826. };
  2827. M3U8Parser.parseMasterPlaylist = function parseMasterPlaylist(string, baseurl) {
  2828. var hasVariableRefs = false;
  2829. var parsed = {
  2830. contentSteering: null,
  2831. levels: [],
  2832. playlistParsingError: null,
  2833. sessionData: null,
  2834. sessionKeys: null,
  2835. startTimeOffset: null,
  2836. variableList: null,
  2837. hasVariableRefs: hasVariableRefs
  2838. };
  2839. var levelsWithKnownCodecs = [];
  2840. MASTER_PLAYLIST_REGEX.lastIndex = 0;
  2841. var result;
  2842. while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
  2843. if (result[1]) {
  2844. var _level$unknownCodecs;
  2845. // '#EXT-X-STREAM-INF' is found, parse level tag in group 1
  2846. var attrs = new AttrList(result[1]);
  2847. var uri = result[2];
  2848. var level = {
  2849. attrs: attrs,
  2850. bitrate: attrs.decimalInteger('BANDWIDTH') || attrs.decimalInteger('AVERAGE-BANDWIDTH'),
  2851. name: attrs.NAME,
  2852. url: M3U8Parser.resolve(uri, baseurl)
  2853. };
  2854. var resolution = attrs.decimalResolution('RESOLUTION');
  2855. if (resolution) {
  2856. level.width = resolution.width;
  2857. level.height = resolution.height;
  2858. }
  2859. setCodecs(attrs.CODECS, level);
  2860. if (!((_level$unknownCodecs = level.unknownCodecs) != null && _level$unknownCodecs.length)) {
  2861. levelsWithKnownCodecs.push(level);
  2862. }
  2863. parsed.levels.push(level);
  2864. } else if (result[3]) {
  2865. var tag = result[3];
  2866. var attributes = result[4];
  2867. switch (tag) {
  2868. case 'SESSION-DATA':
  2869. {
  2870. // #EXT-X-SESSION-DATA
  2871. var sessionAttrs = new AttrList(attributes);
  2872. var dataId = sessionAttrs['DATA-ID'];
  2873. if (dataId) {
  2874. if (parsed.sessionData === null) {
  2875. parsed.sessionData = {};
  2876. }
  2877. parsed.sessionData[dataId] = sessionAttrs;
  2878. }
  2879. break;
  2880. }
  2881. case 'SESSION-KEY':
  2882. {
  2883. // #EXT-X-SESSION-KEY
  2884. var sessionKey = parseKey(attributes, baseurl);
  2885. if (sessionKey.encrypted && sessionKey.isSupported()) {
  2886. if (parsed.sessionKeys === null) {
  2887. parsed.sessionKeys = [];
  2888. }
  2889. parsed.sessionKeys.push(sessionKey);
  2890. } else {
  2891. logger.warn("[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: \"" + attributes + "\"");
  2892. }
  2893. break;
  2894. }
  2895. case 'DEFINE':
  2896. {
  2897. break;
  2898. }
  2899. case 'CONTENT-STEERING':
  2900. {
  2901. // #EXT-X-CONTENT-STEERING
  2902. var contentSteeringAttributes = new AttrList(attributes);
  2903. parsed.contentSteering = {
  2904. uri: M3U8Parser.resolve(contentSteeringAttributes['SERVER-URI'], baseurl),
  2905. pathwayId: contentSteeringAttributes['PATHWAY-ID'] || '.'
  2906. };
  2907. break;
  2908. }
  2909. case 'START':
  2910. {
  2911. // #EXT-X-START
  2912. parsed.startTimeOffset = parseStartTimeOffset(attributes);
  2913. break;
  2914. }
  2915. }
  2916. }
  2917. }
  2918. // Filter out levels with unknown codecs if it does not remove all levels
  2919. var stripUnknownCodecLevels = levelsWithKnownCodecs.length > 0 && levelsWithKnownCodecs.length < parsed.levels.length;
  2920. parsed.levels = stripUnknownCodecLevels ? levelsWithKnownCodecs : parsed.levels;
  2921. if (parsed.levels.length === 0) {
  2922. parsed.playlistParsingError = new Error('no levels found in manifest');
  2923. }
  2924. return parsed;
  2925. };
  2926. M3U8Parser.parseMasterPlaylistMedia = function parseMasterPlaylistMedia(string, baseurl, parsed) {
  2927. var result;
  2928. var results = {};
  2929. var levels = parsed.levels;
  2930. var groupsByType = {
  2931. AUDIO: levels.map(function (level) {
  2932. return {
  2933. id: level.attrs.AUDIO,
  2934. audioCodec: level.audioCodec
  2935. };
  2936. }),
  2937. SUBTITLES: levels.map(function (level) {
  2938. return {
  2939. id: level.attrs.SUBTITLES,
  2940. textCodec: level.textCodec
  2941. };
  2942. }),
  2943. 'CLOSED-CAPTIONS': []
  2944. };
  2945. var id = 0;
  2946. MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
  2947. while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
  2948. var attrs = new AttrList(result[1]);
  2949. var type = attrs.TYPE;
  2950. if (type) {
  2951. var groups = groupsByType[type];
  2952. var medias = results[type] || [];
  2953. results[type] = medias;
  2954. var lang = attrs.LANGUAGE;
  2955. var assocLang = attrs['ASSOC-LANGUAGE'];
  2956. var channels = attrs.CHANNELS;
  2957. var characteristics = attrs.CHARACTERISTICS;
  2958. var instreamId = attrs['INSTREAM-ID'];
  2959. var media = {
  2960. attrs: attrs,
  2961. bitrate: 0,
  2962. id: id++,
  2963. groupId: attrs['GROUP-ID'] || '',
  2964. name: attrs.NAME || lang || '',
  2965. type: type,
  2966. default: attrs.bool('DEFAULT'),
  2967. autoselect: attrs.bool('AUTOSELECT'),
  2968. forced: attrs.bool('FORCED'),
  2969. lang: lang,
  2970. url: attrs.URI ? M3U8Parser.resolve(attrs.URI, baseurl) : ''
  2971. };
  2972. if (assocLang) {
  2973. media.assocLang = assocLang;
  2974. }
  2975. if (channels) {
  2976. media.channels = channels;
  2977. }
  2978. if (characteristics) {
  2979. media.characteristics = characteristics;
  2980. }
  2981. if (instreamId) {
  2982. media.instreamId = instreamId;
  2983. }
  2984. if (groups != null && groups.length) {
  2985. // If there are audio or text groups signalled in the manifest, let's look for a matching codec string for this track
  2986. // If we don't find the track signalled, lets use the first audio groups codec we have
  2987. // Acting as a best guess
  2988. var groupCodec = M3U8Parser.findGroup(groups, media.groupId) || groups[0];
  2989. assignCodec(media, groupCodec, 'audioCodec');
  2990. assignCodec(media, groupCodec, 'textCodec');
  2991. }
  2992. medias.push(media);
  2993. }
  2994. }
  2995. return results;
  2996. };
  2997. M3U8Parser.parseLevelPlaylist = function parseLevelPlaylist(string, baseurl, id, type, levelUrlId, multivariantVariableList) {
  2998. var level = new LevelDetails(baseurl);
  2999. var fragments = level.fragments;
  3000. // The most recent init segment seen (applies to all subsequent segments)
  3001. var currentInitSegment = null;
  3002. var currentSN = 0;
  3003. var currentPart = 0;
  3004. var totalduration = 0;
  3005. var discontinuityCounter = 0;
  3006. var prevFrag = null;
  3007. var frag = new Fragment(type, baseurl);
  3008. var result;
  3009. var i;
  3010. var levelkeys;
  3011. var firstPdtIndex = -1;
  3012. var createNextFrag = false;
  3013. var nextByteRange = null;
  3014. LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
  3015. level.m3u8 = string;
  3016. level.hasVariableRefs = false;
  3017. while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
  3018. if (createNextFrag) {
  3019. createNextFrag = false;
  3020. frag = new Fragment(type, baseurl);
  3021. // setup the next fragment for part loading
  3022. frag.start = totalduration;
  3023. frag.sn = currentSN;
  3024. frag.cc = discontinuityCounter;
  3025. frag.level = id;
  3026. if (currentInitSegment) {
  3027. frag.initSegment = currentInitSegment;
  3028. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  3029. currentInitSegment.rawProgramDateTime = null;
  3030. if (nextByteRange) {
  3031. frag.setByteRange(nextByteRange);
  3032. nextByteRange = null;
  3033. }
  3034. }
  3035. }
  3036. var duration = result[1];
  3037. if (duration) {
  3038. // INF
  3039. frag.duration = parseFloat(duration);
  3040. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  3041. var title = (' ' + result[2]).slice(1);
  3042. frag.title = title || null;
  3043. frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);
  3044. } else if (result[3]) {
  3045. // url
  3046. if (isFiniteNumber(frag.duration)) {
  3047. frag.start = totalduration;
  3048. if (levelkeys) {
  3049. setFragLevelKeys(frag, levelkeys, level);
  3050. }
  3051. frag.sn = currentSN;
  3052. frag.level = id;
  3053. frag.cc = discontinuityCounter;
  3054. fragments.push(frag);
  3055. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  3056. var uri = (' ' + result[3]).slice(1);
  3057. frag.relurl = uri;
  3058. assignProgramDateTime(frag, prevFrag);
  3059. prevFrag = frag;
  3060. totalduration += frag.duration;
  3061. currentSN++;
  3062. currentPart = 0;
  3063. createNextFrag = true;
  3064. }
  3065. } else if (result[4]) {
  3066. // X-BYTERANGE
  3067. var data = (' ' + result[4]).slice(1);
  3068. if (prevFrag) {
  3069. frag.setByteRange(data, prevFrag);
  3070. } else {
  3071. frag.setByteRange(data);
  3072. }
  3073. } else if (result[5]) {
  3074. // PROGRAM-DATE-TIME
  3075. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  3076. frag.rawProgramDateTime = (' ' + result[5]).slice(1);
  3077. frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);
  3078. if (firstPdtIndex === -1) {
  3079. firstPdtIndex = fragments.length;
  3080. }
  3081. } else {
  3082. result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
  3083. if (!result) {
  3084. logger.warn('No matches on slow regex match for level playlist!');
  3085. continue;
  3086. }
  3087. for (i = 1; i < result.length; i++) {
  3088. if (typeof result[i] !== 'undefined') {
  3089. break;
  3090. }
  3091. }
  3092. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  3093. var tag = (' ' + result[i]).slice(1);
  3094. var value1 = (' ' + result[i + 1]).slice(1);
  3095. var value2 = result[i + 2] ? (' ' + result[i + 2]).slice(1) : '';
  3096. switch (tag) {
  3097. case 'PLAYLIST-TYPE':
  3098. level.type = value1.toUpperCase();
  3099. break;
  3100. case 'MEDIA-SEQUENCE':
  3101. currentSN = level.startSN = parseInt(value1);
  3102. break;
  3103. case 'SKIP':
  3104. {
  3105. var skipAttrs = new AttrList(value1);
  3106. var skippedSegments = skipAttrs.decimalInteger('SKIPPED-SEGMENTS');
  3107. if (isFiniteNumber(skippedSegments)) {
  3108. level.skippedSegments = skippedSegments;
  3109. // This will result in fragments[] containing undefined values, which we will fill in with `mergeDetails`
  3110. for (var _i = skippedSegments; _i--;) {
  3111. fragments.unshift(null);
  3112. }
  3113. currentSN += skippedSegments;
  3114. }
  3115. var recentlyRemovedDateranges = skipAttrs.enumeratedString('RECENTLY-REMOVED-DATERANGES');
  3116. if (recentlyRemovedDateranges) {
  3117. level.recentlyRemovedDateranges = recentlyRemovedDateranges.split('\t');
  3118. }
  3119. break;
  3120. }
  3121. case 'TARGETDURATION':
  3122. level.targetduration = Math.max(parseInt(value1), 1);
  3123. break;
  3124. case 'VERSION':
  3125. level.version = parseInt(value1);
  3126. break;
  3127. case 'INDEPENDENT-SEGMENTS':
  3128. case 'EXTM3U':
  3129. break;
  3130. case 'ENDLIST':
  3131. level.live = false;
  3132. break;
  3133. case '#':
  3134. if (value1 || value2) {
  3135. frag.tagList.push(value2 ? [value1, value2] : [value1]);
  3136. }
  3137. break;
  3138. case 'DISCONTINUITY':
  3139. discontinuityCounter++;
  3140. frag.tagList.push(['DIS']);
  3141. break;
  3142. case 'GAP':
  3143. frag.gap = true;
  3144. frag.tagList.push([tag]);
  3145. break;
  3146. case 'BITRATE':
  3147. frag.tagList.push([tag, value1]);
  3148. break;
  3149. case 'DATERANGE':
  3150. {
  3151. var dateRangeAttr = new AttrList(value1);
  3152. var dateRange = new DateRange(dateRangeAttr, level.dateRanges[dateRangeAttr.ID]);
  3153. if (dateRange.isValid || level.skippedSegments) {
  3154. level.dateRanges[dateRange.id] = dateRange;
  3155. } else {
  3156. logger.warn("Ignoring invalid DATERANGE tag: \"" + value1 + "\"");
  3157. }
  3158. // Add to fragment tag list for backwards compatibility (< v1.2.0)
  3159. frag.tagList.push(['EXT-X-DATERANGE', value1]);
  3160. break;
  3161. }
  3162. case 'DEFINE':
  3163. {
  3164. break;
  3165. }
  3166. case 'DISCONTINUITY-SEQUENCE':
  3167. discontinuityCounter = parseInt(value1);
  3168. break;
  3169. case 'KEY':
  3170. {
  3171. var levelKey = parseKey(value1, baseurl);
  3172. if (levelKey.isSupported()) {
  3173. if (levelKey.method === 'NONE') {
  3174. levelkeys = undefined;
  3175. break;
  3176. }
  3177. if (!levelkeys) {
  3178. levelkeys = {};
  3179. }
  3180. if (levelkeys[levelKey.keyFormat]) {
  3181. levelkeys = _extends({}, levelkeys);
  3182. }
  3183. levelkeys[levelKey.keyFormat] = levelKey;
  3184. } else {
  3185. logger.warn("[Keys] Ignoring invalid EXT-X-KEY tag: \"" + value1 + "\"");
  3186. }
  3187. break;
  3188. }
  3189. case 'START':
  3190. level.startTimeOffset = parseStartTimeOffset(value1);
  3191. break;
  3192. case 'MAP':
  3193. {
  3194. var mapAttrs = new AttrList(value1);
  3195. if (frag.duration) {
  3196. // Initial segment tag is after segment duration tag.
  3197. // #EXTINF: 6.0
  3198. // #EXT-X-MAP:URI="init.mp4
  3199. var init = new Fragment(type, baseurl);
  3200. setInitSegment(init, mapAttrs, id, levelkeys);
  3201. currentInitSegment = init;
  3202. frag.initSegment = currentInitSegment;
  3203. if (currentInitSegment.rawProgramDateTime && !frag.rawProgramDateTime) {
  3204. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  3205. }
  3206. } else {
  3207. // Initial segment tag is before segment duration tag
  3208. // Handle case where EXT-X-MAP is declared after EXT-X-BYTERANGE
  3209. var end = frag.byteRangeEndOffset;
  3210. if (end) {
  3211. var start = frag.byteRangeStartOffset;
  3212. nextByteRange = end - start + "@" + start;
  3213. } else {
  3214. nextByteRange = null;
  3215. }
  3216. setInitSegment(frag, mapAttrs, id, levelkeys);
  3217. currentInitSegment = frag;
  3218. createNextFrag = true;
  3219. }
  3220. break;
  3221. }
  3222. case 'SERVER-CONTROL':
  3223. {
  3224. var serverControlAttrs = new AttrList(value1);
  3225. level.canBlockReload = serverControlAttrs.bool('CAN-BLOCK-RELOAD');
  3226. level.canSkipUntil = serverControlAttrs.optionalFloat('CAN-SKIP-UNTIL', 0);
  3227. level.canSkipDateRanges = level.canSkipUntil > 0 && serverControlAttrs.bool('CAN-SKIP-DATERANGES');
  3228. level.partHoldBack = serverControlAttrs.optionalFloat('PART-HOLD-BACK', 0);
  3229. level.holdBack = serverControlAttrs.optionalFloat('HOLD-BACK', 0);
  3230. break;
  3231. }
  3232. case 'PART-INF':
  3233. {
  3234. var partInfAttrs = new AttrList(value1);
  3235. level.partTarget = partInfAttrs.decimalFloatingPoint('PART-TARGET');
  3236. break;
  3237. }
  3238. case 'PART':
  3239. {
  3240. var partList = level.partList;
  3241. if (!partList) {
  3242. partList = level.partList = [];
  3243. }
  3244. var previousFragmentPart = currentPart > 0 ? partList[partList.length - 1] : undefined;
  3245. var index = currentPart++;
  3246. var partAttrs = new AttrList(value1);
  3247. var part = new Part(partAttrs, frag, baseurl, index, previousFragmentPart);
  3248. partList.push(part);
  3249. frag.duration += part.duration;
  3250. break;
  3251. }
  3252. case 'PRELOAD-HINT':
  3253. {
  3254. var preloadHintAttrs = new AttrList(value1);
  3255. level.preloadHint = preloadHintAttrs;
  3256. break;
  3257. }
  3258. case 'RENDITION-REPORT':
  3259. {
  3260. var renditionReportAttrs = new AttrList(value1);
  3261. level.renditionReports = level.renditionReports || [];
  3262. level.renditionReports.push(renditionReportAttrs);
  3263. break;
  3264. }
  3265. default:
  3266. logger.warn("line parsed but not handled: " + result);
  3267. break;
  3268. }
  3269. }
  3270. }
  3271. if (prevFrag && !prevFrag.relurl) {
  3272. fragments.pop();
  3273. totalduration -= prevFrag.duration;
  3274. if (level.partList) {
  3275. level.fragmentHint = prevFrag;
  3276. }
  3277. } else if (level.partList) {
  3278. assignProgramDateTime(frag, prevFrag);
  3279. frag.cc = discontinuityCounter;
  3280. level.fragmentHint = frag;
  3281. if (levelkeys) {
  3282. setFragLevelKeys(frag, levelkeys, level);
  3283. }
  3284. }
  3285. var fragmentLength = fragments.length;
  3286. var firstFragment = fragments[0];
  3287. var lastFragment = fragments[fragmentLength - 1];
  3288. totalduration += level.skippedSegments * level.targetduration;
  3289. if (totalduration > 0 && fragmentLength && lastFragment) {
  3290. level.averagetargetduration = totalduration / fragmentLength;
  3291. var lastSn = lastFragment.sn;
  3292. level.endSN = lastSn !== 'initSegment' ? lastSn : 0;
  3293. if (!level.live) {
  3294. lastFragment.endList = true;
  3295. }
  3296. if (firstFragment) {
  3297. level.startCC = firstFragment.cc;
  3298. }
  3299. } else {
  3300. level.endSN = 0;
  3301. level.startCC = 0;
  3302. }
  3303. if (level.fragmentHint) {
  3304. totalduration += level.fragmentHint.duration;
  3305. }
  3306. level.totalduration = totalduration;
  3307. level.endCC = discontinuityCounter;
  3308. /**
  3309. * Backfill any missing PDT values
  3310. * "If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after
  3311. * one or more Media Segment URIs, the client SHOULD extrapolate
  3312. * backward from that tag (using EXTINF durations and/or media
  3313. * timestamps) to associate dates with those segments."
  3314. * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs
  3315. * computed.
  3316. */
  3317. if (firstPdtIndex > 0) {
  3318. backfillProgramDateTimes(fragments, firstPdtIndex);
  3319. }
  3320. return level;
  3321. };
  3322. return M3U8Parser;
  3323. }();
  3324. function parseKey(keyTagAttributes, baseurl, parsed) {
  3325. var _keyAttrs$METHOD, _keyAttrs$KEYFORMAT;
  3326. // https://tools.ietf.org/html/rfc8216#section-4.3.2.4
  3327. var keyAttrs = new AttrList(keyTagAttributes);
  3328. var decryptmethod = (_keyAttrs$METHOD = keyAttrs.METHOD) != null ? _keyAttrs$METHOD : '';
  3329. var decrypturi = keyAttrs.URI;
  3330. var decryptiv = keyAttrs.hexadecimalInteger('IV');
  3331. var decryptkeyformatversions = keyAttrs.KEYFORMATVERSIONS;
  3332. // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of "identity".
  3333. var decryptkeyformat = (_keyAttrs$KEYFORMAT = keyAttrs.KEYFORMAT) != null ? _keyAttrs$KEYFORMAT : 'identity';
  3334. if (decrypturi && keyAttrs.IV && !decryptiv) {
  3335. logger.error("Invalid IV: " + keyAttrs.IV);
  3336. }
  3337. // If decrypturi is a URI with a scheme, then baseurl will be ignored
  3338. // No uri is allowed when METHOD is NONE
  3339. var resolvedUri = decrypturi ? M3U8Parser.resolve(decrypturi, baseurl) : '';
  3340. var keyFormatVersions = (decryptkeyformatversions ? decryptkeyformatversions : '1').split('/').map(Number).filter(Number.isFinite);
  3341. return new LevelKey(decryptmethod, resolvedUri, decryptkeyformat, keyFormatVersions, decryptiv);
  3342. }
  3343. function parseStartTimeOffset(startAttributes) {
  3344. var startAttrs = new AttrList(startAttributes);
  3345. var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');
  3346. if (isFiniteNumber(startTimeOffset)) {
  3347. return startTimeOffset;
  3348. }
  3349. return null;
  3350. }
  3351. function setCodecs(codecsAttributeValue, level) {
  3352. var codecs = (codecsAttributeValue || '').split(/[ ,]+/).filter(function (c) {
  3353. return c;
  3354. });
  3355. ['video', 'audio', 'text'].forEach(function (type) {
  3356. var filtered = codecs.filter(function (codec) {
  3357. return isCodecType(codec, type);
  3358. });
  3359. if (filtered.length) {
  3360. // Comma separated list of all codecs for type
  3361. level[type + "Codec"] = filtered.join(',');
  3362. // Remove known codecs so that only unknownCodecs are left after iterating through each type
  3363. codecs = codecs.filter(function (codec) {
  3364. return filtered.indexOf(codec) === -1;
  3365. });
  3366. }
  3367. });
  3368. level.unknownCodecs = codecs;
  3369. }
  3370. function assignCodec(media, groupItem, codecProperty) {
  3371. var codecValue = groupItem[codecProperty];
  3372. if (codecValue) {
  3373. media[codecProperty] = codecValue;
  3374. }
  3375. }
  3376. function backfillProgramDateTimes(fragments, firstPdtIndex) {
  3377. var fragPrev = fragments[firstPdtIndex];
  3378. for (var i = firstPdtIndex; i--;) {
  3379. var frag = fragments[i];
  3380. // Exit on delta-playlist skipped segments
  3381. if (!frag) {
  3382. return;
  3383. }
  3384. frag.programDateTime = fragPrev.programDateTime - frag.duration * 1000;
  3385. fragPrev = frag;
  3386. }
  3387. }
  3388. function assignProgramDateTime(frag, prevFrag) {
  3389. if (frag.rawProgramDateTime) {
  3390. frag.programDateTime = Date.parse(frag.rawProgramDateTime);
  3391. } else if (prevFrag != null && prevFrag.programDateTime) {
  3392. frag.programDateTime = prevFrag.endProgramDateTime;
  3393. }
  3394. if (!isFiniteNumber(frag.programDateTime)) {
  3395. frag.programDateTime = null;
  3396. frag.rawProgramDateTime = null;
  3397. }
  3398. }
  3399. function setInitSegment(frag, mapAttrs, id, levelkeys) {
  3400. frag.relurl = mapAttrs.URI;
  3401. if (mapAttrs.BYTERANGE) {
  3402. frag.setByteRange(mapAttrs.BYTERANGE);
  3403. }
  3404. frag.level = id;
  3405. frag.sn = 'initSegment';
  3406. if (levelkeys) {
  3407. frag.levelkeys = levelkeys;
  3408. }
  3409. frag.initSegment = null;
  3410. }
  3411. function setFragLevelKeys(frag, levelkeys, level) {
  3412. frag.levelkeys = levelkeys;
  3413. var encryptedFragments = level.encryptedFragments;
  3414. if ((!encryptedFragments.length || encryptedFragments[encryptedFragments.length - 1].levelkeys !== levelkeys) && Object.keys(levelkeys).some(function (format) {
  3415. return levelkeys[format].isCommonEncryption;
  3416. })) {
  3417. encryptedFragments.push(frag);
  3418. }
  3419. }
  3420. var PlaylistContextType = {
  3421. MANIFEST: "manifest",
  3422. LEVEL: "level",
  3423. AUDIO_TRACK: "audioTrack",
  3424. SUBTITLE_TRACK: "subtitleTrack"
  3425. };
  3426. var PlaylistLevelType = {
  3427. MAIN: "main",
  3428. AUDIO: "audio",
  3429. SUBTITLE: "subtitle"
  3430. };
  3431. function mapContextToLevelType(context) {
  3432. var type = context.type;
  3433. switch (type) {
  3434. case PlaylistContextType.AUDIO_TRACK:
  3435. return PlaylistLevelType.AUDIO;
  3436. case PlaylistContextType.SUBTITLE_TRACK:
  3437. return PlaylistLevelType.SUBTITLE;
  3438. default:
  3439. return PlaylistLevelType.MAIN;
  3440. }
  3441. }
  3442. function getResponseUrl(response, context) {
  3443. var url = response.url;
  3444. // responseURL not supported on some browsers (it is used to detect URL redirection)
  3445. // data-uri mode also not supported (but no need to detect redirection)
  3446. if (url === undefined || url.indexOf('data:') === 0) {
  3447. // fallback to initial URL
  3448. url = context.url;
  3449. }
  3450. return url;
  3451. }
  3452. var PlaylistLoader = /*#__PURE__*/function () {
  3453. function PlaylistLoader(hls) {
  3454. this.hls = void 0;
  3455. this.loaders = Object.create(null);
  3456. this.variableList = null;
  3457. this.hls = hls;
  3458. this.registerListeners();
  3459. }
  3460. var _proto = PlaylistLoader.prototype;
  3461. _proto.startLoad = function startLoad(startPosition) {};
  3462. _proto.stopLoad = function stopLoad() {
  3463. this.destroyInternalLoaders();
  3464. };
  3465. _proto.registerListeners = function registerListeners() {
  3466. var hls = this.hls;
  3467. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3468. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  3469. hls.on(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  3470. hls.on(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  3471. };
  3472. _proto.unregisterListeners = function unregisterListeners() {
  3473. var hls = this.hls;
  3474. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3475. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  3476. hls.off(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  3477. hls.off(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  3478. }
  3479. /**
  3480. * Returns defaults or configured loader-type overloads (pLoader and loader config params)
  3481. */;
  3482. _proto.createInternalLoader = function createInternalLoader(context) {
  3483. var config = this.hls.config;
  3484. var PLoader = config.pLoader;
  3485. var Loader = config.loader;
  3486. var InternalLoader = PLoader || Loader;
  3487. var loader = new InternalLoader(config);
  3488. this.loaders[context.type] = loader;
  3489. return loader;
  3490. };
  3491. _proto.getInternalLoader = function getInternalLoader(context) {
  3492. return this.loaders[context.type];
  3493. };
  3494. _proto.resetInternalLoader = function resetInternalLoader(contextType) {
  3495. if (this.loaders[contextType]) {
  3496. delete this.loaders[contextType];
  3497. }
  3498. }
  3499. /**
  3500. * Call `destroy` on all internal loader instances mapped (one per context type)
  3501. */;
  3502. _proto.destroyInternalLoaders = function destroyInternalLoaders() {
  3503. for (var contextType in this.loaders) {
  3504. var loader = this.loaders[contextType];
  3505. if (loader) {
  3506. loader.destroy();
  3507. }
  3508. this.resetInternalLoader(contextType);
  3509. }
  3510. };
  3511. _proto.destroy = function destroy() {
  3512. this.variableList = null;
  3513. this.unregisterListeners();
  3514. this.destroyInternalLoaders();
  3515. };
  3516. _proto.onManifestLoading = function onManifestLoading(event, data) {
  3517. var url = data.url;
  3518. this.variableList = null;
  3519. this.load({
  3520. id: null,
  3521. level: 0,
  3522. responseType: 'text',
  3523. type: PlaylistContextType.MANIFEST,
  3524. url: url,
  3525. deliveryDirectives: null
  3526. });
  3527. };
  3528. _proto.onLevelLoading = function onLevelLoading(event, data) {
  3529. var id = data.id,
  3530. level = data.level,
  3531. pathwayId = data.pathwayId,
  3532. url = data.url,
  3533. deliveryDirectives = data.deliveryDirectives;
  3534. this.load({
  3535. id: id,
  3536. level: level,
  3537. pathwayId: pathwayId,
  3538. responseType: 'text',
  3539. type: PlaylistContextType.LEVEL,
  3540. url: url,
  3541. deliveryDirectives: deliveryDirectives
  3542. });
  3543. };
  3544. _proto.onAudioTrackLoading = function onAudioTrackLoading(event, data) {
  3545. var id = data.id,
  3546. groupId = data.groupId,
  3547. url = data.url,
  3548. deliveryDirectives = data.deliveryDirectives;
  3549. this.load({
  3550. id: id,
  3551. groupId: groupId,
  3552. level: null,
  3553. responseType: 'text',
  3554. type: PlaylistContextType.AUDIO_TRACK,
  3555. url: url,
  3556. deliveryDirectives: deliveryDirectives
  3557. });
  3558. };
  3559. _proto.onSubtitleTrackLoading = function onSubtitleTrackLoading(event, data) {
  3560. var id = data.id,
  3561. groupId = data.groupId,
  3562. url = data.url,
  3563. deliveryDirectives = data.deliveryDirectives;
  3564. this.load({
  3565. id: id,
  3566. groupId: groupId,
  3567. level: null,
  3568. responseType: 'text',
  3569. type: PlaylistContextType.SUBTITLE_TRACK,
  3570. url: url,
  3571. deliveryDirectives: deliveryDirectives
  3572. });
  3573. };
  3574. _proto.load = function load(context) {
  3575. var _context$deliveryDire,
  3576. _this = this;
  3577. var config = this.hls.config;
  3578. // logger.debug(`[playlist-loader]: Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);
  3579. // Check if a loader for this context already exists
  3580. var loader = this.getInternalLoader(context);
  3581. if (loader) {
  3582. var loaderContext = loader.context;
  3583. if (loaderContext && loaderContext.url === context.url && loaderContext.level === context.level) {
  3584. // same URL can't overlap
  3585. logger.trace('[playlist-loader]: playlist request ongoing');
  3586. return;
  3587. }
  3588. logger.log("[playlist-loader]: aborting previous loader for type: " + context.type);
  3589. loader.abort();
  3590. }
  3591. // apply different configs for retries depending on
  3592. // context (manifest, level, audio/subs playlist)
  3593. var loadPolicy;
  3594. if (context.type === PlaylistContextType.MANIFEST) {
  3595. loadPolicy = config.manifestLoadPolicy.default;
  3596. } else {
  3597. loadPolicy = _extends({}, config.playlistLoadPolicy.default, {
  3598. timeoutRetry: null,
  3599. errorRetry: null
  3600. });
  3601. }
  3602. loader = this.createInternalLoader(context);
  3603. // Override level/track timeout for LL-HLS requests
  3604. // (the default of 10000ms is counter productive to blocking playlist reload requests)
  3605. if (isFiniteNumber((_context$deliveryDire = context.deliveryDirectives) == null ? void 0 : _context$deliveryDire.part)) {
  3606. var levelDetails;
  3607. if (context.type === PlaylistContextType.LEVEL && context.level !== null) {
  3608. levelDetails = this.hls.levels[context.level].details;
  3609. } else if (context.type === PlaylistContextType.AUDIO_TRACK && context.id !== null) {
  3610. levelDetails = this.hls.audioTracks[context.id].details;
  3611. } else if (context.type === PlaylistContextType.SUBTITLE_TRACK && context.id !== null) {
  3612. levelDetails = this.hls.subtitleTracks[context.id].details;
  3613. }
  3614. if (levelDetails) {
  3615. var partTarget = levelDetails.partTarget;
  3616. var targetDuration = levelDetails.targetduration;
  3617. if (partTarget && targetDuration) {
  3618. var maxLowLatencyPlaylistRefresh = Math.max(partTarget * 3, targetDuration * 0.8) * 1000;
  3619. loadPolicy = _extends({}, loadPolicy, {
  3620. maxTimeToFirstByteMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs),
  3621. maxLoadTimeMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs)
  3622. });
  3623. }
  3624. }
  3625. }
  3626. var legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  3627. var loaderConfig = {
  3628. loadPolicy: loadPolicy,
  3629. timeout: loadPolicy.maxLoadTimeMs,
  3630. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  3631. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  3632. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  3633. };
  3634. var loaderCallbacks = {
  3635. onSuccess: function onSuccess(response, stats, context, networkDetails) {
  3636. var loader = _this.getInternalLoader(context);
  3637. _this.resetInternalLoader(context.type);
  3638. var string = response.data;
  3639. // Validate if it is an M3U8 at all
  3640. if (string.indexOf('#EXTM3U') !== 0) {
  3641. _this.handleManifestParsingError(response, context, new Error('no EXTM3U delimiter'), networkDetails || null, stats);
  3642. return;
  3643. }
  3644. stats.parsing.start = performance.now();
  3645. if (M3U8Parser.isMediaPlaylist(string)) {
  3646. _this.handleTrackOrLevelPlaylist(response, stats, context, networkDetails || null, loader);
  3647. } else {
  3648. _this.handleMasterPlaylist(response, stats, context, networkDetails);
  3649. }
  3650. },
  3651. onError: function onError(response, context, networkDetails, stats) {
  3652. _this.handleNetworkError(context, networkDetails, false, response, stats);
  3653. },
  3654. onTimeout: function onTimeout(stats, context, networkDetails) {
  3655. _this.handleNetworkError(context, networkDetails, true, undefined, stats);
  3656. }
  3657. };
  3658. // logger.debug(`[playlist-loader]: Calling internal loader delegate for URL: ${context.url}`);
  3659. loader.load(context, loaderConfig, loaderCallbacks);
  3660. };
  3661. _proto.handleMasterPlaylist = function handleMasterPlaylist(response, stats, context, networkDetails) {
  3662. var hls = this.hls;
  3663. var string = response.data;
  3664. var url = getResponseUrl(response, context);
  3665. var parsedResult = M3U8Parser.parseMasterPlaylist(string, url);
  3666. if (parsedResult.playlistParsingError) {
  3667. this.handleManifestParsingError(response, context, parsedResult.playlistParsingError, networkDetails, stats);
  3668. return;
  3669. }
  3670. var contentSteering = parsedResult.contentSteering,
  3671. levels = parsedResult.levels,
  3672. sessionData = parsedResult.sessionData,
  3673. sessionKeys = parsedResult.sessionKeys,
  3674. startTimeOffset = parsedResult.startTimeOffset,
  3675. variableList = parsedResult.variableList;
  3676. this.variableList = variableList;
  3677. var _M3U8Parser$parseMast = M3U8Parser.parseMasterPlaylistMedia(string, url, parsedResult),
  3678. _M3U8Parser$parseMast2 = _M3U8Parser$parseMast.AUDIO,
  3679. audioTracks = _M3U8Parser$parseMast2 === void 0 ? [] : _M3U8Parser$parseMast2,
  3680. subtitles = _M3U8Parser$parseMast.SUBTITLES,
  3681. captions = _M3U8Parser$parseMast['CLOSED-CAPTIONS'];
  3682. if (audioTracks.length) {
  3683. // check if we have found an audio track embedded in main playlist (audio track without URI attribute)
  3684. var embeddedAudioFound = audioTracks.some(function (audioTrack) {
  3685. return !audioTrack.url;
  3686. });
  3687. // if no embedded audio track defined, but audio codec signaled in quality level,
  3688. // we need to signal this main audio track this could happen with playlists with
  3689. // alt audio rendition in which quality levels (main)
  3690. // contains both audio+video. but with mixed audio track not signaled
  3691. if (!embeddedAudioFound && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
  3692. logger.log('[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one');
  3693. audioTracks.unshift({
  3694. type: 'main',
  3695. name: 'main',
  3696. groupId: 'main',
  3697. default: false,
  3698. autoselect: false,
  3699. forced: false,
  3700. id: -1,
  3701. attrs: new AttrList({}),
  3702. bitrate: 0,
  3703. url: ''
  3704. });
  3705. }
  3706. }
  3707. hls.trigger(Events.MANIFEST_LOADED, {
  3708. levels: levels,
  3709. audioTracks: audioTracks,
  3710. subtitles: subtitles,
  3711. captions: captions,
  3712. contentSteering: contentSteering,
  3713. url: url,
  3714. stats: stats,
  3715. networkDetails: networkDetails,
  3716. sessionData: sessionData,
  3717. sessionKeys: sessionKeys,
  3718. startTimeOffset: startTimeOffset,
  3719. variableList: variableList
  3720. });
  3721. };
  3722. _proto.handleTrackOrLevelPlaylist = function handleTrackOrLevelPlaylist(response, stats, context, networkDetails, loader) {
  3723. var hls = this.hls;
  3724. var id = context.id,
  3725. level = context.level,
  3726. type = context.type;
  3727. var url = getResponseUrl(response, context);
  3728. var levelUrlId = 0;
  3729. var levelId = isFiniteNumber(level) ? level : isFiniteNumber(id) ? id : 0;
  3730. var levelType = mapContextToLevelType(context);
  3731. var levelDetails = M3U8Parser.parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId, this.variableList);
  3732. // We have done our first request (Manifest-type) and receive
  3733. // not a master playlist but a chunk-list (track/level)
  3734. // We fire the manifest-loaded event anyway with the parsed level-details
  3735. // by creating a single-level structure for it.
  3736. if (type === PlaylistContextType.MANIFEST) {
  3737. var singleLevel = {
  3738. attrs: new AttrList({}),
  3739. bitrate: 0,
  3740. details: levelDetails,
  3741. name: '',
  3742. url: url
  3743. };
  3744. hls.trigger(Events.MANIFEST_LOADED, {
  3745. levels: [singleLevel],
  3746. audioTracks: [],
  3747. url: url,
  3748. stats: stats,
  3749. networkDetails: networkDetails,
  3750. sessionData: null,
  3751. sessionKeys: null,
  3752. contentSteering: null,
  3753. startTimeOffset: null,
  3754. variableList: null
  3755. });
  3756. }
  3757. // save parsing time
  3758. stats.parsing.end = performance.now();
  3759. // extend the context with the new levelDetails property
  3760. context.levelDetails = levelDetails;
  3761. this.handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader);
  3762. };
  3763. _proto.handleManifestParsingError = function handleManifestParsingError(response, context, error, networkDetails, stats) {
  3764. this.hls.trigger(Events.ERROR, {
  3765. type: ErrorTypes.NETWORK_ERROR,
  3766. details: ErrorDetails.MANIFEST_PARSING_ERROR,
  3767. fatal: context.type === PlaylistContextType.MANIFEST,
  3768. url: response.url,
  3769. err: error,
  3770. error: error,
  3771. reason: error.message,
  3772. response: response,
  3773. context: context,
  3774. networkDetails: networkDetails,
  3775. stats: stats
  3776. });
  3777. };
  3778. _proto.handleNetworkError = function handleNetworkError(context, networkDetails, timeout, response, stats) {
  3779. if (timeout === void 0) {
  3780. timeout = false;
  3781. }
  3782. var message = "A network " + (timeout ? 'timeout' : 'error' + (response ? ' (status ' + response.code + ')' : '')) + " occurred while loading " + context.type;
  3783. if (context.type === PlaylistContextType.LEVEL) {
  3784. message += ": " + context.level + " id: " + context.id;
  3785. } else if (context.type === PlaylistContextType.AUDIO_TRACK || context.type === PlaylistContextType.SUBTITLE_TRACK) {
  3786. message += " id: " + context.id + " group-id: \"" + context.groupId + "\"";
  3787. }
  3788. var error = new Error(message);
  3789. logger.warn("[playlist-loader]: " + message);
  3790. var details = ErrorDetails.UNKNOWN;
  3791. var fatal = false;
  3792. var loader = this.getInternalLoader(context);
  3793. switch (context.type) {
  3794. case PlaylistContextType.MANIFEST:
  3795. details = timeout ? ErrorDetails.MANIFEST_LOAD_TIMEOUT : ErrorDetails.MANIFEST_LOAD_ERROR;
  3796. fatal = true;
  3797. break;
  3798. case PlaylistContextType.LEVEL:
  3799. details = timeout ? ErrorDetails.LEVEL_LOAD_TIMEOUT : ErrorDetails.LEVEL_LOAD_ERROR;
  3800. fatal = false;
  3801. break;
  3802. case PlaylistContextType.AUDIO_TRACK:
  3803. details = timeout ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : ErrorDetails.AUDIO_TRACK_LOAD_ERROR;
  3804. fatal = false;
  3805. break;
  3806. case PlaylistContextType.SUBTITLE_TRACK:
  3807. details = timeout ? ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT : ErrorDetails.SUBTITLE_LOAD_ERROR;
  3808. fatal = false;
  3809. break;
  3810. }
  3811. if (loader) {
  3812. this.resetInternalLoader(context.type);
  3813. }
  3814. var errorData = {
  3815. type: ErrorTypes.NETWORK_ERROR,
  3816. details: details,
  3817. fatal: fatal,
  3818. url: context.url,
  3819. loader: loader,
  3820. context: context,
  3821. error: error,
  3822. networkDetails: networkDetails,
  3823. stats: stats
  3824. };
  3825. if (response) {
  3826. var url = (networkDetails == null ? void 0 : networkDetails.url) || context.url;
  3827. errorData.response = _objectSpread2({
  3828. url: url,
  3829. data: undefined
  3830. }, response);
  3831. }
  3832. this.hls.trigger(Events.ERROR, errorData);
  3833. };
  3834. _proto.handlePlaylistLoaded = function handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader) {
  3835. var hls = this.hls;
  3836. var type = context.type,
  3837. level = context.level,
  3838. id = context.id,
  3839. groupId = context.groupId,
  3840. deliveryDirectives = context.deliveryDirectives;
  3841. var url = getResponseUrl(response, context);
  3842. var parent = mapContextToLevelType(context);
  3843. var levelIndex = typeof context.level === 'number' && parent === PlaylistLevelType.MAIN ? level : undefined;
  3844. if (!levelDetails.fragments.length) {
  3845. var _error = new Error('No Segments found in Playlist');
  3846. hls.trigger(Events.ERROR, {
  3847. type: ErrorTypes.NETWORK_ERROR,
  3848. details: ErrorDetails.LEVEL_EMPTY_ERROR,
  3849. fatal: false,
  3850. url: url,
  3851. error: _error,
  3852. reason: _error.message,
  3853. response: response,
  3854. context: context,
  3855. level: levelIndex,
  3856. parent: parent,
  3857. networkDetails: networkDetails,
  3858. stats: stats
  3859. });
  3860. return;
  3861. }
  3862. if (!levelDetails.targetduration) {
  3863. levelDetails.playlistParsingError = new Error('Missing Target Duration');
  3864. }
  3865. var error = levelDetails.playlistParsingError;
  3866. if (error) {
  3867. hls.trigger(Events.ERROR, {
  3868. type: ErrorTypes.NETWORK_ERROR,
  3869. details: ErrorDetails.LEVEL_PARSING_ERROR,
  3870. fatal: false,
  3871. url: url,
  3872. error: error,
  3873. reason: error.message,
  3874. response: response,
  3875. context: context,
  3876. level: levelIndex,
  3877. parent: parent,
  3878. networkDetails: networkDetails,
  3879. stats: stats
  3880. });
  3881. return;
  3882. }
  3883. if (levelDetails.live && loader) {
  3884. if (loader.getCacheAge) {
  3885. levelDetails.ageHeader = loader.getCacheAge() || 0;
  3886. }
  3887. if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) {
  3888. levelDetails.ageHeader = 0;
  3889. }
  3890. }
  3891. switch (type) {
  3892. case PlaylistContextType.MANIFEST:
  3893. case PlaylistContextType.LEVEL:
  3894. hls.trigger(Events.LEVEL_LOADED, {
  3895. details: levelDetails,
  3896. level: levelIndex || 0,
  3897. id: id || 0,
  3898. stats: stats,
  3899. networkDetails: networkDetails,
  3900. deliveryDirectives: deliveryDirectives
  3901. });
  3902. break;
  3903. case PlaylistContextType.AUDIO_TRACK:
  3904. hls.trigger(Events.AUDIO_TRACK_LOADED, {
  3905. details: levelDetails,
  3906. id: id || 0,
  3907. groupId: groupId || '',
  3908. stats: stats,
  3909. networkDetails: networkDetails,
  3910. deliveryDirectives: deliveryDirectives
  3911. });
  3912. break;
  3913. case PlaylistContextType.SUBTITLE_TRACK:
  3914. hls.trigger(Events.SUBTITLE_TRACK_LOADED, {
  3915. details: levelDetails,
  3916. id: id || 0,
  3917. groupId: groupId || '',
  3918. stats: stats,
  3919. networkDetails: networkDetails,
  3920. deliveryDirectives: deliveryDirectives
  3921. });
  3922. break;
  3923. }
  3924. };
  3925. return PlaylistLoader;
  3926. }();
  3927. function sendAddTrackEvent(track, videoEl) {
  3928. var event;
  3929. try {
  3930. event = new Event('addtrack');
  3931. } catch (err) {
  3932. // for IE11
  3933. event = document.createEvent('Event');
  3934. event.initEvent('addtrack', false, false);
  3935. }
  3936. event.track = track;
  3937. videoEl.dispatchEvent(event);
  3938. }
  3939. function clearCurrentCues(track) {
  3940. // When track.mode is disabled, track.cues will be null.
  3941. // To guarantee the removal of cues, we need to temporarily
  3942. // change the mode to hidden
  3943. var mode = track.mode;
  3944. if (mode === 'disabled') {
  3945. track.mode = 'hidden';
  3946. }
  3947. if (track.cues) {
  3948. for (var i = track.cues.length; i--;) {
  3949. track.removeCue(track.cues[i]);
  3950. }
  3951. }
  3952. if (mode === 'disabled') {
  3953. track.mode = mode;
  3954. }
  3955. }
  3956. function removeCuesInRange(track, start, end, predicate) {
  3957. var mode = track.mode;
  3958. if (mode === 'disabled') {
  3959. track.mode = 'hidden';
  3960. }
  3961. if (track.cues && track.cues.length > 0) {
  3962. var cues = getCuesInRange(track.cues, start, end);
  3963. for (var i = 0; i < cues.length; i++) {
  3964. if (!predicate || predicate(cues[i])) {
  3965. track.removeCue(cues[i]);
  3966. }
  3967. }
  3968. }
  3969. if (mode === 'disabled') {
  3970. track.mode = mode;
  3971. }
  3972. }
  3973. // Find first cue starting after given time.
  3974. // Modified version of binary search O(log(n)).
  3975. function getFirstCueIndexAfterTime(cues, time) {
  3976. // If first cue starts after time, start there
  3977. if (time < cues[0].startTime) {
  3978. return 0;
  3979. }
  3980. // If the last cue ends before time there is no overlap
  3981. var len = cues.length - 1;
  3982. if (time > cues[len].endTime) {
  3983. return -1;
  3984. }
  3985. var left = 0;
  3986. var right = len;
  3987. while (left <= right) {
  3988. var mid = Math.floor((right + left) / 2);
  3989. if (time < cues[mid].startTime) {
  3990. right = mid - 1;
  3991. } else if (time > cues[mid].startTime && left < len) {
  3992. left = mid + 1;
  3993. } else {
  3994. // If it's not lower or higher, it must be equal.
  3995. return mid;
  3996. }
  3997. }
  3998. // At this point, left and right have swapped.
  3999. // No direct match was found, left or right element must be the closest. Check which one has the smallest diff.
  4000. return cues[left].startTime - time < time - cues[right].startTime ? left : right;
  4001. }
  4002. function getCuesInRange(cues, start, end) {
  4003. var cuesFound = [];
  4004. var firstCueInRange = getFirstCueIndexAfterTime(cues, start);
  4005. if (firstCueInRange > -1) {
  4006. for (var i = firstCueInRange, len = cues.length; i < len; i++) {
  4007. var _cue = cues[i];
  4008. if (_cue.startTime >= start && _cue.endTime <= end) {
  4009. cuesFound.push(_cue);
  4010. } else if (_cue.startTime > end) {
  4011. return cuesFound;
  4012. }
  4013. }
  4014. }
  4015. return cuesFound;
  4016. }
  4017. var MetadataSchema = {
  4018. audioId3: "org.id3",
  4019. dateRange: "com.apple.quicktime.HLS",
  4020. emsg: "https://aomedia.org/emsg/ID3"
  4021. };
  4022. var MIN_CUE_DURATION = 0.25;
  4023. function getCueClass() {
  4024. if (typeof self === 'undefined') return undefined;
  4025. return self.VTTCue || self.TextTrackCue;
  4026. }
  4027. function createCueWithDataFields(Cue, startTime, endTime, data, type) {
  4028. var cue = new Cue(startTime, endTime, '');
  4029. try {
  4030. cue.value = data;
  4031. if (type) {
  4032. cue.type = type;
  4033. }
  4034. } catch (e) {
  4035. cue = new Cue(startTime, endTime, JSON.stringify(type ? _objectSpread2({
  4036. type: type
  4037. }, data) : data));
  4038. }
  4039. return cue;
  4040. }
  4041. // VTTCue latest draft allows an infinite duration, fallback
  4042. // to MAX_VALUE if necessary
  4043. var MAX_CUE_ENDTIME = function () {
  4044. var Cue = getCueClass();
  4045. try {
  4046. Cue && new Cue(0, Number.POSITIVE_INFINITY, '');
  4047. } catch (e) {
  4048. return Number.MAX_VALUE;
  4049. }
  4050. return Number.POSITIVE_INFINITY;
  4051. }();
  4052. function dateRangeDateToTimelineSeconds(date, offset) {
  4053. return date.getTime() / 1000 - offset;
  4054. }
  4055. function hexToArrayBuffer(str) {
  4056. return Uint8Array.from(str.replace(/^0x/, '').replace(/([\da-fA-F]{2}) ?/g, '0x$1 ').replace(/ +$/, '').split(' ')).buffer;
  4057. }
  4058. var ID3TrackController = /*#__PURE__*/function () {
  4059. function ID3TrackController(hls) {
  4060. this.hls = void 0;
  4061. this.id3Track = null;
  4062. this.media = null;
  4063. this.dateRangeCuesAppended = {};
  4064. this.hls = hls;
  4065. this._registerListeners();
  4066. }
  4067. var _proto = ID3TrackController.prototype;
  4068. _proto.destroy = function destroy() {
  4069. this._unregisterListeners();
  4070. this.id3Track = null;
  4071. this.media = null;
  4072. this.dateRangeCuesAppended = {};
  4073. // @ts-ignore
  4074. this.hls = null;
  4075. };
  4076. _proto._registerListeners = function _registerListeners() {
  4077. var hls = this.hls;
  4078. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  4079. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  4080. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4081. hls.on(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  4082. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  4083. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  4084. };
  4085. _proto._unregisterListeners = function _unregisterListeners() {
  4086. var hls = this.hls;
  4087. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  4088. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  4089. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4090. hls.off(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  4091. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  4092. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  4093. }
  4094. // Add ID3 metatadata text track.
  4095. ;
  4096. _proto.onMediaAttached = function onMediaAttached(event, data) {
  4097. this.media = data.media;
  4098. };
  4099. _proto.onMediaDetaching = function onMediaDetaching() {
  4100. if (!this.id3Track) {
  4101. return;
  4102. }
  4103. clearCurrentCues(this.id3Track);
  4104. this.id3Track = null;
  4105. this.media = null;
  4106. this.dateRangeCuesAppended = {};
  4107. };
  4108. _proto.onManifestLoading = function onManifestLoading() {
  4109. this.dateRangeCuesAppended = {};
  4110. };
  4111. _proto.createTrack = function createTrack(media) {
  4112. var track = this.getID3Track(media.textTracks);
  4113. track.mode = 'hidden';
  4114. return track;
  4115. };
  4116. _proto.getID3Track = function getID3Track(textTracks) {
  4117. if (!this.media) {
  4118. return;
  4119. }
  4120. for (var i = 0; i < textTracks.length; i++) {
  4121. var textTrack = textTracks[i];
  4122. if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {
  4123. // send 'addtrack' when reusing the textTrack for metadata,
  4124. // same as what we do for captions
  4125. sendAddTrackEvent(textTrack, this.media);
  4126. return textTrack;
  4127. }
  4128. }
  4129. return this.media.addTextTrack('metadata', 'id3');
  4130. };
  4131. _proto.onFragParsingMetadata = function onFragParsingMetadata(event, data) {
  4132. if (!this.media) {
  4133. return;
  4134. }
  4135. var _this$hls$config = this.hls.config,
  4136. enableEmsgMetadataCues = _this$hls$config.enableEmsgMetadataCues,
  4137. enableID3MetadataCues = _this$hls$config.enableID3MetadataCues;
  4138. if (!enableEmsgMetadataCues && !enableID3MetadataCues) {
  4139. return;
  4140. }
  4141. var samples = data.samples;
  4142. // create track dynamically
  4143. if (!this.id3Track) {
  4144. this.id3Track = this.createTrack(this.media);
  4145. }
  4146. var Cue = getCueClass();
  4147. if (!Cue) {
  4148. return;
  4149. }
  4150. for (var i = 0; i < samples.length; i++) {
  4151. var type = samples[i].type;
  4152. if (type === MetadataSchema.emsg && !enableEmsgMetadataCues || !enableID3MetadataCues) {
  4153. continue;
  4154. }
  4155. var frames = getID3Frames(samples[i].data);
  4156. if (frames) {
  4157. var startTime = samples[i].pts;
  4158. var endTime = startTime + samples[i].duration;
  4159. if (endTime > MAX_CUE_ENDTIME) {
  4160. endTime = MAX_CUE_ENDTIME;
  4161. }
  4162. var timeDiff = endTime - startTime;
  4163. if (timeDiff <= 0) {
  4164. endTime = startTime + MIN_CUE_DURATION;
  4165. }
  4166. for (var j = 0; j < frames.length; j++) {
  4167. var frame = frames[j];
  4168. // Safari doesn't put the timestamp frame in the TextTrack
  4169. if (!isTimeStampFrame(frame)) {
  4170. // add a bounds to any unbounded cues
  4171. this.updateId3CueEnds(startTime, type);
  4172. var cue = createCueWithDataFields(Cue, startTime, endTime, frame, type);
  4173. if (cue) {
  4174. this.id3Track.addCue(cue);
  4175. }
  4176. }
  4177. }
  4178. }
  4179. }
  4180. };
  4181. _proto.updateId3CueEnds = function updateId3CueEnds(startTime, type) {
  4182. var _this$id3Track;
  4183. var cues = (_this$id3Track = this.id3Track) == null ? void 0 : _this$id3Track.cues;
  4184. if (cues) {
  4185. for (var i = cues.length; i--;) {
  4186. var cue = cues[i];
  4187. if (cue.type === type && cue.startTime < startTime && cue.endTime === MAX_CUE_ENDTIME) {
  4188. cue.endTime = startTime;
  4189. }
  4190. }
  4191. }
  4192. };
  4193. _proto.onBufferFlushing = function onBufferFlushing(event, _ref) {
  4194. var startOffset = _ref.startOffset,
  4195. endOffset = _ref.endOffset,
  4196. type = _ref.type;
  4197. var id3Track = this.id3Track,
  4198. hls = this.hls;
  4199. if (!hls) {
  4200. return;
  4201. }
  4202. var _hls$config = hls.config,
  4203. enableEmsgMetadataCues = _hls$config.enableEmsgMetadataCues,
  4204. enableID3MetadataCues = _hls$config.enableID3MetadataCues;
  4205. if (id3Track && (enableEmsgMetadataCues || enableID3MetadataCues)) {
  4206. var predicate;
  4207. if (type === 'audio') {
  4208. predicate = function predicate(cue) {
  4209. return cue.type === MetadataSchema.audioId3 && enableID3MetadataCues;
  4210. };
  4211. } else if (type === 'video') {
  4212. predicate = function predicate(cue) {
  4213. return cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  4214. };
  4215. } else {
  4216. predicate = function predicate(cue) {
  4217. return cue.type === MetadataSchema.audioId3 && enableID3MetadataCues || cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  4218. };
  4219. }
  4220. removeCuesInRange(id3Track, startOffset, endOffset, predicate);
  4221. }
  4222. };
  4223. _proto.onLevelUpdated = function onLevelUpdated(event, _ref2) {
  4224. var _this = this;
  4225. var details = _ref2.details;
  4226. if (!this.media || !details.hasProgramDateTime || !this.hls.config.enableDateRangeMetadataCues) {
  4227. return;
  4228. }
  4229. var dateRangeCuesAppended = this.dateRangeCuesAppended,
  4230. id3Track = this.id3Track;
  4231. var dateRanges = details.dateRanges;
  4232. var ids = Object.keys(dateRanges);
  4233. // Remove cues from track not found in details.dateRanges
  4234. if (id3Track) {
  4235. var idsToRemove = Object.keys(dateRangeCuesAppended).filter(function (id) {
  4236. return !ids.includes(id);
  4237. });
  4238. var _loop = function _loop() {
  4239. var id = idsToRemove[i];
  4240. Object.keys(dateRangeCuesAppended[id].cues).forEach(function (key) {
  4241. id3Track.removeCue(dateRangeCuesAppended[id].cues[key]);
  4242. });
  4243. delete dateRangeCuesAppended[id];
  4244. };
  4245. for (var i = idsToRemove.length; i--;) {
  4246. _loop();
  4247. }
  4248. }
  4249. // Exit if the playlist does not have Date Ranges or does not have Program Date Time
  4250. var lastFragment = details.fragments[details.fragments.length - 1];
  4251. if (ids.length === 0 || !isFiniteNumber(lastFragment == null ? void 0 : lastFragment.programDateTime)) {
  4252. return;
  4253. }
  4254. if (!this.id3Track) {
  4255. this.id3Track = this.createTrack(this.media);
  4256. }
  4257. var dateTimeOffset = lastFragment.programDateTime / 1000 - lastFragment.start;
  4258. var Cue = getCueClass();
  4259. var _loop2 = function _loop2() {
  4260. var id = ids[_i];
  4261. var dateRange = dateRanges[id];
  4262. var startTime = dateRangeDateToTimelineSeconds(dateRange.startDate, dateTimeOffset);
  4263. // Process DateRanges to determine end-time (known DURATION, END-DATE, or END-ON-NEXT)
  4264. var appendedDateRangeCues = dateRangeCuesAppended[id];
  4265. var cues = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.cues) || {};
  4266. var durationKnown = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.durationKnown) || false;
  4267. var endTime = MAX_CUE_ENDTIME;
  4268. var endDate = dateRange.endDate;
  4269. if (endDate) {
  4270. endTime = dateRangeDateToTimelineSeconds(endDate, dateTimeOffset);
  4271. durationKnown = true;
  4272. } else if (dateRange.endOnNext && !durationKnown) {
  4273. var nextDateRangeWithSameClass = ids.reduce(function (candidateDateRange, id) {
  4274. if (id !== dateRange.id) {
  4275. var otherDateRange = dateRanges[id];
  4276. if (otherDateRange.class === dateRange.class && otherDateRange.startDate > dateRange.startDate && (!candidateDateRange || dateRange.startDate < candidateDateRange.startDate)) {
  4277. return otherDateRange;
  4278. }
  4279. }
  4280. return candidateDateRange;
  4281. }, null);
  4282. if (nextDateRangeWithSameClass) {
  4283. endTime = dateRangeDateToTimelineSeconds(nextDateRangeWithSameClass.startDate, dateTimeOffset);
  4284. durationKnown = true;
  4285. }
  4286. }
  4287. // Create TextTrack Cues for each MetadataGroup Item (select DateRange attribute)
  4288. // This is to emulate Safari HLS playback handling of DateRange tags
  4289. var attributes = Object.keys(dateRange.attr);
  4290. for (var j = 0; j < attributes.length; j++) {
  4291. var key = attributes[j];
  4292. if (!isDateRangeCueAttribute(key)) {
  4293. continue;
  4294. }
  4295. var cue = cues[key];
  4296. if (cue) {
  4297. if (durationKnown && !appendedDateRangeCues.durationKnown) {
  4298. cue.endTime = endTime;
  4299. }
  4300. } else if (Cue) {
  4301. var data = dateRange.attr[key];
  4302. if (isSCTE35Attribute(key)) {
  4303. data = hexToArrayBuffer(data);
  4304. }
  4305. var _cue = createCueWithDataFields(Cue, startTime, endTime, {
  4306. key: key,
  4307. data: data
  4308. }, MetadataSchema.dateRange);
  4309. if (_cue) {
  4310. _cue.id = id;
  4311. _this.id3Track.addCue(_cue);
  4312. cues[key] = _cue;
  4313. }
  4314. }
  4315. }
  4316. // Keep track of processed DateRanges by ID for updating cues with new DateRange tag attributes
  4317. dateRangeCuesAppended[id] = {
  4318. cues: cues,
  4319. dateRange: dateRange,
  4320. durationKnown: durationKnown
  4321. };
  4322. };
  4323. for (var _i = 0; _i < ids.length; _i++) {
  4324. _loop2();
  4325. }
  4326. };
  4327. return ID3TrackController;
  4328. }();
  4329. var LatencyController = /*#__PURE__*/function () {
  4330. function LatencyController(hls) {
  4331. var _this = this;
  4332. this.hls = void 0;
  4333. this.config = void 0;
  4334. this.media = null;
  4335. this.levelDetails = null;
  4336. this.currentTime = 0;
  4337. this.stallCount = 0;
  4338. this._latency = null;
  4339. this.timeupdateHandler = function () {
  4340. return _this.timeupdate();
  4341. };
  4342. this.hls = hls;
  4343. this.config = hls.config;
  4344. this.registerListeners();
  4345. }
  4346. var _proto = LatencyController.prototype;
  4347. _proto.destroy = function destroy() {
  4348. this.unregisterListeners();
  4349. this.onMediaDetaching();
  4350. this.levelDetails = null;
  4351. // @ts-ignore
  4352. this.hls = this.timeupdateHandler = null;
  4353. };
  4354. _proto.registerListeners = function registerListeners() {
  4355. this.hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  4356. this.hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  4357. this.hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4358. this.hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  4359. this.hls.on(Events.ERROR, this.onError, this);
  4360. };
  4361. _proto.unregisterListeners = function unregisterListeners() {
  4362. this.hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  4363. this.hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  4364. this.hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4365. this.hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  4366. this.hls.off(Events.ERROR, this.onError, this);
  4367. };
  4368. _proto.onMediaAttached = function onMediaAttached(event, data) {
  4369. this.media = data.media;
  4370. this.media.addEventListener('timeupdate', this.timeupdateHandler);
  4371. };
  4372. _proto.onMediaDetaching = function onMediaDetaching() {
  4373. if (this.media) {
  4374. this.media.removeEventListener('timeupdate', this.timeupdateHandler);
  4375. this.media = null;
  4376. }
  4377. };
  4378. _proto.onManifestLoading = function onManifestLoading() {
  4379. this.levelDetails = null;
  4380. this._latency = null;
  4381. this.stallCount = 0;
  4382. };
  4383. _proto.onLevelUpdated = function onLevelUpdated(event, _ref) {
  4384. var details = _ref.details;
  4385. this.levelDetails = details;
  4386. if (details.advanced) {
  4387. this.timeupdate();
  4388. }
  4389. if (!details.live && this.media) {
  4390. this.media.removeEventListener('timeupdate', this.timeupdateHandler);
  4391. }
  4392. };
  4393. _proto.onError = function onError(event, data) {
  4394. var _this$levelDetails;
  4395. if (data.details !== ErrorDetails.BUFFER_STALLED_ERROR) {
  4396. return;
  4397. }
  4398. this.stallCount++;
  4399. if ((_this$levelDetails = this.levelDetails) != null && _this$levelDetails.live) {
  4400. logger.warn('[playback-rate-controller]: Stall detected, adjusting target latency');
  4401. }
  4402. };
  4403. _proto.timeupdate = function timeupdate() {
  4404. var media = this.media,
  4405. levelDetails = this.levelDetails;
  4406. if (!media || !levelDetails) {
  4407. return;
  4408. }
  4409. this.currentTime = media.currentTime;
  4410. var latency = this.computeLatency();
  4411. if (latency === null) {
  4412. return;
  4413. }
  4414. this._latency = latency;
  4415. // Adapt playbackRate to meet target latency in low-latency mode
  4416. var _this$config = this.config,
  4417. lowLatencyMode = _this$config.lowLatencyMode,
  4418. maxLiveSyncPlaybackRate = _this$config.maxLiveSyncPlaybackRate;
  4419. if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1 || !levelDetails.live) {
  4420. return;
  4421. }
  4422. var targetLatency = this.targetLatency;
  4423. if (targetLatency === null) {
  4424. return;
  4425. }
  4426. var distanceFromTarget = latency - targetLatency;
  4427. // Only adjust playbackRate when within one target duration of targetLatency
  4428. // and more than one second from under-buffering.
  4429. // Playback further than one target duration from target can be considered DVR playback.
  4430. var liveMinLatencyDuration = Math.min(this.maxLatency, targetLatency + levelDetails.targetduration);
  4431. var inLiveRange = distanceFromTarget < liveMinLatencyDuration;
  4432. if (inLiveRange && distanceFromTarget > 0.05 && this.forwardBufferLength > 1) {
  4433. var max = Math.min(2, Math.max(1.0, maxLiveSyncPlaybackRate));
  4434. var rate = Math.round(2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled)) * 20) / 20;
  4435. media.playbackRate = Math.min(max, Math.max(1, rate));
  4436. } else if (media.playbackRate !== 1 && media.playbackRate !== 0) {
  4437. media.playbackRate = 1;
  4438. }
  4439. };
  4440. _proto.estimateLiveEdge = function estimateLiveEdge() {
  4441. var levelDetails = this.levelDetails;
  4442. if (levelDetails === null) {
  4443. return null;
  4444. }
  4445. return levelDetails.edge + levelDetails.age;
  4446. };
  4447. _proto.computeLatency = function computeLatency() {
  4448. var liveEdge = this.estimateLiveEdge();
  4449. if (liveEdge === null) {
  4450. return null;
  4451. }
  4452. return liveEdge - this.currentTime;
  4453. };
  4454. _createClass(LatencyController, [{
  4455. key: "latency",
  4456. get: function get() {
  4457. return this._latency || 0;
  4458. }
  4459. }, {
  4460. key: "maxLatency",
  4461. get: function get() {
  4462. var config = this.config,
  4463. levelDetails = this.levelDetails;
  4464. if (config.liveMaxLatencyDuration !== undefined) {
  4465. return config.liveMaxLatencyDuration;
  4466. }
  4467. return levelDetails ? config.liveMaxLatencyDurationCount * levelDetails.targetduration : 0;
  4468. }
  4469. }, {
  4470. key: "targetLatency",
  4471. get: function get() {
  4472. var levelDetails = this.levelDetails;
  4473. if (levelDetails === null) {
  4474. return null;
  4475. }
  4476. var holdBack = levelDetails.holdBack,
  4477. partHoldBack = levelDetails.partHoldBack,
  4478. targetduration = levelDetails.targetduration;
  4479. var _this$config2 = this.config,
  4480. liveSyncDuration = _this$config2.liveSyncDuration,
  4481. liveSyncDurationCount = _this$config2.liveSyncDurationCount,
  4482. lowLatencyMode = _this$config2.lowLatencyMode;
  4483. var userConfig = this.hls.userConfig;
  4484. var targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack;
  4485. if (userConfig.liveSyncDuration || userConfig.liveSyncDurationCount || targetLatency === 0) {
  4486. targetLatency = liveSyncDuration !== undefined ? liveSyncDuration : liveSyncDurationCount * targetduration;
  4487. }
  4488. var maxLiveSyncOnStallIncrease = targetduration;
  4489. var liveSyncOnStallIncrease = 1.0;
  4490. return targetLatency + Math.min(this.stallCount * liveSyncOnStallIncrease, maxLiveSyncOnStallIncrease);
  4491. }
  4492. }, {
  4493. key: "liveSyncPosition",
  4494. get: function get() {
  4495. var liveEdge = this.estimateLiveEdge();
  4496. var targetLatency = this.targetLatency;
  4497. var levelDetails = this.levelDetails;
  4498. if (liveEdge === null || targetLatency === null || levelDetails === null) {
  4499. return null;
  4500. }
  4501. var edge = levelDetails.edge;
  4502. var syncPosition = liveEdge - targetLatency - this.edgeStalled;
  4503. var min = edge - levelDetails.totalduration;
  4504. var max = edge - (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration);
  4505. return Math.min(Math.max(min, syncPosition), max);
  4506. }
  4507. }, {
  4508. key: "drift",
  4509. get: function get() {
  4510. var levelDetails = this.levelDetails;
  4511. if (levelDetails === null) {
  4512. return 1;
  4513. }
  4514. return levelDetails.drift;
  4515. }
  4516. }, {
  4517. key: "edgeStalled",
  4518. get: function get() {
  4519. var levelDetails = this.levelDetails;
  4520. if (levelDetails === null) {
  4521. return 0;
  4522. }
  4523. var maxLevelUpdateAge = (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration) * 3;
  4524. return Math.max(levelDetails.age - maxLevelUpdateAge, 0);
  4525. }
  4526. }, {
  4527. key: "forwardBufferLength",
  4528. get: function get() {
  4529. var media = this.media,
  4530. levelDetails = this.levelDetails;
  4531. if (!media || !levelDetails) {
  4532. return 0;
  4533. }
  4534. var bufferedRanges = media.buffered.length;
  4535. return (bufferedRanges ? media.buffered.end(bufferedRanges - 1) : levelDetails.edge) - this.currentTime;
  4536. }
  4537. }]);
  4538. return LatencyController;
  4539. }();
  4540. var HdcpLevels = ['NONE', 'TYPE-0', 'TYPE-1', null];
  4541. function isHdcpLevel(value) {
  4542. return HdcpLevels.indexOf(value) > -1;
  4543. }
  4544. var VideoRangeValues = ['SDR', 'PQ', 'HLG'];
  4545. function isVideoRange(value) {
  4546. return !!value && VideoRangeValues.indexOf(value) > -1;
  4547. }
  4548. var HlsSkip = {
  4549. No: "",
  4550. Yes: "YES",
  4551. v2: "v2"
  4552. };
  4553. function getSkipValue(details) {
  4554. var canSkipUntil = details.canSkipUntil,
  4555. canSkipDateRanges = details.canSkipDateRanges,
  4556. age = details.age;
  4557. // A Client SHOULD NOT request a Playlist Delta Update unless it already
  4558. // has a version of the Playlist that is no older than one-half of the Skip Boundary.
  4559. // @see: https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis#section-6.3.7
  4560. var playlistRecentEnough = age < canSkipUntil / 2;
  4561. if (canSkipUntil && playlistRecentEnough) {
  4562. if (canSkipDateRanges) {
  4563. return HlsSkip.v2;
  4564. }
  4565. return HlsSkip.Yes;
  4566. }
  4567. return HlsSkip.No;
  4568. }
  4569. var HlsUrlParameters = /*#__PURE__*/function () {
  4570. function HlsUrlParameters(msn, part, skip) {
  4571. this.msn = void 0;
  4572. this.part = void 0;
  4573. this.skip = void 0;
  4574. this.msn = msn;
  4575. this.part = part;
  4576. this.skip = skip;
  4577. }
  4578. var _proto = HlsUrlParameters.prototype;
  4579. _proto.addDirectives = function addDirectives(uri) {
  4580. var url = new self.URL(uri);
  4581. if (this.msn !== undefined) {
  4582. url.searchParams.set('_HLS_msn', this.msn.toString());
  4583. }
  4584. if (this.part !== undefined) {
  4585. url.searchParams.set('_HLS_part', this.part.toString());
  4586. }
  4587. if (this.skip) {
  4588. url.searchParams.set('_HLS_skip', this.skip);
  4589. }
  4590. return url.href;
  4591. };
  4592. return HlsUrlParameters;
  4593. }();
  4594. var Level = /*#__PURE__*/function () {
  4595. function Level(data) {
  4596. this._attrs = void 0;
  4597. this.audioCodec = void 0;
  4598. this.bitrate = void 0;
  4599. this.codecSet = void 0;
  4600. this.url = void 0;
  4601. this.frameRate = void 0;
  4602. this.height = void 0;
  4603. this.id = void 0;
  4604. this.name = void 0;
  4605. this.videoCodec = void 0;
  4606. this.width = void 0;
  4607. this.details = void 0;
  4608. this.fragmentError = 0;
  4609. this.loadError = 0;
  4610. this.loaded = void 0;
  4611. this.realBitrate = 0;
  4612. this.supportedPromise = void 0;
  4613. this.supportedResult = void 0;
  4614. this._avgBitrate = 0;
  4615. this._audioGroups = void 0;
  4616. this._subtitleGroups = void 0;
  4617. // Deprecated (retained for backwards compatibility)
  4618. this._urlId = 0;
  4619. this.url = [data.url];
  4620. this._attrs = [data.attrs];
  4621. this.bitrate = data.bitrate;
  4622. if (data.details) {
  4623. this.details = data.details;
  4624. }
  4625. this.id = data.id || 0;
  4626. this.name = data.name;
  4627. this.width = data.width || 0;
  4628. this.height = data.height || 0;
  4629. this.frameRate = data.attrs.optionalFloat('FRAME-RATE', 0);
  4630. this._avgBitrate = data.attrs.decimalInteger('AVERAGE-BANDWIDTH');
  4631. this.audioCodec = data.audioCodec;
  4632. this.videoCodec = data.videoCodec;
  4633. this.codecSet = [data.videoCodec, data.audioCodec].filter(function (c) {
  4634. return !!c;
  4635. }).map(function (s) {
  4636. return s.substring(0, 4);
  4637. }).join(',');
  4638. this.addGroupId('audio', data.attrs.AUDIO);
  4639. this.addGroupId('text', data.attrs.SUBTITLES);
  4640. }
  4641. var _proto2 = Level.prototype;
  4642. _proto2.hasAudioGroup = function hasAudioGroup(groupId) {
  4643. return hasGroup(this._audioGroups, groupId);
  4644. };
  4645. _proto2.hasSubtitleGroup = function hasSubtitleGroup(groupId) {
  4646. return hasGroup(this._subtitleGroups, groupId);
  4647. };
  4648. _proto2.addGroupId = function addGroupId(type, groupId) {
  4649. if (!groupId) {
  4650. return;
  4651. }
  4652. if (type === 'audio') {
  4653. var audioGroups = this._audioGroups;
  4654. if (!audioGroups) {
  4655. audioGroups = this._audioGroups = [];
  4656. }
  4657. if (audioGroups.indexOf(groupId) === -1) {
  4658. audioGroups.push(groupId);
  4659. }
  4660. } else if (type === 'text') {
  4661. var subtitleGroups = this._subtitleGroups;
  4662. if (!subtitleGroups) {
  4663. subtitleGroups = this._subtitleGroups = [];
  4664. }
  4665. if (subtitleGroups.indexOf(groupId) === -1) {
  4666. subtitleGroups.push(groupId);
  4667. }
  4668. }
  4669. }
  4670. // Deprecated methods (retained for backwards compatibility)
  4671. ;
  4672. _proto2.addFallback = function addFallback() {};
  4673. _createClass(Level, [{
  4674. key: "maxBitrate",
  4675. get: function get() {
  4676. return Math.max(this.realBitrate, this.bitrate);
  4677. }
  4678. }, {
  4679. key: "averageBitrate",
  4680. get: function get() {
  4681. return this._avgBitrate || this.realBitrate || this.bitrate;
  4682. }
  4683. }, {
  4684. key: "attrs",
  4685. get: function get() {
  4686. return this._attrs[0];
  4687. }
  4688. }, {
  4689. key: "codecs",
  4690. get: function get() {
  4691. return this.attrs.CODECS || '';
  4692. }
  4693. }, {
  4694. key: "pathwayId",
  4695. get: function get() {
  4696. return this.attrs['PATHWAY-ID'] || '.';
  4697. }
  4698. }, {
  4699. key: "videoRange",
  4700. get: function get() {
  4701. return this.attrs['VIDEO-RANGE'] || 'SDR';
  4702. }
  4703. }, {
  4704. key: "score",
  4705. get: function get() {
  4706. return this.attrs.optionalFloat('SCORE', 0);
  4707. }
  4708. }, {
  4709. key: "uri",
  4710. get: function get() {
  4711. return this.url[0] || '';
  4712. }
  4713. }, {
  4714. key: "audioGroups",
  4715. get: function get() {
  4716. return this._audioGroups;
  4717. }
  4718. }, {
  4719. key: "subtitleGroups",
  4720. get: function get() {
  4721. return this._subtitleGroups;
  4722. }
  4723. }, {
  4724. key: "urlId",
  4725. get: function get() {
  4726. return 0;
  4727. },
  4728. set: function set(value) {}
  4729. }, {
  4730. key: "audioGroupIds",
  4731. get: function get() {
  4732. return this.audioGroups ? [this.audioGroupId] : undefined;
  4733. }
  4734. }, {
  4735. key: "textGroupIds",
  4736. get: function get() {
  4737. return this.subtitleGroups ? [this.textGroupId] : undefined;
  4738. }
  4739. }, {
  4740. key: "audioGroupId",
  4741. get: function get() {
  4742. var _this$audioGroups;
  4743. return (_this$audioGroups = this.audioGroups) == null ? void 0 : _this$audioGroups[0];
  4744. }
  4745. }, {
  4746. key: "textGroupId",
  4747. get: function get() {
  4748. var _this$subtitleGroups;
  4749. return (_this$subtitleGroups = this.subtitleGroups) == null ? void 0 : _this$subtitleGroups[0];
  4750. }
  4751. }]);
  4752. return Level;
  4753. }();
  4754. function hasGroup(groups, groupId) {
  4755. if (!groupId || !groups) {
  4756. return false;
  4757. }
  4758. return groups.indexOf(groupId) !== -1;
  4759. }
  4760. function updateFromToPTS(fragFrom, fragTo) {
  4761. var fragToPTS = fragTo.startPTS;
  4762. // if we know startPTS[toIdx]
  4763. if (isFiniteNumber(fragToPTS)) {
  4764. // update fragment duration.
  4765. // it helps to fix drifts between playlist reported duration and fragment real duration
  4766. var duration = 0;
  4767. var frag;
  4768. if (fragTo.sn > fragFrom.sn) {
  4769. duration = fragToPTS - fragFrom.start;
  4770. frag = fragFrom;
  4771. } else {
  4772. duration = fragFrom.start - fragToPTS;
  4773. frag = fragTo;
  4774. }
  4775. if (frag.duration !== duration) {
  4776. frag.duration = duration;
  4777. }
  4778. // we dont know startPTS[toIdx]
  4779. } else if (fragTo.sn > fragFrom.sn) {
  4780. var contiguous = fragFrom.cc === fragTo.cc;
  4781. // TODO: With part-loading end/durations we need to confirm the whole fragment is loaded before using (or setting) minEndPTS
  4782. if (contiguous && fragFrom.minEndPTS) {
  4783. fragTo.start = fragFrom.start + (fragFrom.minEndPTS - fragFrom.start);
  4784. } else {
  4785. fragTo.start = fragFrom.start + fragFrom.duration;
  4786. }
  4787. } else {
  4788. fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);
  4789. }
  4790. }
  4791. function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
  4792. var parsedMediaDuration = endPTS - startPTS;
  4793. if (parsedMediaDuration <= 0) {
  4794. logger.warn('Fragment should have a positive duration', frag);
  4795. endPTS = startPTS + frag.duration;
  4796. endDTS = startDTS + frag.duration;
  4797. }
  4798. var maxStartPTS = startPTS;
  4799. var minEndPTS = endPTS;
  4800. var fragStartPts = frag.startPTS;
  4801. var fragEndPts = frag.endPTS;
  4802. if (isFiniteNumber(fragStartPts)) {
  4803. // delta PTS between audio and video
  4804. var deltaPTS = Math.abs(fragStartPts - startPTS);
  4805. if (!isFiniteNumber(frag.deltaPTS)) {
  4806. frag.deltaPTS = deltaPTS;
  4807. } else {
  4808. frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
  4809. }
  4810. maxStartPTS = Math.max(startPTS, fragStartPts);
  4811. startPTS = Math.min(startPTS, fragStartPts);
  4812. startDTS = Math.min(startDTS, frag.startDTS);
  4813. minEndPTS = Math.min(endPTS, fragEndPts);
  4814. endPTS = Math.max(endPTS, fragEndPts);
  4815. endDTS = Math.max(endDTS, frag.endDTS);
  4816. }
  4817. var drift = startPTS - frag.start;
  4818. if (frag.start !== 0) {
  4819. frag.start = startPTS;
  4820. }
  4821. frag.duration = endPTS - frag.start;
  4822. frag.startPTS = startPTS;
  4823. frag.maxStartPTS = maxStartPTS;
  4824. frag.startDTS = startDTS;
  4825. frag.endPTS = endPTS;
  4826. frag.minEndPTS = minEndPTS;
  4827. frag.endDTS = endDTS;
  4828. var sn = frag.sn; // 'initSegment'
  4829. // exit if sn out of range
  4830. if (!details || sn < details.startSN || sn > details.endSN) {
  4831. return 0;
  4832. }
  4833. var i;
  4834. var fragIdx = sn - details.startSN;
  4835. var fragments = details.fragments;
  4836. // update frag reference in fragments array
  4837. // rationale is that fragments array might not contain this frag object.
  4838. // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()
  4839. // if we don't update frag, we won't be able to propagate PTS info on the playlist
  4840. // resulting in invalid sliding computation
  4841. fragments[fragIdx] = frag;
  4842. // adjust fragment PTS/duration from seqnum-1 to frag 0
  4843. for (i = fragIdx; i > 0; i--) {
  4844. updateFromToPTS(fragments[i], fragments[i - 1]);
  4845. }
  4846. // adjust fragment PTS/duration from seqnum to last frag
  4847. for (i = fragIdx; i < fragments.length - 1; i++) {
  4848. updateFromToPTS(fragments[i], fragments[i + 1]);
  4849. }
  4850. if (details.fragmentHint) {
  4851. updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint);
  4852. }
  4853. details.PTSKnown = details.alignedSliding = true;
  4854. return drift;
  4855. }
  4856. function mergeDetails(oldDetails, newDetails) {
  4857. // Track the last initSegment processed. Initialize it to the last one on the timeline.
  4858. var currentInitSegment = null;
  4859. var oldFragments = oldDetails.fragments;
  4860. for (var i = oldFragments.length - 1; i >= 0; i--) {
  4861. var oldInit = oldFragments[i].initSegment;
  4862. if (oldInit) {
  4863. currentInitSegment = oldInit;
  4864. break;
  4865. }
  4866. }
  4867. if (oldDetails.fragmentHint) {
  4868. // prevent PTS and duration from being adjusted on the next hint
  4869. delete oldDetails.fragmentHint.endPTS;
  4870. }
  4871. // check if old/new playlists have fragments in common
  4872. // loop through overlapping SN and update startPTS , cc, and duration if any found
  4873. var ccOffset = 0;
  4874. var PTSFrag;
  4875. mapFragmentIntersection(oldDetails, newDetails, function (oldFrag, newFrag) {
  4876. if (oldFrag.relurl) {
  4877. // Do not compare CC if the old fragment has no url. This is a level.fragmentHint used by LL-HLS parts.
  4878. // It maybe be off by 1 if it was created before any parts or discontinuity tags were appended to the end
  4879. // of the playlist.
  4880. ccOffset = oldFrag.cc - newFrag.cc;
  4881. }
  4882. if (isFiniteNumber(oldFrag.startPTS) && isFiniteNumber(oldFrag.endPTS)) {
  4883. newFrag.start = newFrag.startPTS = oldFrag.startPTS;
  4884. newFrag.startDTS = oldFrag.startDTS;
  4885. newFrag.maxStartPTS = oldFrag.maxStartPTS;
  4886. newFrag.endPTS = oldFrag.endPTS;
  4887. newFrag.endDTS = oldFrag.endDTS;
  4888. newFrag.minEndPTS = oldFrag.minEndPTS;
  4889. newFrag.duration = oldFrag.endPTS - oldFrag.startPTS;
  4890. if (newFrag.duration) {
  4891. PTSFrag = newFrag;
  4892. }
  4893. // PTS is known when any segment has startPTS and endPTS
  4894. newDetails.PTSKnown = newDetails.alignedSliding = true;
  4895. }
  4896. newFrag.elementaryStreams = oldFrag.elementaryStreams;
  4897. newFrag.loader = oldFrag.loader;
  4898. newFrag.stats = oldFrag.stats;
  4899. if (oldFrag.initSegment) {
  4900. newFrag.initSegment = oldFrag.initSegment;
  4901. currentInitSegment = oldFrag.initSegment;
  4902. }
  4903. });
  4904. if (currentInitSegment) {
  4905. var fragmentsToCheck = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
  4906. fragmentsToCheck.forEach(function (frag) {
  4907. var _currentInitSegment;
  4908. if (frag && (!frag.initSegment || frag.initSegment.relurl === ((_currentInitSegment = currentInitSegment) == null ? void 0 : _currentInitSegment.relurl))) {
  4909. frag.initSegment = currentInitSegment;
  4910. }
  4911. });
  4912. }
  4913. if (newDetails.skippedSegments) {
  4914. newDetails.deltaUpdateFailed = newDetails.fragments.some(function (frag) {
  4915. return !frag;
  4916. });
  4917. if (newDetails.deltaUpdateFailed) {
  4918. logger.warn('[level-helper] Previous playlist missing segments skipped in delta playlist');
  4919. for (var _i = newDetails.skippedSegments; _i--;) {
  4920. newDetails.fragments.shift();
  4921. }
  4922. newDetails.startSN = newDetails.fragments[0].sn;
  4923. newDetails.startCC = newDetails.fragments[0].cc;
  4924. } else if (newDetails.canSkipDateRanges) {
  4925. newDetails.dateRanges = mergeDateRanges(oldDetails.dateRanges, newDetails.dateRanges, newDetails.recentlyRemovedDateranges);
  4926. }
  4927. }
  4928. var newFragments = newDetails.fragments;
  4929. if (ccOffset) {
  4930. logger.warn('discontinuity sliding from playlist, take drift into account');
  4931. for (var _i2 = 0; _i2 < newFragments.length; _i2++) {
  4932. newFragments[_i2].cc += ccOffset;
  4933. }
  4934. }
  4935. if (newDetails.skippedSegments) {
  4936. newDetails.startCC = newDetails.fragments[0].cc;
  4937. }
  4938. // Merge parts
  4939. mapPartIntersection(oldDetails.partList, newDetails.partList, function (oldPart, newPart) {
  4940. newPart.elementaryStreams = oldPart.elementaryStreams;
  4941. newPart.stats = oldPart.stats;
  4942. });
  4943. // if at least one fragment contains PTS info, recompute PTS information for all fragments
  4944. if (PTSFrag) {
  4945. updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
  4946. } else {
  4947. // ensure that delta is within oldFragments range
  4948. // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])
  4949. // in that case we also need to adjust start offset of all fragments
  4950. adjustSliding(oldDetails, newDetails);
  4951. }
  4952. if (newFragments.length) {
  4953. newDetails.totalduration = newDetails.edge - newFragments[0].start;
  4954. }
  4955. newDetails.driftStartTime = oldDetails.driftStartTime;
  4956. newDetails.driftStart = oldDetails.driftStart;
  4957. var advancedDateTime = newDetails.advancedDateTime;
  4958. if (newDetails.advanced && advancedDateTime) {
  4959. var edge = newDetails.edge;
  4960. if (!newDetails.driftStart) {
  4961. newDetails.driftStartTime = advancedDateTime;
  4962. newDetails.driftStart = edge;
  4963. }
  4964. newDetails.driftEndTime = advancedDateTime;
  4965. newDetails.driftEnd = edge;
  4966. } else {
  4967. newDetails.driftEndTime = oldDetails.driftEndTime;
  4968. newDetails.driftEnd = oldDetails.driftEnd;
  4969. newDetails.advancedDateTime = oldDetails.advancedDateTime;
  4970. }
  4971. }
  4972. function mergeDateRanges(oldDateRanges, deltaDateRanges, recentlyRemovedDateranges) {
  4973. var dateRanges = _extends({}, oldDateRanges);
  4974. if (recentlyRemovedDateranges) {
  4975. recentlyRemovedDateranges.forEach(function (id) {
  4976. delete dateRanges[id];
  4977. });
  4978. }
  4979. Object.keys(deltaDateRanges).forEach(function (id) {
  4980. var dateRange = new DateRange(deltaDateRanges[id].attr, dateRanges[id]);
  4981. if (dateRange.isValid) {
  4982. dateRanges[id] = dateRange;
  4983. } else {
  4984. logger.warn("Ignoring invalid Playlist Delta Update DATERANGE tag: \"" + JSON.stringify(deltaDateRanges[id].attr) + "\"");
  4985. }
  4986. });
  4987. return dateRanges;
  4988. }
  4989. function mapPartIntersection(oldParts, newParts, intersectionFn) {
  4990. if (oldParts && newParts) {
  4991. var delta = 0;
  4992. for (var i = 0, len = oldParts.length; i <= len; i++) {
  4993. var _oldPart = oldParts[i];
  4994. var _newPart = newParts[i + delta];
  4995. if (_oldPart && _newPart && _oldPart.index === _newPart.index && _oldPart.fragment.sn === _newPart.fragment.sn) {
  4996. intersectionFn(_oldPart, _newPart);
  4997. } else {
  4998. delta--;
  4999. }
  5000. }
  5001. }
  5002. }
  5003. function mapFragmentIntersection(oldDetails, newDetails, intersectionFn) {
  5004. var skippedSegments = newDetails.skippedSegments;
  5005. var start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;
  5006. var end = (oldDetails.fragmentHint ? 1 : 0) + (skippedSegments ? newDetails.endSN : Math.min(oldDetails.endSN, newDetails.endSN)) - newDetails.startSN;
  5007. var delta = newDetails.startSN - oldDetails.startSN;
  5008. var newFrags = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
  5009. var oldFrags = oldDetails.fragmentHint ? oldDetails.fragments.concat(oldDetails.fragmentHint) : oldDetails.fragments;
  5010. for (var i = start; i <= end; i++) {
  5011. var _oldFrag = oldFrags[delta + i];
  5012. var _newFrag = newFrags[i];
  5013. if (skippedSegments && !_newFrag && i < skippedSegments) {
  5014. // Fill in skipped segments in delta playlist
  5015. _newFrag = newDetails.fragments[i] = _oldFrag;
  5016. }
  5017. if (_oldFrag && _newFrag) {
  5018. intersectionFn(_oldFrag, _newFrag);
  5019. }
  5020. }
  5021. }
  5022. function adjustSliding(oldDetails, newDetails) {
  5023. var delta = newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN;
  5024. var oldFragments = oldDetails.fragments;
  5025. if (delta < 0 || delta >= oldFragments.length) {
  5026. return;
  5027. }
  5028. addSliding(newDetails, oldFragments[delta].start);
  5029. }
  5030. function addSliding(details, start) {
  5031. if (start) {
  5032. var fragments = details.fragments;
  5033. for (var i = details.skippedSegments; i < fragments.length; i++) {
  5034. fragments[i].start += start;
  5035. }
  5036. if (details.fragmentHint) {
  5037. details.fragmentHint.start += start;
  5038. }
  5039. }
  5040. }
  5041. function computeReloadInterval(newDetails, distanceToLiveEdgeMs) {
  5042. if (distanceToLiveEdgeMs === void 0) {
  5043. distanceToLiveEdgeMs = Infinity;
  5044. }
  5045. var reloadInterval = 1000 * newDetails.targetduration;
  5046. if (newDetails.updated) {
  5047. // Use last segment duration when shorter than target duration and near live edge
  5048. var fragments = newDetails.fragments;
  5049. var liveEdgeMaxTargetDurations = 4;
  5050. if (fragments.length && reloadInterval * liveEdgeMaxTargetDurations > distanceToLiveEdgeMs) {
  5051. var lastSegmentDuration = fragments[fragments.length - 1].duration * 1000;
  5052. if (lastSegmentDuration < reloadInterval) {
  5053. reloadInterval = lastSegmentDuration;
  5054. }
  5055. }
  5056. } else {
  5057. // estimate = 'miss half average';
  5058. // follow HLS Spec, If the client reloads a Playlist file and finds that it has not
  5059. // changed then it MUST wait for a period of one-half the target
  5060. // duration before retrying.
  5061. reloadInterval /= 2;
  5062. }
  5063. return Math.round(reloadInterval);
  5064. }
  5065. function getFragmentWithSN(level, sn, fragCurrent) {
  5066. if (!(level != null && level.details)) {
  5067. return null;
  5068. }
  5069. var levelDetails = level.details;
  5070. var fragment = levelDetails.fragments[sn - levelDetails.startSN];
  5071. if (fragment) {
  5072. return fragment;
  5073. }
  5074. fragment = levelDetails.fragmentHint;
  5075. if (fragment && fragment.sn === sn) {
  5076. return fragment;
  5077. }
  5078. if (sn < levelDetails.startSN && fragCurrent && fragCurrent.sn === sn) {
  5079. return fragCurrent;
  5080. }
  5081. return null;
  5082. }
  5083. function getPartWith(level, sn, partIndex) {
  5084. var _level$details;
  5085. if (!(level != null && level.details)) {
  5086. return null;
  5087. }
  5088. return findPart((_level$details = level.details) == null ? void 0 : _level$details.partList, sn, partIndex);
  5089. }
  5090. function findPart(partList, sn, partIndex) {
  5091. if (partList) {
  5092. for (var i = partList.length; i--;) {
  5093. var part = partList[i];
  5094. if (part.index === partIndex && part.fragment.sn === sn) {
  5095. return part;
  5096. }
  5097. }
  5098. }
  5099. return null;
  5100. }
  5101. function reassignFragmentLevelIndexes(levels) {
  5102. levels.forEach(function (level, index) {
  5103. var details = level.details;
  5104. if (details != null && details.fragments) {
  5105. details.fragments.forEach(function (fragment) {
  5106. fragment.level = index;
  5107. });
  5108. }
  5109. });
  5110. }
  5111. function isTimeoutError(error) {
  5112. switch (error.details) {
  5113. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  5114. case ErrorDetails.KEY_LOAD_TIMEOUT:
  5115. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  5116. case ErrorDetails.MANIFEST_LOAD_TIMEOUT:
  5117. return true;
  5118. }
  5119. return false;
  5120. }
  5121. function getRetryConfig(loadPolicy, error) {
  5122. var isTimeout = isTimeoutError(error);
  5123. return loadPolicy.default[(isTimeout ? 'timeout' : 'error') + "Retry"];
  5124. }
  5125. function getRetryDelay(retryConfig, retryCount) {
  5126. // exponential backoff capped to max retry delay
  5127. var backoffFactor = retryConfig.backoff === 'linear' ? 1 : Math.pow(2, retryCount);
  5128. return Math.min(backoffFactor * retryConfig.retryDelayMs, retryConfig.maxRetryDelayMs);
  5129. }
  5130. function getLoaderConfigWithoutReties(loderConfig) {
  5131. return _objectSpread2(_objectSpread2({}, loderConfig), {
  5132. errorRetry: null,
  5133. timeoutRetry: null
  5134. });
  5135. }
  5136. function shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse) {
  5137. if (!retryConfig) {
  5138. return false;
  5139. }
  5140. var httpStatus = loaderResponse == null ? void 0 : loaderResponse.code;
  5141. var retry = retryCount < retryConfig.maxNumRetry && (retryForHttpStatus(httpStatus) || !!isTimeout);
  5142. return retryConfig.shouldRetry ? retryConfig.shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse, retry) : retry;
  5143. }
  5144. function retryForHttpStatus(httpStatus) {
  5145. // Do not retry on status 4xx, status 0 (CORS error), or undefined (decrypt/gap/parse error)
  5146. return httpStatus === 0 && navigator.onLine === false || !!httpStatus && (httpStatus < 400 || httpStatus > 499);
  5147. }
  5148. var BinarySearch = {
  5149. /**
  5150. * Searches for an item in an array which matches a certain condition.
  5151. * This requires the condition to only match one item in the array,
  5152. * and for the array to be ordered.
  5153. *
  5154. * @param list The array to search.
  5155. * @param comparisonFn
  5156. * Called and provided a candidate item as the first argument.
  5157. * Should return:
  5158. * > -1 if the item should be located at a lower index than the provided item.
  5159. * > 1 if the item should be located at a higher index than the provided item.
  5160. * > 0 if the item is the item you're looking for.
  5161. *
  5162. * @returns the object if found, otherwise returns null
  5163. */
  5164. search: function search(list, comparisonFn) {
  5165. var minIndex = 0;
  5166. var maxIndex = list.length - 1;
  5167. var currentIndex = null;
  5168. var currentElement = null;
  5169. while (minIndex <= maxIndex) {
  5170. currentIndex = (minIndex + maxIndex) / 2 | 0;
  5171. currentElement = list[currentIndex];
  5172. var comparisonResult = comparisonFn(currentElement);
  5173. if (comparisonResult > 0) {
  5174. minIndex = currentIndex + 1;
  5175. } else if (comparisonResult < 0) {
  5176. maxIndex = currentIndex - 1;
  5177. } else {
  5178. return currentElement;
  5179. }
  5180. }
  5181. return null;
  5182. }
  5183. };
  5184. /**
  5185. * Returns first fragment whose endPdt value exceeds the given PDT, or null.
  5186. * @param fragments - The array of candidate fragments
  5187. * @param PDTValue - The PDT value which must be exceeded
  5188. * @param maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  5189. */
  5190. function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
  5191. if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !isFiniteNumber(PDTValue)) {
  5192. return null;
  5193. }
  5194. // if less than start
  5195. var startPDT = fragments[0].programDateTime;
  5196. if (PDTValue < (startPDT || 0)) {
  5197. return null;
  5198. }
  5199. var endPDT = fragments[fragments.length - 1].endProgramDateTime;
  5200. if (PDTValue >= (endPDT || 0)) {
  5201. return null;
  5202. }
  5203. maxFragLookUpTolerance = maxFragLookUpTolerance || 0;
  5204. for (var seg = 0; seg < fragments.length; ++seg) {
  5205. var frag = fragments[seg];
  5206. if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
  5207. return frag;
  5208. }
  5209. }
  5210. return null;
  5211. }
  5212. /**
  5213. * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.
  5214. * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus
  5215. * breaking any traps which would cause the same fragment to be continuously selected within a small range.
  5216. * @param fragPrevious - The last frag successfully appended
  5217. * @param fragments - The array of candidate fragments
  5218. * @param bufferEnd - The end of the contiguous buffered range the playhead is currently within
  5219. * @param maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  5220. * @returns a matching fragment or null
  5221. */
  5222. function findFragmentByPTS(fragPrevious, fragments, bufferEnd, maxFragLookUpTolerance, nextFragLookupTolerance) {
  5223. if (bufferEnd === void 0) {
  5224. bufferEnd = 0;
  5225. }
  5226. if (maxFragLookUpTolerance === void 0) {
  5227. maxFragLookUpTolerance = 0;
  5228. }
  5229. if (nextFragLookupTolerance === void 0) {
  5230. nextFragLookupTolerance = 0.005;
  5231. }
  5232. var fragNext = null;
  5233. if (fragPrevious) {
  5234. fragNext = fragments[fragPrevious.sn - fragments[0].sn + 1] || null;
  5235. // check for buffer-end rounding error
  5236. var bufferEdgeError = fragPrevious.endDTS - bufferEnd;
  5237. if (bufferEdgeError > 0 && bufferEdgeError < 0.0000015) {
  5238. bufferEnd += 0.0000015;
  5239. }
  5240. } else if (bufferEnd === 0 && fragments[0].start === 0) {
  5241. fragNext = fragments[0];
  5242. }
  5243. // Prefer the next fragment if it's within tolerance
  5244. if (fragNext && ((!fragPrevious || fragPrevious.level === fragNext.level) && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0 || fragmentWithinFastStartSwitch(fragNext, fragPrevious, Math.min(nextFragLookupTolerance, maxFragLookUpTolerance)))) {
  5245. return fragNext;
  5246. }
  5247. // We might be seeking past the tolerance so find the best match
  5248. var foundFragment = BinarySearch.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
  5249. if (foundFragment && (foundFragment !== fragPrevious || !fragNext)) {
  5250. return foundFragment;
  5251. }
  5252. // If no match was found return the next fragment after fragPrevious, or null
  5253. return fragNext;
  5254. }
  5255. function fragmentWithinFastStartSwitch(fragNext, fragPrevious, nextFragLookupTolerance) {
  5256. if (fragPrevious && fragPrevious.start === 0 && fragPrevious.level < fragNext.level && (fragPrevious.endPTS || 0) > 0) {
  5257. var firstDuration = fragPrevious.tagList.reduce(function (duration, tag) {
  5258. if (tag[0] === 'INF') {
  5259. duration += parseFloat(tag[1]);
  5260. }
  5261. return duration;
  5262. }, nextFragLookupTolerance);
  5263. return fragNext.start <= firstDuration;
  5264. }
  5265. return false;
  5266. }
  5267. /**
  5268. * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.
  5269. * @param candidate - The fragment to test
  5270. * @param bufferEnd - The end of the current buffered range the playhead is currently within
  5271. * @param maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous
  5272. * @returns 0 if it matches, 1 if too low, -1 if too high
  5273. */
  5274. function fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, candidate) {
  5275. if (bufferEnd === void 0) {
  5276. bufferEnd = 0;
  5277. }
  5278. if (maxFragLookUpTolerance === void 0) {
  5279. maxFragLookUpTolerance = 0;
  5280. }
  5281. // eagerly accept an accurate match (no tolerance)
  5282. if (candidate.start <= bufferEnd && candidate.start + candidate.duration > bufferEnd) {
  5283. return 0;
  5284. }
  5285. // offset should be within fragment boundary - config.maxFragLookUpTolerance
  5286. // this is to cope with situations like
  5287. // bufferEnd = 9.991
  5288. // frag[Ø] : [0,10]
  5289. // frag[1] : [10,20]
  5290. // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
  5291. // frag start frag start+duration
  5292. // |-----------------------------|
  5293. // <---> <--->
  5294. // ...--------><-----------------------------><---------....
  5295. // previous frag matching fragment next frag
  5296. // return -1 return 0 return 1
  5297. // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
  5298. // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
  5299. var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
  5300. if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
  5301. return 1;
  5302. } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
  5303. // if maxFragLookUpTolerance will have negative value then don't return -1 for first element
  5304. return -1;
  5305. }
  5306. return 0;
  5307. }
  5308. /**
  5309. * The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.
  5310. * This function tests the candidate's program date time values, as represented in Unix time
  5311. * @param candidate - The fragment to test
  5312. * @param pdtBufferEnd - The Unix time representing the end of the current buffered range
  5313. * @param maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous
  5314. * @returns true if contiguous, false otherwise
  5315. */
  5316. function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
  5317. var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000;
  5318. // endProgramDateTime can be null, default to zero
  5319. var endProgramDateTime = candidate.endProgramDateTime || 0;
  5320. return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
  5321. }
  5322. function findFragWithCC(fragments, cc) {
  5323. return BinarySearch.search(fragments, function (candidate) {
  5324. if (candidate.cc < cc) {
  5325. return 1;
  5326. } else if (candidate.cc > cc) {
  5327. return -1;
  5328. } else {
  5329. return 0;
  5330. }
  5331. });
  5332. }
  5333. var NetworkErrorAction = {
  5334. DoNothing: 0,
  5335. SendEndCallback: 1,
  5336. SendAlternateToPenaltyBox: 2,
  5337. RemoveAlternatePermanently: 3,
  5338. InsertDiscontinuity: 4,
  5339. RetryRequest: 5
  5340. };
  5341. var ErrorActionFlags = {
  5342. None: 0,
  5343. MoveAllAlternatesMatchingHost: 1,
  5344. MoveAllAlternatesMatchingHDCP: 2,
  5345. SwitchToSDR: 4
  5346. }; // Reserved for future use
  5347. var ErrorController = /*#__PURE__*/function () {
  5348. function ErrorController(hls) {
  5349. this.hls = void 0;
  5350. this.playlistError = 0;
  5351. this.penalizedRenditions = {};
  5352. this.log = void 0;
  5353. this.warn = void 0;
  5354. this.error = void 0;
  5355. this.hls = hls;
  5356. this.log = logger.log.bind(logger, "[info]:");
  5357. this.warn = logger.warn.bind(logger, "[warning]:");
  5358. this.error = logger.error.bind(logger, "[error]:");
  5359. this.registerListeners();
  5360. }
  5361. var _proto = ErrorController.prototype;
  5362. _proto.registerListeners = function registerListeners() {
  5363. var hls = this.hls;
  5364. hls.on(Events.ERROR, this.onError, this);
  5365. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  5366. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  5367. };
  5368. _proto.unregisterListeners = function unregisterListeners() {
  5369. var hls = this.hls;
  5370. if (!hls) {
  5371. return;
  5372. }
  5373. hls.off(Events.ERROR, this.onError, this);
  5374. hls.off(Events.ERROR, this.onErrorOut, this);
  5375. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  5376. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  5377. };
  5378. _proto.destroy = function destroy() {
  5379. this.unregisterListeners();
  5380. // @ts-ignore
  5381. this.hls = null;
  5382. this.penalizedRenditions = {};
  5383. };
  5384. _proto.startLoad = function startLoad(startPosition) {};
  5385. _proto.stopLoad = function stopLoad() {
  5386. this.playlistError = 0;
  5387. };
  5388. _proto.getVariantLevelIndex = function getVariantLevelIndex(frag) {
  5389. return (frag == null ? void 0 : frag.type) === PlaylistLevelType.MAIN ? frag.level : this.hls.loadLevel;
  5390. };
  5391. _proto.onManifestLoading = function onManifestLoading() {
  5392. this.playlistError = 0;
  5393. this.penalizedRenditions = {};
  5394. };
  5395. _proto.onLevelUpdated = function onLevelUpdated() {
  5396. this.playlistError = 0;
  5397. };
  5398. _proto.onError = function onError(event, data) {
  5399. var _data$frag, _data$level;
  5400. if (data.fatal) {
  5401. return;
  5402. }
  5403. var hls = this.hls;
  5404. var context = data.context;
  5405. switch (data.details) {
  5406. case ErrorDetails.FRAG_LOAD_ERROR:
  5407. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  5408. case ErrorDetails.KEY_LOAD_ERROR:
  5409. case ErrorDetails.KEY_LOAD_TIMEOUT:
  5410. data.errorAction = this.getFragRetryOrSwitchAction(data);
  5411. return;
  5412. case ErrorDetails.FRAG_PARSING_ERROR:
  5413. // ignore empty segment errors marked as gap
  5414. if ((_data$frag = data.frag) != null && _data$frag.gap) {
  5415. data.errorAction = {
  5416. action: NetworkErrorAction.DoNothing,
  5417. flags: ErrorActionFlags.None
  5418. };
  5419. return;
  5420. }
  5421. // falls through
  5422. case ErrorDetails.FRAG_GAP:
  5423. case ErrorDetails.FRAG_DECRYPT_ERROR:
  5424. {
  5425. // Switch level if possible, otherwise allow retry count to reach max error retries
  5426. data.errorAction = this.getFragRetryOrSwitchAction(data);
  5427. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  5428. return;
  5429. }
  5430. case ErrorDetails.LEVEL_EMPTY_ERROR:
  5431. case ErrorDetails.LEVEL_PARSING_ERROR:
  5432. {
  5433. var _data$context, _data$context$levelDe;
  5434. // Only retry when empty and live
  5435. var levelIndex = data.parent === PlaylistLevelType.MAIN ? data.level : hls.loadLevel;
  5436. if (data.details === ErrorDetails.LEVEL_EMPTY_ERROR && !!((_data$context = data.context) != null && (_data$context$levelDe = _data$context.levelDetails) != null && _data$context$levelDe.live)) {
  5437. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, levelIndex);
  5438. } else {
  5439. // Escalate to fatal if not retrying or switching
  5440. data.levelRetry = false;
  5441. data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  5442. }
  5443. }
  5444. return;
  5445. case ErrorDetails.LEVEL_LOAD_ERROR:
  5446. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  5447. if (typeof (context == null ? void 0 : context.level) === 'number') {
  5448. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, context.level);
  5449. }
  5450. return;
  5451. case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
  5452. case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
  5453. case ErrorDetails.SUBTITLE_LOAD_ERROR:
  5454. case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:
  5455. if (context) {
  5456. var level = hls.levels[hls.loadLevel];
  5457. if (level && (context.type === PlaylistContextType.AUDIO_TRACK && level.hasAudioGroup(context.groupId) || context.type === PlaylistContextType.SUBTITLE_TRACK && level.hasSubtitleGroup(context.groupId))) {
  5458. // Perform Pathway switch or Redundant failover if possible for fastest recovery
  5459. // otherwise allow playlist retry count to reach max error retries
  5460. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, hls.loadLevel);
  5461. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  5462. data.errorAction.flags = ErrorActionFlags.MoveAllAlternatesMatchingHost;
  5463. return;
  5464. }
  5465. }
  5466. return;
  5467. case ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:
  5468. {
  5469. var _level = hls.levels[hls.loadLevel];
  5470. var restrictedHdcpLevel = _level == null ? void 0 : _level.attrs['HDCP-LEVEL'];
  5471. if (restrictedHdcpLevel) {
  5472. data.errorAction = {
  5473. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  5474. flags: ErrorActionFlags.MoveAllAlternatesMatchingHDCP,
  5475. hdcpLevel: restrictedHdcpLevel
  5476. };
  5477. } else {
  5478. this.keySystemError(data);
  5479. }
  5480. }
  5481. return;
  5482. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  5483. case ErrorDetails.REMUX_ALLOC_ERROR:
  5484. case ErrorDetails.BUFFER_APPEND_ERROR:
  5485. data.errorAction = this.getLevelSwitchAction(data, (_data$level = data.level) != null ? _data$level : hls.loadLevel);
  5486. return;
  5487. case ErrorDetails.INTERNAL_EXCEPTION:
  5488. case ErrorDetails.BUFFER_APPENDING_ERROR:
  5489. case ErrorDetails.BUFFER_FULL_ERROR:
  5490. case ErrorDetails.LEVEL_SWITCH_ERROR:
  5491. case ErrorDetails.BUFFER_STALLED_ERROR:
  5492. case ErrorDetails.BUFFER_SEEK_OVER_HOLE:
  5493. case ErrorDetails.BUFFER_NUDGE_ON_STALL:
  5494. data.errorAction = {
  5495. action: NetworkErrorAction.DoNothing,
  5496. flags: ErrorActionFlags.None
  5497. };
  5498. return;
  5499. }
  5500. if (data.type === ErrorTypes.KEY_SYSTEM_ERROR) {
  5501. this.keySystemError(data);
  5502. }
  5503. };
  5504. _proto.keySystemError = function keySystemError(data) {
  5505. var levelIndex = this.getVariantLevelIndex(data.frag);
  5506. // Do not retry level. Escalate to fatal if switching levels fails.
  5507. data.levelRetry = false;
  5508. data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  5509. };
  5510. _proto.getPlaylistRetryOrSwitchAction = function getPlaylistRetryOrSwitchAction(data, levelIndex) {
  5511. var hls = this.hls;
  5512. var retryConfig = getRetryConfig(hls.config.playlistLoadPolicy, data);
  5513. var retryCount = this.playlistError++;
  5514. var retry = shouldRetry(retryConfig, retryCount, isTimeoutError(data), data.response);
  5515. if (retry) {
  5516. return {
  5517. action: NetworkErrorAction.RetryRequest,
  5518. flags: ErrorActionFlags.None,
  5519. retryConfig: retryConfig,
  5520. retryCount: retryCount
  5521. };
  5522. }
  5523. var errorAction = this.getLevelSwitchAction(data, levelIndex);
  5524. if (retryConfig) {
  5525. errorAction.retryConfig = retryConfig;
  5526. errorAction.retryCount = retryCount;
  5527. }
  5528. return errorAction;
  5529. };
  5530. _proto.getFragRetryOrSwitchAction = function getFragRetryOrSwitchAction(data) {
  5531. var hls = this.hls;
  5532. // Share fragment error count accross media options (main, audio, subs)
  5533. // This allows for level based rendition switching when media option assets fail
  5534. var variantLevelIndex = this.getVariantLevelIndex(data.frag);
  5535. var level = hls.levels[variantLevelIndex];
  5536. var _hls$config = hls.config,
  5537. fragLoadPolicy = _hls$config.fragLoadPolicy,
  5538. keyLoadPolicy = _hls$config.keyLoadPolicy;
  5539. var retryConfig = getRetryConfig(data.details.startsWith('key') ? keyLoadPolicy : fragLoadPolicy, data);
  5540. var fragmentErrors = hls.levels.reduce(function (acc, level) {
  5541. return acc + level.fragmentError;
  5542. }, 0);
  5543. // Switch levels when out of retried or level index out of bounds
  5544. if (level) {
  5545. if (data.details !== ErrorDetails.FRAG_GAP) {
  5546. level.fragmentError++;
  5547. }
  5548. var retry = shouldRetry(retryConfig, fragmentErrors, isTimeoutError(data), data.response);
  5549. if (retry) {
  5550. return {
  5551. action: NetworkErrorAction.RetryRequest,
  5552. flags: ErrorActionFlags.None,
  5553. retryConfig: retryConfig,
  5554. retryCount: fragmentErrors
  5555. };
  5556. }
  5557. }
  5558. // Reach max retry count, or Missing level reference
  5559. // Switch to valid index
  5560. var errorAction = this.getLevelSwitchAction(data, variantLevelIndex);
  5561. // Add retry details to allow skipping of FRAG_PARSING_ERROR
  5562. if (retryConfig) {
  5563. errorAction.retryConfig = retryConfig;
  5564. errorAction.retryCount = fragmentErrors;
  5565. }
  5566. return errorAction;
  5567. };
  5568. _proto.getLevelSwitchAction = function getLevelSwitchAction(data, levelIndex) {
  5569. var hls = this.hls;
  5570. if (levelIndex === null || levelIndex === undefined) {
  5571. levelIndex = hls.loadLevel;
  5572. }
  5573. var level = this.hls.levels[levelIndex];
  5574. if (level) {
  5575. var _data$frag2, _data$context2;
  5576. var errorDetails = data.details;
  5577. level.loadError++;
  5578. if (errorDetails === ErrorDetails.BUFFER_APPEND_ERROR) {
  5579. level.fragmentError++;
  5580. }
  5581. // Search for next level to retry
  5582. var nextLevel = -1;
  5583. var levels = hls.levels,
  5584. loadLevel = hls.loadLevel,
  5585. minAutoLevel = hls.minAutoLevel,
  5586. maxAutoLevel = hls.maxAutoLevel;
  5587. if (!hls.autoLevelEnabled) {
  5588. hls.loadLevel = -1;
  5589. }
  5590. var fragErrorType = (_data$frag2 = data.frag) == null ? void 0 : _data$frag2.type;
  5591. // Find alternate audio codec if available on audio codec error
  5592. var isAudioCodecError = fragErrorType === PlaylistLevelType.AUDIO && errorDetails === ErrorDetails.FRAG_PARSING_ERROR || data.sourceBufferName === 'audio' && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  5593. var findAudioCodecAlternate = isAudioCodecError && levels.some(function (_ref) {
  5594. var audioCodec = _ref.audioCodec;
  5595. return level.audioCodec !== audioCodec;
  5596. });
  5597. // Find alternate video codec if available on video codec error
  5598. var isVideoCodecError = data.sourceBufferName === 'video' && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  5599. var findVideoCodecAlternate = isVideoCodecError && levels.some(function (_ref2) {
  5600. var codecSet = _ref2.codecSet,
  5601. audioCodec = _ref2.audioCodec;
  5602. return level.codecSet !== codecSet && level.audioCodec === audioCodec;
  5603. });
  5604. var _ref3 = (_data$context2 = data.context) != null ? _data$context2 : {},
  5605. playlistErrorType = _ref3.type,
  5606. playlistErrorGroupId = _ref3.groupId;
  5607. var _loop = function _loop() {
  5608. var candidate = (i + loadLevel) % levels.length;
  5609. if (candidate !== loadLevel && candidate >= minAutoLevel && candidate <= maxAutoLevel && levels[candidate].loadError === 0) {
  5610. var _level$audioGroups, _level$subtitleGroups;
  5611. var levelCandidate = levels[candidate];
  5612. // Skip level switch if GAP tag is found in next level at same position
  5613. if (errorDetails === ErrorDetails.FRAG_GAP && fragErrorType === PlaylistLevelType.MAIN && data.frag) {
  5614. var levelDetails = levels[candidate].details;
  5615. if (levelDetails) {
  5616. var fragCandidate = findFragmentByPTS(data.frag, levelDetails.fragments, data.frag.start);
  5617. if (fragCandidate != null && fragCandidate.gap) {
  5618. return 0; // continue
  5619. }
  5620. }
  5621. } else if (playlistErrorType === PlaylistContextType.AUDIO_TRACK && levelCandidate.hasAudioGroup(playlistErrorGroupId) || playlistErrorType === PlaylistContextType.SUBTITLE_TRACK && levelCandidate.hasSubtitleGroup(playlistErrorGroupId)) {
  5622. // For audio/subs playlist errors find another group ID or fallthrough to redundant fail-over
  5623. return 0; // continue
  5624. } else if (fragErrorType === PlaylistLevelType.AUDIO && (_level$audioGroups = level.audioGroups) != null && _level$audioGroups.some(function (groupId) {
  5625. return levelCandidate.hasAudioGroup(groupId);
  5626. }) || fragErrorType === PlaylistLevelType.SUBTITLE && (_level$subtitleGroups = level.subtitleGroups) != null && _level$subtitleGroups.some(function (groupId) {
  5627. return levelCandidate.hasSubtitleGroup(groupId);
  5628. }) || findAudioCodecAlternate && level.audioCodec === levelCandidate.audioCodec || !findAudioCodecAlternate && level.audioCodec !== levelCandidate.audioCodec || findVideoCodecAlternate && level.codecSet === levelCandidate.codecSet) {
  5629. // For video/audio/subs frag errors find another group ID or fallthrough to redundant fail-over
  5630. return 0; // continue
  5631. }
  5632. nextLevel = candidate;
  5633. return 1; // break
  5634. }
  5635. },
  5636. _ret;
  5637. for (var i = levels.length; i--;) {
  5638. _ret = _loop();
  5639. if (_ret === 0) continue;
  5640. if (_ret === 1) break;
  5641. }
  5642. if (nextLevel > -1 && hls.loadLevel !== nextLevel) {
  5643. data.levelRetry = true;
  5644. this.playlistError = 0;
  5645. return {
  5646. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  5647. flags: ErrorActionFlags.None,
  5648. nextAutoLevel: nextLevel
  5649. };
  5650. }
  5651. }
  5652. // No levels to switch / Manual level selection / Level not found
  5653. // Resolve with Pathway switch, Redundant fail-over, or stay on lowest Level
  5654. return {
  5655. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  5656. flags: ErrorActionFlags.MoveAllAlternatesMatchingHost
  5657. };
  5658. };
  5659. _proto.onErrorOut = function onErrorOut(event, data) {
  5660. var _data$errorAction;
  5661. switch ((_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.action) {
  5662. case NetworkErrorAction.DoNothing:
  5663. break;
  5664. case NetworkErrorAction.SendAlternateToPenaltyBox:
  5665. this.sendAlternateToPenaltyBox(data);
  5666. if (!data.errorAction.resolved && data.details !== ErrorDetails.FRAG_GAP) {
  5667. data.fatal = true;
  5668. } else if (/MediaSource readyState: ended/.test(data.error.message)) {
  5669. this.warn("MediaSource ended after \"" + data.sourceBufferName + "\" sourceBuffer append error. Attempting to recover from media error.");
  5670. this.hls.recoverMediaError();
  5671. }
  5672. break;
  5673. }
  5674. if (data.fatal) {
  5675. this.hls.stopLoad();
  5676. return;
  5677. }
  5678. };
  5679. _proto.sendAlternateToPenaltyBox = function sendAlternateToPenaltyBox(data) {
  5680. var hls = this.hls;
  5681. var errorAction = data.errorAction;
  5682. if (!errorAction) {
  5683. return;
  5684. }
  5685. var flags = errorAction.flags,
  5686. hdcpLevel = errorAction.hdcpLevel,
  5687. nextAutoLevel = errorAction.nextAutoLevel;
  5688. switch (flags) {
  5689. case ErrorActionFlags.None:
  5690. this.switchLevel(data, nextAutoLevel);
  5691. break;
  5692. case ErrorActionFlags.MoveAllAlternatesMatchingHDCP:
  5693. if (hdcpLevel) {
  5694. hls.maxHdcpLevel = HdcpLevels[HdcpLevels.indexOf(hdcpLevel) - 1];
  5695. errorAction.resolved = true;
  5696. }
  5697. this.warn("Restricting playback to HDCP-LEVEL of \"" + hls.maxHdcpLevel + "\" or lower");
  5698. break;
  5699. }
  5700. // If not resolved by previous actions try to switch to next level
  5701. if (!errorAction.resolved) {
  5702. this.switchLevel(data, nextAutoLevel);
  5703. }
  5704. };
  5705. _proto.switchLevel = function switchLevel(data, levelIndex) {
  5706. if (levelIndex !== undefined && data.errorAction) {
  5707. this.warn("switching to level " + levelIndex + " after " + data.details);
  5708. this.hls.nextAutoLevel = levelIndex;
  5709. data.errorAction.resolved = true;
  5710. // Stream controller is responsible for this but won't switch on false start
  5711. this.hls.nextLoadLevel = this.hls.nextAutoLevel;
  5712. }
  5713. };
  5714. return ErrorController;
  5715. }();
  5716. var BasePlaylistController = /*#__PURE__*/function () {
  5717. function BasePlaylistController(hls, logPrefix) {
  5718. this.hls = void 0;
  5719. this.timer = -1;
  5720. this.requestScheduled = -1;
  5721. this.canLoad = false;
  5722. this.log = void 0;
  5723. this.warn = void 0;
  5724. this.log = logger.log.bind(logger, logPrefix + ":");
  5725. this.warn = logger.warn.bind(logger, logPrefix + ":");
  5726. this.hls = hls;
  5727. }
  5728. var _proto = BasePlaylistController.prototype;
  5729. _proto.destroy = function destroy() {
  5730. this.clearTimer();
  5731. // @ts-ignore
  5732. this.hls = this.log = this.warn = null;
  5733. };
  5734. _proto.clearTimer = function clearTimer() {
  5735. if (this.timer !== -1) {
  5736. self.clearTimeout(this.timer);
  5737. this.timer = -1;
  5738. }
  5739. };
  5740. _proto.startLoad = function startLoad() {
  5741. this.canLoad = true;
  5742. this.requestScheduled = -1;
  5743. this.loadPlaylist();
  5744. };
  5745. _proto.stopLoad = function stopLoad() {
  5746. this.canLoad = false;
  5747. this.clearTimer();
  5748. };
  5749. _proto.switchParams = function switchParams(playlistUri, previous, current) {
  5750. var renditionReports = previous == null ? void 0 : previous.renditionReports;
  5751. if (renditionReports) {
  5752. var foundIndex = -1;
  5753. for (var i = 0; i < renditionReports.length; i++) {
  5754. var attr = renditionReports[i];
  5755. var uri = void 0;
  5756. try {
  5757. uri = new self.URL(attr.URI, previous.url).href;
  5758. } catch (error) {
  5759. logger.warn("Could not construct new URL for Rendition Report: " + error);
  5760. uri = attr.URI || '';
  5761. }
  5762. // Use exact match. Otherwise, the last partial match, if any, will be used
  5763. // (Playlist URI includes a query string that the Rendition Report does not)
  5764. if (uri === playlistUri) {
  5765. foundIndex = i;
  5766. break;
  5767. } else if (uri === playlistUri.substring(0, uri.length)) {
  5768. foundIndex = i;
  5769. }
  5770. }
  5771. if (foundIndex !== -1) {
  5772. var _attr = renditionReports[foundIndex];
  5773. var msn = parseInt(_attr['LAST-MSN']) || (previous == null ? void 0 : previous.lastPartSn);
  5774. var part = parseInt(_attr['LAST-PART']) || (previous == null ? void 0 : previous.lastPartIndex);
  5775. if (this.hls.config.lowLatencyMode) {
  5776. var currentGoal = Math.min(previous.age - previous.partTarget, previous.targetduration);
  5777. if (part >= 0 && currentGoal > previous.partTarget) {
  5778. part += 1;
  5779. }
  5780. }
  5781. var skip = current && getSkipValue(current);
  5782. return new HlsUrlParameters(msn, part >= 0 ? part : undefined, skip);
  5783. }
  5784. }
  5785. };
  5786. _proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {
  5787. if (this.requestScheduled === -1) {
  5788. this.requestScheduled = self.performance.now();
  5789. }
  5790. // Loading is handled by the subclasses
  5791. };
  5792. _proto.shouldLoadPlaylist = function shouldLoadPlaylist(playlist) {
  5793. return this.canLoad && !!playlist && !!playlist.url && (!playlist.details || playlist.details.live);
  5794. };
  5795. _proto.shouldReloadPlaylist = function shouldReloadPlaylist(playlist) {
  5796. return this.timer === -1 && this.requestScheduled === -1 && this.shouldLoadPlaylist(playlist);
  5797. };
  5798. _proto.playlistLoaded = function playlistLoaded(index, data, previousDetails) {
  5799. var _this = this;
  5800. var details = data.details,
  5801. stats = data.stats;
  5802. // Set last updated date-time
  5803. var now = self.performance.now();
  5804. var elapsed = stats.loading.first ? Math.max(0, now - stats.loading.first) : 0;
  5805. details.advancedDateTime = Date.now() - elapsed;
  5806. // if current playlist is a live playlist, arm a timer to reload it
  5807. if (details.live || previousDetails != null && previousDetails.live) {
  5808. details.reloaded(previousDetails);
  5809. if (previousDetails) {
  5810. this.log("live playlist " + index + " " + (details.advanced ? 'REFRESHED ' + details.lastPartSn + '-' + details.lastPartIndex : details.updated ? 'UPDATED' : 'MISSED'));
  5811. }
  5812. // Merge live playlists to adjust fragment starts and fill in delta playlist skipped segments
  5813. if (previousDetails && details.fragments.length > 0) {
  5814. mergeDetails(previousDetails, details);
  5815. }
  5816. if (!this.canLoad || !details.live) {
  5817. return;
  5818. }
  5819. var deliveryDirectives;
  5820. var msn = undefined;
  5821. var part = undefined;
  5822. if (details.canBlockReload && details.endSN && details.advanced) {
  5823. // Load level with LL-HLS delivery directives
  5824. var lowLatencyMode = this.hls.config.lowLatencyMode;
  5825. var lastPartSn = details.lastPartSn;
  5826. var endSn = details.endSN;
  5827. var lastPartIndex = details.lastPartIndex;
  5828. var hasParts = lastPartIndex !== -1;
  5829. var lastPart = lastPartSn === endSn;
  5830. // When low latency mode is disabled, we'll skip part requests once the last part index is found
  5831. var nextSnStartIndex = lowLatencyMode ? 0 : lastPartIndex;
  5832. if (hasParts) {
  5833. msn = lastPart ? endSn + 1 : lastPartSn;
  5834. part = lastPart ? nextSnStartIndex : lastPartIndex + 1;
  5835. } else {
  5836. msn = endSn + 1;
  5837. }
  5838. // Low-Latency CDN Tune-in: "age" header and time since load indicates we're behind by more than one part
  5839. // Update directives to obtain the Playlist that has the estimated additional duration of media
  5840. var lastAdvanced = details.age;
  5841. var cdnAge = lastAdvanced + details.ageHeader;
  5842. var currentGoal = Math.min(cdnAge - details.partTarget, details.targetduration * 1.5);
  5843. if (currentGoal > 0) {
  5844. if (previousDetails && currentGoal > previousDetails.tuneInGoal) {
  5845. // If we attempted to get the next or latest playlist update, but currentGoal increased,
  5846. // then we either can't catchup, or the "age" header cannot be trusted.
  5847. this.warn("CDN Tune-in goal increased from: " + previousDetails.tuneInGoal + " to: " + currentGoal + " with playlist age: " + details.age);
  5848. currentGoal = 0;
  5849. } else {
  5850. var segments = Math.floor(currentGoal / details.targetduration);
  5851. msn += segments;
  5852. if (part !== undefined) {
  5853. var parts = Math.round(currentGoal % details.targetduration / details.partTarget);
  5854. part += parts;
  5855. }
  5856. this.log("CDN Tune-in age: " + details.ageHeader + "s last advanced " + lastAdvanced.toFixed(2) + "s goal: " + currentGoal + " skip sn " + segments + " to part " + part);
  5857. }
  5858. details.tuneInGoal = currentGoal;
  5859. }
  5860. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  5861. if (lowLatencyMode || !lastPart) {
  5862. this.loadPlaylist(deliveryDirectives);
  5863. return;
  5864. }
  5865. } else if (details.canBlockReload || details.canSkipUntil) {
  5866. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  5867. }
  5868. var bufferInfo = this.hls.mainForwardBufferInfo;
  5869. var position = bufferInfo ? bufferInfo.end - bufferInfo.len : 0;
  5870. var distanceToLiveEdgeMs = (details.edge - position) * 1000;
  5871. var reloadInterval = computeReloadInterval(details, distanceToLiveEdgeMs);
  5872. if (details.updated && now > this.requestScheduled + reloadInterval) {
  5873. this.requestScheduled = stats.loading.start;
  5874. }
  5875. if (msn !== undefined && details.canBlockReload) {
  5876. this.requestScheduled = stats.loading.first + reloadInterval - (details.partTarget * 1000 || 1000);
  5877. } else if (this.requestScheduled === -1 || this.requestScheduled + reloadInterval < now) {
  5878. this.requestScheduled = now;
  5879. } else if (this.requestScheduled - now <= 0) {
  5880. this.requestScheduled += reloadInterval;
  5881. }
  5882. var estimatedTimeUntilUpdate = this.requestScheduled - now;
  5883. estimatedTimeUntilUpdate = Math.max(0, estimatedTimeUntilUpdate);
  5884. this.log("reload live playlist " + index + " in " + Math.round(estimatedTimeUntilUpdate) + " ms");
  5885. // this.log(
  5886. // `live reload ${details.updated ? 'REFRESHED' : 'MISSED'}
  5887. // reload in ${estimatedTimeUntilUpdate / 1000}
  5888. // round trip ${(stats.loading.end - stats.loading.start) / 1000}
  5889. // diff ${
  5890. // (reloadInterval -
  5891. // (estimatedTimeUntilUpdate +
  5892. // stats.loading.end -
  5893. // stats.loading.start)) /
  5894. // 1000
  5895. // }
  5896. // reload interval ${reloadInterval / 1000}
  5897. // target duration ${details.targetduration}
  5898. // distance to edge ${distanceToLiveEdgeMs / 1000}`
  5899. // );
  5900. this.timer = self.setTimeout(function () {
  5901. return _this.loadPlaylist(deliveryDirectives);
  5902. }, estimatedTimeUntilUpdate);
  5903. } else {
  5904. this.clearTimer();
  5905. }
  5906. };
  5907. _proto.getDeliveryDirectives = function getDeliveryDirectives(details, previousDeliveryDirectives, msn, part) {
  5908. var skip = getSkipValue(details);
  5909. if (previousDeliveryDirectives != null && previousDeliveryDirectives.skip && details.deltaUpdateFailed) {
  5910. msn = previousDeliveryDirectives.msn;
  5911. part = previousDeliveryDirectives.part;
  5912. skip = HlsSkip.No;
  5913. }
  5914. return new HlsUrlParameters(msn, part, skip);
  5915. };
  5916. _proto.checkRetry = function checkRetry(errorEvent) {
  5917. var _this2 = this;
  5918. var errorDetails = errorEvent.details;
  5919. var isTimeout = isTimeoutError(errorEvent);
  5920. var errorAction = errorEvent.errorAction;
  5921. var _ref = errorAction || {},
  5922. action = _ref.action,
  5923. _ref$retryCount = _ref.retryCount,
  5924. retryCount = _ref$retryCount === void 0 ? 0 : _ref$retryCount,
  5925. retryConfig = _ref.retryConfig;
  5926. var retry = !!errorAction && !!retryConfig && (action === NetworkErrorAction.RetryRequest || !errorAction.resolved && action === NetworkErrorAction.SendAlternateToPenaltyBox);
  5927. if (retry) {
  5928. var _errorEvent$context;
  5929. this.requestScheduled = -1;
  5930. if (retryCount >= retryConfig.maxNumRetry) {
  5931. return false;
  5932. }
  5933. if (isTimeout && (_errorEvent$context = errorEvent.context) != null && _errorEvent$context.deliveryDirectives) {
  5934. // The LL-HLS request already timed out so retry immediately
  5935. this.warn("Retrying playlist loading " + (retryCount + 1) + "/" + retryConfig.maxNumRetry + " after \"" + errorDetails + "\" without delivery-directives");
  5936. this.loadPlaylist();
  5937. } else {
  5938. var delay = getRetryDelay(retryConfig, retryCount);
  5939. // Schedule level/track reload
  5940. this.timer = self.setTimeout(function () {
  5941. return _this2.loadPlaylist();
  5942. }, delay);
  5943. this.warn("Retrying playlist loading " + (retryCount + 1) + "/" + retryConfig.maxNumRetry + " after \"" + errorDetails + "\" in " + delay + "ms");
  5944. }
  5945. // `levelRetry = true` used to inform other controllers that a retry is happening
  5946. errorEvent.levelRetry = true;
  5947. errorAction.resolved = true;
  5948. }
  5949. return retry;
  5950. };
  5951. return BasePlaylistController;
  5952. }();
  5953. /*
  5954. * compute an Exponential Weighted moving average
  5955. * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  5956. * - heavily inspired from shaka-player
  5957. */
  5958. var EWMA = /*#__PURE__*/function () {
  5959. // About half of the estimated value will be from the last |halfLife| samples by weight.
  5960. function EWMA(halfLife, estimate, weight) {
  5961. if (estimate === void 0) {
  5962. estimate = 0;
  5963. }
  5964. if (weight === void 0) {
  5965. weight = 0;
  5966. }
  5967. this.halfLife = void 0;
  5968. this.alpha_ = void 0;
  5969. this.estimate_ = void 0;
  5970. this.totalWeight_ = void 0;
  5971. this.halfLife = halfLife;
  5972. // Larger values of alpha expire historical data more slowly.
  5973. this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
  5974. this.estimate_ = estimate;
  5975. this.totalWeight_ = weight;
  5976. }
  5977. var _proto = EWMA.prototype;
  5978. _proto.sample = function sample(weight, value) {
  5979. var adjAlpha = Math.pow(this.alpha_, weight);
  5980. this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
  5981. this.totalWeight_ += weight;
  5982. };
  5983. _proto.getTotalWeight = function getTotalWeight() {
  5984. return this.totalWeight_;
  5985. };
  5986. _proto.getEstimate = function getEstimate() {
  5987. if (this.alpha_) {
  5988. var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
  5989. if (zeroFactor) {
  5990. return this.estimate_ / zeroFactor;
  5991. }
  5992. }
  5993. return this.estimate_;
  5994. };
  5995. return EWMA;
  5996. }();
  5997. /*
  5998. * EWMA Bandwidth Estimator
  5999. * - heavily inspired from shaka-player
  6000. * Tracks bandwidth samples and estimates available bandwidth.
  6001. * Based on the minimum of two exponentially-weighted moving averages with
  6002. * different half-lives.
  6003. */
  6004. var EwmaBandWidthEstimator = /*#__PURE__*/function () {
  6005. function EwmaBandWidthEstimator(slow, fast, defaultEstimate, defaultTTFB) {
  6006. if (defaultTTFB === void 0) {
  6007. defaultTTFB = 100;
  6008. }
  6009. this.defaultEstimate_ = void 0;
  6010. this.minWeight_ = void 0;
  6011. this.minDelayMs_ = void 0;
  6012. this.slow_ = void 0;
  6013. this.fast_ = void 0;
  6014. this.defaultTTFB_ = void 0;
  6015. this.ttfb_ = void 0;
  6016. this.defaultEstimate_ = defaultEstimate;
  6017. this.minWeight_ = 0.001;
  6018. this.minDelayMs_ = 50;
  6019. this.slow_ = new EWMA(slow);
  6020. this.fast_ = new EWMA(fast);
  6021. this.defaultTTFB_ = defaultTTFB;
  6022. this.ttfb_ = new EWMA(slow);
  6023. }
  6024. var _proto = EwmaBandWidthEstimator.prototype;
  6025. _proto.update = function update(slow, fast) {
  6026. var slow_ = this.slow_,
  6027. fast_ = this.fast_,
  6028. ttfb_ = this.ttfb_;
  6029. if (slow_.halfLife !== slow) {
  6030. this.slow_ = new EWMA(slow, slow_.getEstimate(), slow_.getTotalWeight());
  6031. }
  6032. if (fast_.halfLife !== fast) {
  6033. this.fast_ = new EWMA(fast, fast_.getEstimate(), fast_.getTotalWeight());
  6034. }
  6035. if (ttfb_.halfLife !== slow) {
  6036. this.ttfb_ = new EWMA(slow, ttfb_.getEstimate(), ttfb_.getTotalWeight());
  6037. }
  6038. };
  6039. _proto.sample = function sample(durationMs, numBytes) {
  6040. durationMs = Math.max(durationMs, this.minDelayMs_);
  6041. var numBits = 8 * numBytes;
  6042. // weight is duration in seconds
  6043. var durationS = durationMs / 1000;
  6044. // value is bandwidth in bits/s
  6045. var bandwidthInBps = numBits / durationS;
  6046. this.fast_.sample(durationS, bandwidthInBps);
  6047. this.slow_.sample(durationS, bandwidthInBps);
  6048. };
  6049. _proto.sampleTTFB = function sampleTTFB(ttfb) {
  6050. // weight is frequency curve applied to TTFB in seconds
  6051. // (longer times have less weight with expected input under 1 second)
  6052. var seconds = ttfb / 1000;
  6053. var weight = Math.sqrt(2) * Math.exp(-Math.pow(seconds, 2) / 2);
  6054. this.ttfb_.sample(weight, Math.max(ttfb, 5));
  6055. };
  6056. _proto.canEstimate = function canEstimate() {
  6057. return this.fast_.getTotalWeight() >= this.minWeight_;
  6058. };
  6059. _proto.getEstimate = function getEstimate() {
  6060. if (this.canEstimate()) {
  6061. // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));
  6062. // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));
  6063. // Take the minimum of these two estimates. This should have the effect of
  6064. // adapting down quickly, but up more slowly.
  6065. return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
  6066. } else {
  6067. return this.defaultEstimate_;
  6068. }
  6069. };
  6070. _proto.getEstimateTTFB = function getEstimateTTFB() {
  6071. if (this.ttfb_.getTotalWeight() >= this.minWeight_) {
  6072. return this.ttfb_.getEstimate();
  6073. } else {
  6074. return this.defaultTTFB_;
  6075. }
  6076. };
  6077. _proto.destroy = function destroy() {};
  6078. return EwmaBandWidthEstimator;
  6079. }();
  6080. /**
  6081. * @returns Whether we can detect and validate HDR capability within the window context
  6082. */
  6083. function isHdrSupported() {
  6084. if (typeof matchMedia === 'function') {
  6085. var mediaQueryList = matchMedia('(dynamic-range: high)');
  6086. var badQuery = matchMedia('bad query');
  6087. if (mediaQueryList.media !== badQuery.media) {
  6088. return mediaQueryList.matches === true;
  6089. }
  6090. }
  6091. return false;
  6092. }
  6093. /**
  6094. * Sanitizes inputs to return the active video selection options for HDR/SDR.
  6095. * When both inputs are null:
  6096. *
  6097. * `{ preferHDR: false, allowedVideoRanges: [] }`
  6098. *
  6099. * When `currentVideoRange` non-null, maintain the active range:
  6100. *
  6101. * `{ preferHDR: currentVideoRange !== 'SDR', allowedVideoRanges: [currentVideoRange] }`
  6102. *
  6103. * When VideoSelectionOption non-null:
  6104. *
  6105. * - Allow all video ranges if `allowedVideoRanges` unspecified.
  6106. * - If `preferHDR` is non-null use the value to filter `allowedVideoRanges`.
  6107. * - Else check window for HDR support and set `preferHDR` to the result.
  6108. *
  6109. * @param currentVideoRange
  6110. * @param videoPreference
  6111. */
  6112. function getVideoSelectionOptions(currentVideoRange, videoPreference) {
  6113. var preferHDR = false;
  6114. var allowedVideoRanges = [];
  6115. if (currentVideoRange) {
  6116. preferHDR = currentVideoRange !== 'SDR';
  6117. allowedVideoRanges = [currentVideoRange];
  6118. }
  6119. if (videoPreference) {
  6120. allowedVideoRanges = videoPreference.allowedVideoRanges || VideoRangeValues.slice(0);
  6121. preferHDR = videoPreference.preferHDR !== undefined ? videoPreference.preferHDR : isHdrSupported();
  6122. if (preferHDR) {
  6123. allowedVideoRanges = allowedVideoRanges.filter(function (range) {
  6124. return range !== 'SDR';
  6125. });
  6126. } else {
  6127. allowedVideoRanges = ['SDR'];
  6128. }
  6129. }
  6130. return {
  6131. preferHDR: preferHDR,
  6132. allowedVideoRanges: allowedVideoRanges
  6133. };
  6134. }
  6135. function getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference) {
  6136. var codecSets = Object.keys(codecTiers);
  6137. var channelsPreference = audioPreference == null ? void 0 : audioPreference.channels;
  6138. var audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec;
  6139. var preferStereo = channelsPreference && parseInt(channelsPreference) === 2;
  6140. // Use first level set to determine stereo, and minimum resolution and framerate
  6141. var hasStereo = true;
  6142. var hasCurrentVideoRange = false;
  6143. var minHeight = Infinity;
  6144. var minFramerate = Infinity;
  6145. var minBitrate = Infinity;
  6146. var selectedScore = 0;
  6147. var videoRanges = [];
  6148. var _getVideoSelectionOpt = getVideoSelectionOptions(currentVideoRange, videoPreference),
  6149. preferHDR = _getVideoSelectionOpt.preferHDR,
  6150. allowedVideoRanges = _getVideoSelectionOpt.allowedVideoRanges;
  6151. var _loop = function _loop() {
  6152. var tier = codecTiers[codecSets[i]];
  6153. hasStereo = tier.channels[2] > 0;
  6154. minHeight = Math.min(minHeight, tier.minHeight);
  6155. minFramerate = Math.min(minFramerate, tier.minFramerate);
  6156. minBitrate = Math.min(minBitrate, tier.minBitrate);
  6157. var matchingVideoRanges = allowedVideoRanges.filter(function (range) {
  6158. return tier.videoRanges[range] > 0;
  6159. });
  6160. if (matchingVideoRanges.length > 0) {
  6161. hasCurrentVideoRange = true;
  6162. videoRanges = matchingVideoRanges;
  6163. }
  6164. };
  6165. for (var i = codecSets.length; i--;) {
  6166. _loop();
  6167. }
  6168. minHeight = isFiniteNumber(minHeight) ? minHeight : 0;
  6169. minFramerate = isFiniteNumber(minFramerate) ? minFramerate : 0;
  6170. var maxHeight = Math.max(1080, minHeight);
  6171. var maxFramerate = Math.max(30, minFramerate);
  6172. minBitrate = isFiniteNumber(minBitrate) ? minBitrate : currentBw;
  6173. currentBw = Math.max(minBitrate, currentBw);
  6174. // If there are no variants with matching preference, set currentVideoRange to undefined
  6175. if (!hasCurrentVideoRange) {
  6176. currentVideoRange = undefined;
  6177. videoRanges = [];
  6178. }
  6179. var codecSet = codecSets.reduce(function (selected, candidate) {
  6180. // 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
  6181. var candidateTier = codecTiers[candidate];
  6182. if (candidate === selected) {
  6183. return selected;
  6184. }
  6185. if (candidateTier.minBitrate > currentBw) {
  6186. logStartCodecCandidateIgnored(candidate, "min bitrate of " + candidateTier.minBitrate + " > current estimate of " + currentBw);
  6187. return selected;
  6188. }
  6189. if (!candidateTier.hasDefaultAudio) {
  6190. logStartCodecCandidateIgnored(candidate, "no renditions with default or auto-select sound found");
  6191. return selected;
  6192. }
  6193. if (audioCodecPreference && candidate.indexOf(audioCodecPreference.substring(0, 4)) % 5 !== 0) {
  6194. logStartCodecCandidateIgnored(candidate, "audio codec preference \"" + audioCodecPreference + "\" not found");
  6195. return selected;
  6196. }
  6197. if (channelsPreference && !preferStereo) {
  6198. if (!candidateTier.channels[channelsPreference]) {
  6199. logStartCodecCandidateIgnored(candidate, "no renditions with " + channelsPreference + " channel sound found (channels options: " + Object.keys(candidateTier.channels) + ")");
  6200. return selected;
  6201. }
  6202. } else if ((!audioCodecPreference || preferStereo) && hasStereo && candidateTier.channels['2'] === 0) {
  6203. logStartCodecCandidateIgnored(candidate, "no renditions with stereo sound found");
  6204. return selected;
  6205. }
  6206. if (candidateTier.minHeight > maxHeight) {
  6207. logStartCodecCandidateIgnored(candidate, "min resolution of " + candidateTier.minHeight + " > maximum of " + maxHeight);
  6208. return selected;
  6209. }
  6210. if (candidateTier.minFramerate > maxFramerate) {
  6211. logStartCodecCandidateIgnored(candidate, "min framerate of " + candidateTier.minFramerate + " > maximum of " + maxFramerate);
  6212. return selected;
  6213. }
  6214. if (!videoRanges.some(function (range) {
  6215. return candidateTier.videoRanges[range] > 0;
  6216. })) {
  6217. logStartCodecCandidateIgnored(candidate, "no variants with VIDEO-RANGE of " + JSON.stringify(videoRanges) + " found");
  6218. return selected;
  6219. }
  6220. if (candidateTier.maxScore < selectedScore) {
  6221. logStartCodecCandidateIgnored(candidate, "max score of " + candidateTier.maxScore + " < selected max of " + selectedScore);
  6222. return selected;
  6223. }
  6224. // Remove candiates with less preferred codecs or more errors
  6225. if (selected && (codecsSetSelectionPreferenceValue(candidate) >= codecsSetSelectionPreferenceValue(selected) || candidateTier.fragmentError > codecTiers[selected].fragmentError)) {
  6226. return selected;
  6227. }
  6228. selectedScore = candidateTier.maxScore;
  6229. return candidate;
  6230. }, undefined);
  6231. return {
  6232. codecSet: codecSet,
  6233. videoRanges: videoRanges,
  6234. preferHDR: preferHDR,
  6235. minFramerate: minFramerate,
  6236. minBitrate: minBitrate
  6237. };
  6238. }
  6239. function logStartCodecCandidateIgnored(codeSet, reason) {
  6240. logger.log("[abr] start candidates with \"" + codeSet + "\" ignored because " + reason);
  6241. }
  6242. function getAudioTracksByGroup(allAudioTracks) {
  6243. return allAudioTracks.reduce(function (audioTracksByGroup, track) {
  6244. var trackGroup = audioTracksByGroup.groups[track.groupId];
  6245. if (!trackGroup) {
  6246. trackGroup = audioTracksByGroup.groups[track.groupId] = {
  6247. tracks: [],
  6248. channels: {
  6249. 2: 0
  6250. },
  6251. hasDefault: false,
  6252. hasAutoSelect: false
  6253. };
  6254. }
  6255. trackGroup.tracks.push(track);
  6256. var channelsKey = track.channels || '2';
  6257. trackGroup.channels[channelsKey] = (trackGroup.channels[channelsKey] || 0) + 1;
  6258. trackGroup.hasDefault = trackGroup.hasDefault || track.default;
  6259. trackGroup.hasAutoSelect = trackGroup.hasAutoSelect || track.autoselect;
  6260. if (trackGroup.hasDefault) {
  6261. audioTracksByGroup.hasDefaultAudio = true;
  6262. }
  6263. if (trackGroup.hasAutoSelect) {
  6264. audioTracksByGroup.hasAutoSelectAudio = true;
  6265. }
  6266. return audioTracksByGroup;
  6267. }, {
  6268. hasDefaultAudio: false,
  6269. hasAutoSelectAudio: false,
  6270. groups: {}
  6271. });
  6272. }
  6273. function getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel) {
  6274. return levels.slice(minAutoLevel, maxAutoLevel + 1).reduce(function (tiers, level) {
  6275. if (!level.codecSet) {
  6276. return tiers;
  6277. }
  6278. var audioGroups = level.audioGroups;
  6279. var tier = tiers[level.codecSet];
  6280. if (!tier) {
  6281. tiers[level.codecSet] = tier = {
  6282. minBitrate: Infinity,
  6283. minHeight: Infinity,
  6284. minFramerate: Infinity,
  6285. maxScore: 0,
  6286. videoRanges: {
  6287. SDR: 0
  6288. },
  6289. channels: {
  6290. '2': 0
  6291. },
  6292. hasDefaultAudio: !audioGroups,
  6293. fragmentError: 0
  6294. };
  6295. }
  6296. tier.minBitrate = Math.min(tier.minBitrate, level.bitrate);
  6297. var lesserWidthOrHeight = Math.min(level.height, level.width);
  6298. tier.minHeight = Math.min(tier.minHeight, lesserWidthOrHeight);
  6299. tier.minFramerate = Math.min(tier.minFramerate, level.frameRate);
  6300. tier.maxScore = Math.max(tier.maxScore, level.score);
  6301. tier.fragmentError += level.fragmentError;
  6302. tier.videoRanges[level.videoRange] = (tier.videoRanges[level.videoRange] || 0) + 1;
  6303. return tiers;
  6304. }, {});
  6305. }
  6306. var AbrController = /*#__PURE__*/function () {
  6307. function AbrController(_hls) {
  6308. var _this = this;
  6309. this.hls = void 0;
  6310. this.lastLevelLoadSec = 0;
  6311. this.lastLoadedFragLevel = -1;
  6312. this.firstSelection = -1;
  6313. this._nextAutoLevel = -1;
  6314. this.nextAutoLevelKey = '';
  6315. this.audioTracksByGroup = null;
  6316. this.codecTiers = null;
  6317. this.timer = -1;
  6318. this.fragCurrent = null;
  6319. this.partCurrent = null;
  6320. this.bitrateTestDelay = 0;
  6321. this.bwEstimator = void 0;
  6322. /*
  6323. This method monitors the download rate of the current fragment, and will downswitch if that fragment will not load
  6324. quickly enough to prevent underbuffering
  6325. */
  6326. this._abandonRulesCheck = function () {
  6327. var frag = _this.fragCurrent,
  6328. part = _this.partCurrent,
  6329. hls = _this.hls;
  6330. var autoLevelEnabled = hls.autoLevelEnabled,
  6331. media = hls.media;
  6332. if (!frag || !media) {
  6333. return;
  6334. }
  6335. var now = performance.now();
  6336. var stats = part ? part.stats : frag.stats;
  6337. var duration = part ? part.duration : frag.duration;
  6338. var timeLoading = now - stats.loading.start;
  6339. var minAutoLevel = hls.minAutoLevel;
  6340. // If frag loading is aborted, complete, or from lowest level, stop timer and return
  6341. if (stats.aborted || stats.loaded && stats.loaded === stats.total || frag.level <= minAutoLevel) {
  6342. _this.clearTimer();
  6343. // reset forced auto level value so that next level will be selected
  6344. _this._nextAutoLevel = -1;
  6345. return;
  6346. }
  6347. // This check only runs if we're in ABR mode and actually playing
  6348. if (!autoLevelEnabled || media.paused || !media.playbackRate || !media.readyState) {
  6349. return;
  6350. }
  6351. var bufferInfo = hls.mainForwardBufferInfo;
  6352. if (bufferInfo === null) {
  6353. return;
  6354. }
  6355. var ttfbEstimate = _this.bwEstimator.getEstimateTTFB();
  6356. var playbackRate = Math.abs(media.playbackRate);
  6357. // To maintain stable adaptive playback, only begin monitoring frag loading after half or more of its playback duration has passed
  6358. if (timeLoading <= Math.max(ttfbEstimate, 1000 * (duration / (playbackRate * 2)))) {
  6359. return;
  6360. }
  6361. // bufferStarvationDelay is an estimate of the amount time (in seconds) it will take to exhaust the buffer
  6362. var bufferStarvationDelay = bufferInfo.len / playbackRate;
  6363. var ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  6364. var loadedFirstByte = stats.loaded && ttfb > -1;
  6365. var bwEstimate = _this.getBwEstimate();
  6366. var levels = hls.levels;
  6367. var level = levels[frag.level];
  6368. var expectedLen = stats.total || Math.max(stats.loaded, Math.round(duration * level.averageBitrate / 8));
  6369. var timeStreaming = loadedFirstByte ? timeLoading - ttfb : timeLoading;
  6370. if (timeStreaming < 1 && loadedFirstByte) {
  6371. timeStreaming = Math.min(timeLoading, stats.loaded * 8 / bwEstimate);
  6372. }
  6373. var loadRate = loadedFirstByte ? stats.loaded * 1000 / timeStreaming : 0;
  6374. // fragLoadDelay is an estimate of the time (in seconds) it will take to buffer the remainder of the fragment
  6375. var fragLoadedDelay = loadRate ? (expectedLen - stats.loaded) / loadRate : expectedLen * 8 / bwEstimate + ttfbEstimate / 1000;
  6376. // Only downswitch if the time to finish loading the current fragment is greater than the amount of buffer left
  6377. if (fragLoadedDelay <= bufferStarvationDelay) {
  6378. return;
  6379. }
  6380. var bwe = loadRate ? loadRate * 8 : bwEstimate;
  6381. var fragLevelNextLoadedDelay = Number.POSITIVE_INFINITY;
  6382. var nextLoadLevel;
  6383. // Iterate through lower level and try to find the largest one that avoids rebuffering
  6384. for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
  6385. // compute time to load next fragment at lower level
  6386. // 8 = bits per byte (bps/Bps)
  6387. var levelNextBitrate = levels[nextLoadLevel].maxBitrate;
  6388. fragLevelNextLoadedDelay = _this.getTimeToLoadFrag(ttfbEstimate / 1000, bwe, duration * levelNextBitrate, !levels[nextLoadLevel].details);
  6389. if (fragLevelNextLoadedDelay < bufferStarvationDelay) {
  6390. break;
  6391. }
  6392. }
  6393. // Only emergency switch down if it takes less time to load a new fragment at lowest level instead of continuing
  6394. // to load the current one
  6395. if (fragLevelNextLoadedDelay >= fragLoadedDelay) {
  6396. return;
  6397. }
  6398. // if estimated load time of new segment is completely unreasonable, ignore and do not emergency switch down
  6399. if (fragLevelNextLoadedDelay > duration * 10) {
  6400. return;
  6401. }
  6402. hls.nextLoadLevel = hls.nextAutoLevel = nextLoadLevel;
  6403. if (loadedFirstByte) {
  6404. // If there has been loading progress, sample bandwidth using loading time offset by minimum TTFB time
  6405. _this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  6406. } else {
  6407. // If there has been no loading progress, sample TTFB
  6408. _this.bwEstimator.sampleTTFB(timeLoading);
  6409. }
  6410. var nextLoadLevelBitrate = levels[nextLoadLevel].maxBitrate;
  6411. if (_this.getBwEstimate() * _this.hls.config.abrBandWidthUpFactor > nextLoadLevelBitrate) {
  6412. _this.resetEstimator(nextLoadLevelBitrate);
  6413. }
  6414. _this.clearTimer();
  6415. 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");
  6416. hls.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED, {
  6417. frag: frag,
  6418. part: part,
  6419. stats: stats
  6420. });
  6421. };
  6422. this.hls = _hls;
  6423. this.bwEstimator = this.initEstimator();
  6424. this.registerListeners();
  6425. }
  6426. var _proto = AbrController.prototype;
  6427. _proto.resetEstimator = function resetEstimator(abrEwmaDefaultEstimate) {
  6428. if (abrEwmaDefaultEstimate) {
  6429. logger.log("setting initial bwe to " + abrEwmaDefaultEstimate);
  6430. this.hls.config.abrEwmaDefaultEstimate = abrEwmaDefaultEstimate;
  6431. }
  6432. this.firstSelection = -1;
  6433. this.bwEstimator = this.initEstimator();
  6434. };
  6435. _proto.initEstimator = function initEstimator() {
  6436. var config = this.hls.config;
  6437. return new EwmaBandWidthEstimator(config.abrEwmaSlowVoD, config.abrEwmaFastVoD, config.abrEwmaDefaultEstimate);
  6438. };
  6439. _proto.registerListeners = function registerListeners() {
  6440. var hls = this.hls;
  6441. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  6442. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  6443. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  6444. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  6445. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  6446. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  6447. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  6448. hls.on(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  6449. hls.on(Events.ERROR, this.onError, this);
  6450. };
  6451. _proto.unregisterListeners = function unregisterListeners() {
  6452. var hls = this.hls;
  6453. if (!hls) {
  6454. return;
  6455. }
  6456. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  6457. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  6458. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  6459. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  6460. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  6461. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  6462. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  6463. hls.off(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  6464. hls.off(Events.ERROR, this.onError, this);
  6465. };
  6466. _proto.destroy = function destroy() {
  6467. this.unregisterListeners();
  6468. this.clearTimer();
  6469. // @ts-ignore
  6470. this.hls = this._abandonRulesCheck = null;
  6471. this.fragCurrent = this.partCurrent = null;
  6472. };
  6473. _proto.onManifestLoading = function onManifestLoading(event, data) {
  6474. this.lastLoadedFragLevel = -1;
  6475. this.firstSelection = -1;
  6476. this.lastLevelLoadSec = 0;
  6477. this.fragCurrent = this.partCurrent = null;
  6478. this.onLevelsUpdated();
  6479. this.clearTimer();
  6480. };
  6481. _proto.onLevelsUpdated = function onLevelsUpdated() {
  6482. if (this.lastLoadedFragLevel > -1 && this.fragCurrent) {
  6483. this.lastLoadedFragLevel = this.fragCurrent.level;
  6484. }
  6485. this._nextAutoLevel = -1;
  6486. this.onMaxAutoLevelUpdated();
  6487. this.codecTiers = null;
  6488. this.audioTracksByGroup = null;
  6489. };
  6490. _proto.onMaxAutoLevelUpdated = function onMaxAutoLevelUpdated() {
  6491. this.firstSelection = -1;
  6492. this.nextAutoLevelKey = '';
  6493. };
  6494. _proto.onFragLoading = function onFragLoading(event, data) {
  6495. var frag = data.frag;
  6496. if (this.ignoreFragment(frag)) {
  6497. return;
  6498. }
  6499. if (!frag.bitrateTest) {
  6500. var _data$part;
  6501. this.fragCurrent = frag;
  6502. this.partCurrent = (_data$part = data.part) != null ? _data$part : null;
  6503. }
  6504. this.clearTimer();
  6505. this.timer = self.setInterval(this._abandonRulesCheck, 100);
  6506. };
  6507. _proto.onLevelSwitching = function onLevelSwitching(event, data) {
  6508. this.clearTimer();
  6509. };
  6510. _proto.onError = function onError(event, data) {
  6511. if (data.fatal) {
  6512. return;
  6513. }
  6514. switch (data.details) {
  6515. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  6516. case ErrorDetails.BUFFER_APPEND_ERROR:
  6517. // Reset last loaded level so that a new selection can be made after calling recoverMediaError
  6518. this.lastLoadedFragLevel = -1;
  6519. this.firstSelection = -1;
  6520. break;
  6521. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  6522. {
  6523. var frag = data.frag;
  6524. var fragCurrent = this.fragCurrent,
  6525. part = this.partCurrent;
  6526. if (frag && fragCurrent && frag.sn === fragCurrent.sn && frag.level === fragCurrent.level) {
  6527. var now = performance.now();
  6528. var stats = part ? part.stats : frag.stats;
  6529. var timeLoading = now - stats.loading.start;
  6530. var ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  6531. var loadedFirstByte = stats.loaded && ttfb > -1;
  6532. if (loadedFirstByte) {
  6533. var ttfbEstimate = this.bwEstimator.getEstimateTTFB();
  6534. this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  6535. } else {
  6536. this.bwEstimator.sampleTTFB(timeLoading);
  6537. }
  6538. }
  6539. break;
  6540. }
  6541. }
  6542. };
  6543. _proto.getTimeToLoadFrag = function getTimeToLoadFrag(timeToFirstByteSec, bandwidth, fragSizeBits, isSwitch) {
  6544. var fragLoadSec = timeToFirstByteSec + fragSizeBits / bandwidth;
  6545. var playlistLoadSec = isSwitch ? this.lastLevelLoadSec : 0;
  6546. return fragLoadSec + playlistLoadSec;
  6547. };
  6548. _proto.onLevelLoaded = function onLevelLoaded(event, data) {
  6549. var config = this.hls.config;
  6550. var loading = data.stats.loading;
  6551. var timeLoadingMs = loading.end - loading.start;
  6552. if (isFiniteNumber(timeLoadingMs)) {
  6553. this.lastLevelLoadSec = timeLoadingMs / 1000;
  6554. }
  6555. if (data.details.live) {
  6556. this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive);
  6557. } else {
  6558. this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD);
  6559. }
  6560. };
  6561. _proto.onFragLoaded = function onFragLoaded(event, _ref) {
  6562. var frag = _ref.frag,
  6563. part = _ref.part;
  6564. var stats = part ? part.stats : frag.stats;
  6565. if (frag.type === PlaylistLevelType.MAIN) {
  6566. this.bwEstimator.sampleTTFB(stats.loading.first - stats.loading.start);
  6567. }
  6568. if (this.ignoreFragment(frag)) {
  6569. return;
  6570. }
  6571. // stop monitoring bw once frag loaded
  6572. this.clearTimer();
  6573. // reset forced auto level value so that next level will be selected
  6574. if (frag.level === this._nextAutoLevel) {
  6575. this._nextAutoLevel = -1;
  6576. }
  6577. this.firstSelection = -1;
  6578. // compute level average bitrate
  6579. if (this.hls.config.abrMaxWithRealBitrate) {
  6580. var duration = part ? part.duration : frag.duration;
  6581. var level = this.hls.levels[frag.level];
  6582. var loadedBytes = (level.loaded ? level.loaded.bytes : 0) + stats.loaded;
  6583. var loadedDuration = (level.loaded ? level.loaded.duration : 0) + duration;
  6584. level.loaded = {
  6585. bytes: loadedBytes,
  6586. duration: loadedDuration
  6587. };
  6588. level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
  6589. }
  6590. if (frag.bitrateTest) {
  6591. var fragBufferedData = {
  6592. stats: stats,
  6593. frag: frag,
  6594. part: part,
  6595. id: frag.type
  6596. };
  6597. this.onFragBuffered(Events.FRAG_BUFFERED, fragBufferedData);
  6598. frag.bitrateTest = false;
  6599. } else {
  6600. // store level id after successful fragment load for playback
  6601. this.lastLoadedFragLevel = frag.level;
  6602. }
  6603. };
  6604. _proto.onFragBuffered = function onFragBuffered(event, data) {
  6605. var frag = data.frag,
  6606. part = data.part;
  6607. var stats = part != null && part.stats.loaded ? part.stats : frag.stats;
  6608. if (stats.aborted) {
  6609. return;
  6610. }
  6611. if (this.ignoreFragment(frag)) {
  6612. return;
  6613. }
  6614. // Use the difference between parsing and request instead of buffering and request to compute fragLoadingProcessing;
  6615. // rationale is that buffer appending only happens once media is attached. This can happen when config.startFragPrefetch
  6616. // is used. If we used buffering in that case, our BW estimate sample will be very large.
  6617. var processingMs = stats.parsing.end - stats.loading.start - Math.min(stats.loading.first - stats.loading.start, this.bwEstimator.getEstimateTTFB());
  6618. this.bwEstimator.sample(processingMs, stats.loaded);
  6619. stats.bwEstimate = this.getBwEstimate();
  6620. if (frag.bitrateTest) {
  6621. this.bitrateTestDelay = processingMs / 1000;
  6622. } else {
  6623. this.bitrateTestDelay = 0;
  6624. }
  6625. };
  6626. _proto.ignoreFragment = function ignoreFragment(frag) {
  6627. // Only count non-alt-audio frags which were actually buffered in our BW calculations
  6628. return frag.type !== PlaylistLevelType.MAIN || frag.sn === 'initSegment';
  6629. };
  6630. _proto.clearTimer = function clearTimer() {
  6631. if (this.timer > -1) {
  6632. self.clearInterval(this.timer);
  6633. this.timer = -1;
  6634. }
  6635. };
  6636. _proto.getAutoLevelKey = function getAutoLevelKey() {
  6637. return this.getBwEstimate() + "_" + this.getStarvationDelay().toFixed(2);
  6638. };
  6639. _proto.getNextABRAutoLevel = function getNextABRAutoLevel() {
  6640. var fragCurrent = this.fragCurrent,
  6641. partCurrent = this.partCurrent,
  6642. hls = this.hls;
  6643. var maxAutoLevel = hls.maxAutoLevel,
  6644. config = hls.config,
  6645. minAutoLevel = hls.minAutoLevel;
  6646. var currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  6647. var avgbw = this.getBwEstimate();
  6648. // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.
  6649. var bufferStarvationDelay = this.getStarvationDelay();
  6650. var bwFactor = config.abrBandWidthFactor;
  6651. var bwUpFactor = config.abrBandWidthUpFactor;
  6652. // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all
  6653. if (bufferStarvationDelay) {
  6654. var _bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, 0, bwFactor, bwUpFactor);
  6655. if (_bestLevel >= 0) {
  6656. return _bestLevel;
  6657. }
  6658. }
  6659. // not possible to get rid of rebuffering... try to find level that will guarantee less than maxStarvationDelay of rebuffering
  6660. var maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay;
  6661. if (!bufferStarvationDelay) {
  6662. // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test
  6663. var bitrateTestDelay = this.bitrateTestDelay;
  6664. if (bitrateTestDelay) {
  6665. // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value
  6666. // max video loading delay used in automatic start level selection :
  6667. // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +
  6668. // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )
  6669. // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration
  6670. var maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
  6671. maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
  6672. logger.info("[abr] bitrate test took " + Math.round(1000 * bitrateTestDelay) + "ms, set first fragment max fetchDuration to " + Math.round(1000 * maxStarvationDelay) + " ms");
  6673. // don't use conservative factor on bitrate test
  6674. bwFactor = bwUpFactor = 1;
  6675. }
  6676. }
  6677. var bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor);
  6678. logger.info("[abr] " + (bufferStarvationDelay ? 'rebuffering expected' : 'buffer is empty') + ", optimal quality level " + bestLevel);
  6679. if (bestLevel > -1) {
  6680. return bestLevel;
  6681. }
  6682. // If no matching level found, see if min auto level would be a better option
  6683. var minLevel = hls.levels[minAutoLevel];
  6684. var autoLevel = hls.levels[hls.loadLevel];
  6685. if ((minLevel == null ? void 0 : minLevel.bitrate) < (autoLevel == null ? void 0 : autoLevel.bitrate)) {
  6686. return minAutoLevel;
  6687. }
  6688. // or if bitrate is not lower, continue to use loadLevel
  6689. return hls.loadLevel;
  6690. };
  6691. _proto.getStarvationDelay = function getStarvationDelay() {
  6692. var hls = this.hls;
  6693. var media = hls.media;
  6694. if (!media) {
  6695. return Infinity;
  6696. }
  6697. // playbackRate is the absolute value of the playback rate; if media.playbackRate is 0, we use 1 to load as
  6698. // if we're playing back at the normal rate.
  6699. var playbackRate = media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1.0;
  6700. var bufferInfo = hls.mainForwardBufferInfo;
  6701. return (bufferInfo ? bufferInfo.len : 0) / playbackRate;
  6702. };
  6703. _proto.getBwEstimate = function getBwEstimate() {
  6704. return this.bwEstimator.canEstimate() ? this.bwEstimator.getEstimate() : this.hls.config.abrEwmaDefaultEstimate;
  6705. };
  6706. _proto.findBestLevel = function findBestLevel(currentBw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor) {
  6707. var _level$details,
  6708. _this2 = this;
  6709. var maxFetchDuration = bufferStarvationDelay + maxStarvationDelay;
  6710. var lastLoadedFragLevel = this.lastLoadedFragLevel;
  6711. var selectionBaseLevel = lastLoadedFragLevel === -1 ? this.hls.firstLevel : lastLoadedFragLevel;
  6712. var fragCurrent = this.fragCurrent,
  6713. partCurrent = this.partCurrent;
  6714. var _this$hls = this.hls,
  6715. levels = _this$hls.levels,
  6716. allAudioTracks = _this$hls.allAudioTracks,
  6717. loadLevel = _this$hls.loadLevel,
  6718. config = _this$hls.config;
  6719. if (levels.length === 1) {
  6720. return 0;
  6721. }
  6722. var level = levels[selectionBaseLevel];
  6723. var live = !!(level != null && (_level$details = level.details) != null && _level$details.live);
  6724. var firstSelection = loadLevel === -1 || lastLoadedFragLevel === -1;
  6725. var currentCodecSet;
  6726. var currentVideoRange = 'SDR';
  6727. var currentFrameRate = (level == null ? void 0 : level.frameRate) || 0;
  6728. var audioPreference = config.audioPreference,
  6729. videoPreference = config.videoPreference;
  6730. var audioTracksByGroup = this.audioTracksByGroup || (this.audioTracksByGroup = getAudioTracksByGroup(allAudioTracks));
  6731. if (firstSelection) {
  6732. if (this.firstSelection !== -1) {
  6733. return this.firstSelection;
  6734. }
  6735. var codecTiers = this.codecTiers || (this.codecTiers = getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel));
  6736. var startTier = getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference);
  6737. var codecSet = startTier.codecSet,
  6738. videoRanges = startTier.videoRanges,
  6739. minFramerate = startTier.minFramerate,
  6740. minBitrate = startTier.minBitrate,
  6741. preferHDR = startTier.preferHDR;
  6742. currentCodecSet = codecSet;
  6743. currentVideoRange = preferHDR ? videoRanges[videoRanges.length - 1] : videoRanges[0];
  6744. currentFrameRate = minFramerate;
  6745. currentBw = Math.max(currentBw, minBitrate);
  6746. logger.log("[abr] picked start tier " + JSON.stringify(startTier));
  6747. } else {
  6748. currentCodecSet = level == null ? void 0 : level.codecSet;
  6749. currentVideoRange = level == null ? void 0 : level.videoRange;
  6750. }
  6751. var currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  6752. var ttfbEstimateSec = this.bwEstimator.getEstimateTTFB() / 1000;
  6753. var levelsSkipped = [];
  6754. var _loop = function _loop() {
  6755. var _levelInfo$supportedR;
  6756. var levelInfo = levels[i];
  6757. var upSwitch = i > selectionBaseLevel;
  6758. if (!levelInfo) {
  6759. return 0; // continue
  6760. }
  6761. // skip candidates which change codec-family or video-range,
  6762. // and which decrease or increase frame-rate for up and down-switch respectfully
  6763. 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)) {
  6764. levelsSkipped.push(i);
  6765. return 0; // continue
  6766. }
  6767. var levelDetails = levelInfo.details;
  6768. var avgDuration = (partCurrent ? levelDetails == null ? void 0 : levelDetails.partTarget : levelDetails == null ? void 0 : levelDetails.averagetargetduration) || currentFragDuration;
  6769. var adjustedbw;
  6770. // follow algorithm captured from stagefright :
  6771. // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
  6772. // Pick the highest bandwidth stream below or equal to estimated bandwidth.
  6773. // consider only 80% of the available bandwidth, but if we are switching up,
  6774. // be even more conservative (70%) to avoid overestimating and immediately
  6775. // switching back.
  6776. if (!upSwitch) {
  6777. adjustedbw = bwFactor * currentBw;
  6778. } else {
  6779. adjustedbw = bwUpFactor * currentBw;
  6780. }
  6781. // Use average bitrate when starvation delay (buffer length) is gt or eq two segment durations and rebuffering is not expected (maxStarvationDelay > 0)
  6782. var bitrate = currentFragDuration && bufferStarvationDelay >= currentFragDuration * 2 && maxStarvationDelay === 0 ? levels[i].averageBitrate : levels[i].maxBitrate;
  6783. var fetchDuration = _this2.getTimeToLoadFrag(ttfbEstimateSec, adjustedbw, bitrate * avgDuration, levelDetails === undefined);
  6784. var canSwitchWithinTolerance =
  6785. // if adjusted bw is greater than level bitrate AND
  6786. adjustedbw >= bitrate && (
  6787. // no level change, or new level has no error history
  6788. i === lastLoadedFragLevel || levelInfo.loadError === 0 && levelInfo.fragmentError === 0) && (
  6789. // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
  6790. // 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 ...
  6791. // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1
  6792. fetchDuration <= ttfbEstimateSec || !isFiniteNumber(fetchDuration) || live && !_this2.bitrateTestDelay || fetchDuration < maxFetchDuration);
  6793. if (canSwitchWithinTolerance) {
  6794. var forcedAutoLevel = _this2.forcedAutoLevel;
  6795. if (i !== loadLevel && (forcedAutoLevel === -1 || forcedAutoLevel !== loadLevel)) {
  6796. if (levelsSkipped.length) {
  6797. 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);
  6798. }
  6799. 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);
  6800. }
  6801. if (firstSelection) {
  6802. _this2.firstSelection = i;
  6803. }
  6804. // as we are looping from highest to lowest, this will return the best achievable quality level
  6805. return {
  6806. v: i
  6807. };
  6808. }
  6809. },
  6810. _ret;
  6811. for (var i = maxAutoLevel; i >= minAutoLevel; i--) {
  6812. _ret = _loop();
  6813. if (_ret === 0) continue;
  6814. if (_ret) return _ret.v;
  6815. }
  6816. // not enough time budget even with quality level 0 ... rebuffering might happen
  6817. return -1;
  6818. };
  6819. _createClass(AbrController, [{
  6820. key: "firstAutoLevel",
  6821. get: function get() {
  6822. var _this$hls2 = this.hls,
  6823. maxAutoLevel = _this$hls2.maxAutoLevel,
  6824. minAutoLevel = _this$hls2.minAutoLevel;
  6825. var bwEstimate = this.getBwEstimate();
  6826. var maxStartDelay = this.hls.config.maxStarvationDelay;
  6827. var abrAutoLevel = this.findBestLevel(bwEstimate, minAutoLevel, maxAutoLevel, 0, maxStartDelay, 1, 1);
  6828. if (abrAutoLevel > -1) {
  6829. return abrAutoLevel;
  6830. }
  6831. var firstLevel = this.hls.firstLevel;
  6832. var clamped = Math.min(Math.max(firstLevel, minAutoLevel), maxAutoLevel);
  6833. logger.warn("[abr] Could not find best starting auto level. Defaulting to first in playlist " + firstLevel + " clamped to " + clamped);
  6834. return clamped;
  6835. }
  6836. }, {
  6837. key: "forcedAutoLevel",
  6838. get: function get() {
  6839. if (this.nextAutoLevelKey) {
  6840. return -1;
  6841. }
  6842. return this._nextAutoLevel;
  6843. }
  6844. // return next auto level
  6845. }, {
  6846. key: "nextAutoLevel",
  6847. get: function get() {
  6848. var forcedAutoLevel = this.forcedAutoLevel;
  6849. var bwEstimator = this.bwEstimator;
  6850. var useEstimate = bwEstimator.canEstimate();
  6851. var loadedFirstFrag = this.lastLoadedFragLevel > -1;
  6852. // in case next auto level has been forced, and bw not available or not reliable, return forced value
  6853. if (forcedAutoLevel !== -1 && (!useEstimate || !loadedFirstFrag || this.nextAutoLevelKey === this.getAutoLevelKey())) {
  6854. return forcedAutoLevel;
  6855. }
  6856. // compute next level using ABR logic
  6857. var nextABRAutoLevel = useEstimate && loadedFirstFrag ? this.getNextABRAutoLevel() : this.firstAutoLevel;
  6858. // use forced auto level while it hasn't errored more than ABR selection
  6859. if (forcedAutoLevel !== -1) {
  6860. var levels = this.hls.levels;
  6861. if (levels.length > Math.max(forcedAutoLevel, nextABRAutoLevel) && levels[forcedAutoLevel].loadError <= levels[nextABRAutoLevel].loadError) {
  6862. return forcedAutoLevel;
  6863. }
  6864. }
  6865. // save result until state has changed
  6866. this._nextAutoLevel = nextABRAutoLevel;
  6867. this.nextAutoLevelKey = this.getAutoLevelKey();
  6868. return nextABRAutoLevel;
  6869. },
  6870. set: function set(nextLevel) {
  6871. var _this$hls3 = this.hls,
  6872. maxAutoLevel = _this$hls3.maxAutoLevel,
  6873. minAutoLevel = _this$hls3.minAutoLevel;
  6874. var value = Math.min(Math.max(nextLevel, minAutoLevel), maxAutoLevel);
  6875. if (this._nextAutoLevel !== value) {
  6876. this.nextAutoLevelKey = '';
  6877. this._nextAutoLevel = value;
  6878. }
  6879. }
  6880. }]);
  6881. return AbrController;
  6882. }();
  6883. /**
  6884. * Provides methods dealing with buffer length retrieval for example.
  6885. *
  6886. * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.
  6887. *
  6888. * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered
  6889. */
  6890. var noopBuffered = {
  6891. length: 0,
  6892. start: function start() {
  6893. return 0;
  6894. },
  6895. end: function end() {
  6896. return 0;
  6897. }
  6898. };
  6899. var BufferHelper = /*#__PURE__*/function () {
  6900. function BufferHelper() {}
  6901. /**
  6902. * Return true if `media`'s buffered include `position`
  6903. */
  6904. BufferHelper.isBuffered = function isBuffered(media, position) {
  6905. try {
  6906. if (media) {
  6907. var buffered = BufferHelper.getBuffered(media);
  6908. for (var i = 0; i < buffered.length; i++) {
  6909. if (position >= buffered.start(i) && position <= buffered.end(i)) {
  6910. return true;
  6911. }
  6912. }
  6913. }
  6914. } catch (error) {
  6915. // this is to catch
  6916. // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
  6917. // This SourceBuffer has been removed from the parent media source
  6918. }
  6919. return false;
  6920. };
  6921. BufferHelper.bufferInfo = function bufferInfo(media, pos, maxHoleDuration) {
  6922. try {
  6923. if (media) {
  6924. var vbuffered = BufferHelper.getBuffered(media);
  6925. var buffered = [];
  6926. var i;
  6927. for (i = 0; i < vbuffered.length; i++) {
  6928. buffered.push({
  6929. start: vbuffered.start(i),
  6930. end: vbuffered.end(i)
  6931. });
  6932. }
  6933. return this.bufferedInfo(buffered, pos, maxHoleDuration);
  6934. }
  6935. } catch (error) {
  6936. // this is to catch
  6937. // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
  6938. // This SourceBuffer has been removed from the parent media source
  6939. }
  6940. return {
  6941. len: 0,
  6942. start: pos,
  6943. end: pos,
  6944. nextStart: undefined
  6945. };
  6946. };
  6947. BufferHelper.bufferedInfo = function bufferedInfo(buffered, pos, maxHoleDuration) {
  6948. pos = Math.max(0, pos);
  6949. // sort on buffer.start/smaller end (IE does not always return sorted buffered range)
  6950. buffered.sort(function (a, b) {
  6951. var diff = a.start - b.start;
  6952. if (diff) {
  6953. return diff;
  6954. } else {
  6955. return b.end - a.end;
  6956. }
  6957. });
  6958. var buffered2 = [];
  6959. if (maxHoleDuration) {
  6960. // there might be some small holes between buffer time range
  6961. // consider that holes smaller than maxHoleDuration are irrelevant and build another
  6962. // buffer time range representations that discards those holes
  6963. for (var i = 0; i < buffered.length; i++) {
  6964. var buf2len = buffered2.length;
  6965. if (buf2len) {
  6966. var buf2end = buffered2[buf2len - 1].end;
  6967. // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)
  6968. if (buffered[i].start - buf2end < maxHoleDuration) {
  6969. // merge overlapping time ranges
  6970. // update lastRange.end only if smaller than item.end
  6971. // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)
  6972. // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])
  6973. if (buffered[i].end > buf2end) {
  6974. buffered2[buf2len - 1].end = buffered[i].end;
  6975. }
  6976. } else {
  6977. // big hole
  6978. buffered2.push(buffered[i]);
  6979. }
  6980. } else {
  6981. // first value
  6982. buffered2.push(buffered[i]);
  6983. }
  6984. }
  6985. } else {
  6986. buffered2 = buffered;
  6987. }
  6988. var bufferLen = 0;
  6989. // bufferStartNext can possibly be undefined based on the conditional logic below
  6990. var bufferStartNext;
  6991. // bufferStart and bufferEnd are buffer boundaries around current video position
  6992. var bufferStart = pos;
  6993. var bufferEnd = pos;
  6994. for (var _i = 0; _i < buffered2.length; _i++) {
  6995. var start = buffered2[_i].start;
  6996. var end = buffered2[_i].end;
  6997. // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));
  6998. if (pos + maxHoleDuration >= start && pos < end) {
  6999. // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
  7000. bufferStart = start;
  7001. bufferEnd = end;
  7002. bufferLen = bufferEnd - pos;
  7003. } else if (pos + maxHoleDuration < start) {
  7004. bufferStartNext = start;
  7005. break;
  7006. }
  7007. }
  7008. return {
  7009. len: bufferLen,
  7010. start: bufferStart || 0,
  7011. end: bufferEnd || 0,
  7012. nextStart: bufferStartNext
  7013. };
  7014. }
  7015. /**
  7016. * Safe method to get buffered property.
  7017. * SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource
  7018. */;
  7019. BufferHelper.getBuffered = function getBuffered(media) {
  7020. try {
  7021. return media.buffered;
  7022. } catch (e) {
  7023. logger.log('failed to get media.buffered', e);
  7024. return noopBuffered;
  7025. }
  7026. };
  7027. return BufferHelper;
  7028. }();
  7029. var BufferOperationQueue = /*#__PURE__*/function () {
  7030. function BufferOperationQueue(sourceBufferReference) {
  7031. this.buffers = void 0;
  7032. this.queues = {
  7033. video: [],
  7034. audio: [],
  7035. audiovideo: []
  7036. };
  7037. this.buffers = sourceBufferReference;
  7038. }
  7039. var _proto = BufferOperationQueue.prototype;
  7040. _proto.append = function append(operation, type, pending) {
  7041. var queue = this.queues[type];
  7042. queue.push(operation);
  7043. if (queue.length === 1 && !pending) {
  7044. this.executeNext(type);
  7045. }
  7046. };
  7047. _proto.insertAbort = function insertAbort(operation, type) {
  7048. var queue = this.queues[type];
  7049. queue.unshift(operation);
  7050. this.executeNext(type);
  7051. };
  7052. _proto.appendBlocker = function appendBlocker(type) {
  7053. var execute;
  7054. var promise = new Promise(function (resolve) {
  7055. execute = resolve;
  7056. });
  7057. var operation = {
  7058. execute: execute,
  7059. onStart: function onStart() {},
  7060. onComplete: function onComplete() {},
  7061. onError: function onError() {}
  7062. };
  7063. this.append(operation, type);
  7064. return promise;
  7065. };
  7066. _proto.executeNext = function executeNext(type) {
  7067. var queue = this.queues[type];
  7068. if (queue.length) {
  7069. var operation = queue[0];
  7070. try {
  7071. // Operations are expected to result in an 'updateend' event being fired. If not, the queue will lock. Operations
  7072. // which do not end with this event must call _onSBUpdateEnd manually
  7073. operation.execute();
  7074. } catch (error) {
  7075. logger.warn("[buffer-operation-queue]: Exception executing \"" + type + "\" SourceBuffer operation: " + error);
  7076. operation.onError(error);
  7077. // Only shift the current operation off, otherwise the updateend handler will do this for us
  7078. var sb = this.buffers[type];
  7079. if (!(sb != null && sb.updating)) {
  7080. this.shiftAndExecuteNext(type);
  7081. }
  7082. }
  7083. }
  7084. };
  7085. _proto.shiftAndExecuteNext = function shiftAndExecuteNext(type) {
  7086. this.queues[type].shift();
  7087. this.executeNext(type);
  7088. };
  7089. _proto.current = function current(type) {
  7090. return this.queues[type][0];
  7091. };
  7092. return BufferOperationQueue;
  7093. }();
  7094. var VIDEO_CODEC_PROFILE_REPLACE = /(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;
  7095. var BufferController = /*#__PURE__*/function () {
  7096. function BufferController(hls) {
  7097. var _this = this;
  7098. // The level details used to determine duration, target-duration and live
  7099. this.details = null;
  7100. // cache the self generated object url to detect hijack of video tag
  7101. this._objectUrl = null;
  7102. // A queue of buffer operations which require the SourceBuffer to not be updating upon execution
  7103. this.operationQueue = void 0;
  7104. // References to event listeners for each SourceBuffer, so that they can be referenced for event removal
  7105. this.listeners = void 0;
  7106. this.hls = void 0;
  7107. // The number of BUFFER_CODEC events received before any sourceBuffers are created
  7108. this.bufferCodecEventsExpected = 0;
  7109. // The total number of BUFFER_CODEC events received
  7110. this._bufferCodecEventsTotal = 0;
  7111. // A reference to the attached media element
  7112. this.media = null;
  7113. // A reference to the active media source
  7114. this.mediaSource = null;
  7115. // Last MP3 audio chunk appended
  7116. this.lastMpegAudioChunk = null;
  7117. this.appendSource = void 0;
  7118. // counters
  7119. this.appendErrors = {
  7120. audio: 0,
  7121. video: 0,
  7122. audiovideo: 0
  7123. };
  7124. this.tracks = {};
  7125. this.pendingTracks = {};
  7126. this.sourceBuffer = void 0;
  7127. this.log = void 0;
  7128. this.warn = void 0;
  7129. this.error = void 0;
  7130. this._onEndStreaming = function (event) {
  7131. if (!_this.hls) {
  7132. return;
  7133. }
  7134. _this.hls.pauseBuffering();
  7135. };
  7136. this._onStartStreaming = function (event) {
  7137. if (!_this.hls) {
  7138. return;
  7139. }
  7140. _this.hls.resumeBuffering();
  7141. };
  7142. // Keep as arrow functions so that we can directly reference these functions directly as event listeners
  7143. this._onMediaSourceOpen = function () {
  7144. var media = _this.media,
  7145. mediaSource = _this.mediaSource;
  7146. _this.log('Media source opened');
  7147. if (media) {
  7148. media.removeEventListener('emptied', _this._onMediaEmptied);
  7149. _this.updateMediaElementDuration();
  7150. _this.hls.trigger(Events.MEDIA_ATTACHED, {
  7151. media: media,
  7152. mediaSource: mediaSource
  7153. });
  7154. }
  7155. if (mediaSource) {
  7156. // once received, don't listen anymore to sourceopen event
  7157. mediaSource.removeEventListener('sourceopen', _this._onMediaSourceOpen);
  7158. }
  7159. _this.checkPendingTracks();
  7160. };
  7161. this._onMediaSourceClose = function () {
  7162. _this.log('Media source closed');
  7163. };
  7164. this._onMediaSourceEnded = function () {
  7165. _this.log('Media source ended');
  7166. };
  7167. this._onMediaEmptied = function () {
  7168. var mediaSrc = _this.mediaSrc,
  7169. _objectUrl = _this._objectUrl;
  7170. if (mediaSrc !== _objectUrl) {
  7171. logger.error("Media element src was set while attaching MediaSource (" + _objectUrl + " > " + mediaSrc + ")");
  7172. }
  7173. };
  7174. this.hls = hls;
  7175. var logPrefix = '[buffer-controller]';
  7176. this.appendSource = isManagedMediaSource(getMediaSource(hls.config.preferManagedMediaSource));
  7177. this.log = logger.log.bind(logger, logPrefix);
  7178. this.warn = logger.warn.bind(logger, logPrefix);
  7179. this.error = logger.error.bind(logger, logPrefix);
  7180. this._initSourceBuffer();
  7181. this.registerListeners();
  7182. }
  7183. var _proto = BufferController.prototype;
  7184. _proto.hasSourceTypes = function hasSourceTypes() {
  7185. return this.getSourceBufferTypes().length > 0 || Object.keys(this.pendingTracks).length > 0;
  7186. };
  7187. _proto.destroy = function destroy() {
  7188. this.unregisterListeners();
  7189. this.details = null;
  7190. this.lastMpegAudioChunk = null;
  7191. // @ts-ignore
  7192. this.hls = null;
  7193. };
  7194. _proto.registerListeners = function registerListeners() {
  7195. var hls = this.hls;
  7196. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  7197. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  7198. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  7199. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  7200. hls.on(Events.BUFFER_RESET, this.onBufferReset, this);
  7201. hls.on(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  7202. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  7203. hls.on(Events.BUFFER_EOS, this.onBufferEos, this);
  7204. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  7205. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  7206. hls.on(Events.FRAG_PARSED, this.onFragParsed, this);
  7207. hls.on(Events.FRAG_CHANGED, this.onFragChanged, this);
  7208. };
  7209. _proto.unregisterListeners = function unregisterListeners() {
  7210. var hls = this.hls;
  7211. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  7212. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  7213. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  7214. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  7215. hls.off(Events.BUFFER_RESET, this.onBufferReset, this);
  7216. hls.off(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  7217. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  7218. hls.off(Events.BUFFER_EOS, this.onBufferEos, this);
  7219. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  7220. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  7221. hls.off(Events.FRAG_PARSED, this.onFragParsed, this);
  7222. hls.off(Events.FRAG_CHANGED, this.onFragChanged, this);
  7223. };
  7224. _proto._initSourceBuffer = function _initSourceBuffer() {
  7225. this.sourceBuffer = {};
  7226. this.operationQueue = new BufferOperationQueue(this.sourceBuffer);
  7227. this.listeners = {
  7228. audio: [],
  7229. video: [],
  7230. audiovideo: []
  7231. };
  7232. this.appendErrors = {
  7233. audio: 0,
  7234. video: 0,
  7235. audiovideo: 0
  7236. };
  7237. this.lastMpegAudioChunk = null;
  7238. };
  7239. _proto.onManifestLoading = function onManifestLoading() {
  7240. this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = 0;
  7241. this.details = null;
  7242. };
  7243. _proto.onManifestParsed = function onManifestParsed(event, data) {
  7244. // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller
  7245. // sourcebuffers will be created all at once when the expected nb of tracks will be reached
  7246. // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller
  7247. // it will contain the expected nb of source buffers, no need to compute it
  7248. var codecEvents = 2;
  7249. if (data.audio && !data.video || !data.altAudio || !false) {
  7250. codecEvents = 1;
  7251. }
  7252. this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = codecEvents;
  7253. this.log(this.bufferCodecEventsExpected + " bufferCodec event(s) expected");
  7254. };
  7255. _proto.onMediaAttaching = function onMediaAttaching(event, data) {
  7256. var media = this.media = data.media;
  7257. var MediaSource = getMediaSource(this.appendSource);
  7258. if (media && MediaSource) {
  7259. var _ms$constructor;
  7260. var ms = this.mediaSource = new MediaSource();
  7261. this.log("created media source: " + ((_ms$constructor = ms.constructor) == null ? void 0 : _ms$constructor.name));
  7262. // MediaSource listeners are arrow functions with a lexical scope, and do not need to be bound
  7263. ms.addEventListener('sourceopen', this._onMediaSourceOpen);
  7264. ms.addEventListener('sourceended', this._onMediaSourceEnded);
  7265. ms.addEventListener('sourceclose', this._onMediaSourceClose);
  7266. if (this.appendSource) {
  7267. ms.addEventListener('startstreaming', this._onStartStreaming);
  7268. ms.addEventListener('endstreaming', this._onEndStreaming);
  7269. }
  7270. // cache the locally generated object url
  7271. var objectUrl = this._objectUrl = self.URL.createObjectURL(ms);
  7272. // link video and media Source
  7273. if (this.appendSource) {
  7274. try {
  7275. media.removeAttribute('src');
  7276. // ManagedMediaSource will not open without disableRemotePlayback set to false or source alternatives
  7277. var MMS = self.ManagedMediaSource;
  7278. media.disableRemotePlayback = media.disableRemotePlayback || MMS && ms instanceof MMS;
  7279. removeSourceChildren(media);
  7280. addSource(media, objectUrl);
  7281. media.load();
  7282. } catch (error) {
  7283. media.src = objectUrl;
  7284. }
  7285. } else {
  7286. media.src = objectUrl;
  7287. }
  7288. media.addEventListener('emptied', this._onMediaEmptied);
  7289. }
  7290. };
  7291. _proto.onMediaDetaching = function onMediaDetaching() {
  7292. var media = this.media,
  7293. mediaSource = this.mediaSource,
  7294. _objectUrl = this._objectUrl;
  7295. if (mediaSource) {
  7296. this.log('media source detaching');
  7297. if (mediaSource.readyState === 'open') {
  7298. try {
  7299. // endOfStream could trigger exception if any sourcebuffer is in updating state
  7300. // we don't really care about checking sourcebuffer state here,
  7301. // as we are anyway detaching the MediaSource
  7302. // let's just avoid this exception to propagate
  7303. mediaSource.endOfStream();
  7304. } catch (err) {
  7305. this.warn("onMediaDetaching: " + err.message + " while calling endOfStream");
  7306. }
  7307. }
  7308. // Clean up the SourceBuffers by invoking onBufferReset
  7309. this.onBufferReset();
  7310. mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);
  7311. mediaSource.removeEventListener('sourceended', this._onMediaSourceEnded);
  7312. mediaSource.removeEventListener('sourceclose', this._onMediaSourceClose);
  7313. if (this.appendSource) {
  7314. mediaSource.removeEventListener('startstreaming', this._onStartStreaming);
  7315. mediaSource.removeEventListener('endstreaming', this._onEndStreaming);
  7316. }
  7317. // Detach properly the MediaSource from the HTMLMediaElement as
  7318. // suggested in https://github.com/w3c/media-source/issues/53.
  7319. if (media) {
  7320. media.removeEventListener('emptied', this._onMediaEmptied);
  7321. if (_objectUrl) {
  7322. self.URL.revokeObjectURL(_objectUrl);
  7323. }
  7324. // clean up video tag src only if it's our own url. some external libraries might
  7325. // hijack the video tag and change its 'src' without destroying the Hls instance first
  7326. if (this.mediaSrc === _objectUrl) {
  7327. media.removeAttribute('src');
  7328. if (this.appendSource) {
  7329. removeSourceChildren(media);
  7330. }
  7331. media.load();
  7332. } else {
  7333. this.warn('media|source.src was changed by a third party - skip cleanup');
  7334. }
  7335. }
  7336. this.mediaSource = null;
  7337. this.media = null;
  7338. this._objectUrl = null;
  7339. this.bufferCodecEventsExpected = this._bufferCodecEventsTotal;
  7340. this.pendingTracks = {};
  7341. this.tracks = {};
  7342. }
  7343. this.hls.trigger(Events.MEDIA_DETACHED, undefined);
  7344. };
  7345. _proto.onBufferReset = function onBufferReset() {
  7346. var _this2 = this;
  7347. this.getSourceBufferTypes().forEach(function (type) {
  7348. _this2.resetBuffer(type);
  7349. });
  7350. this._initSourceBuffer();
  7351. };
  7352. _proto.resetBuffer = function resetBuffer(type) {
  7353. var sb = this.sourceBuffer[type];
  7354. try {
  7355. if (sb) {
  7356. var _this$mediaSource;
  7357. this.removeBufferListeners(type);
  7358. // Synchronously remove the SB from the map before the next call in order to prevent an async function from
  7359. // accessing it
  7360. this.sourceBuffer[type] = undefined;
  7361. if ((_this$mediaSource = this.mediaSource) != null && _this$mediaSource.sourceBuffers.length) {
  7362. this.mediaSource.removeSourceBuffer(sb);
  7363. }
  7364. }
  7365. } catch (err) {
  7366. this.warn("onBufferReset " + type, err);
  7367. }
  7368. };
  7369. _proto.onBufferCodecs = function onBufferCodecs(event, data) {
  7370. var _this3 = this;
  7371. var sourceBufferCount = this.getSourceBufferTypes().length;
  7372. var trackNames = Object.keys(data);
  7373. trackNames.forEach(function (trackName) {
  7374. if (sourceBufferCount) {
  7375. // check if SourceBuffer codec needs to change
  7376. var track = _this3.tracks[trackName];
  7377. if (track && typeof track.buffer.changeType === 'function') {
  7378. var _trackCodec;
  7379. var _data$trackName = data[trackName],
  7380. id = _data$trackName.id,
  7381. codec = _data$trackName.codec,
  7382. levelCodec = _data$trackName.levelCodec,
  7383. container = _data$trackName.container,
  7384. metadata = _data$trackName.metadata;
  7385. var currentCodecFull = pickMostCompleteCodecName(track.codec, track.levelCodec);
  7386. var currentCodec = currentCodecFull == null ? void 0 : currentCodecFull.replace(VIDEO_CODEC_PROFILE_REPLACE, '$1');
  7387. var trackCodec = pickMostCompleteCodecName(codec, levelCodec);
  7388. var nextCodec = (_trackCodec = trackCodec) == null ? void 0 : _trackCodec.replace(VIDEO_CODEC_PROFILE_REPLACE, '$1');
  7389. if (trackCodec && currentCodec !== nextCodec) {
  7390. if (trackName.slice(0, 5) === 'audio') {
  7391. trackCodec = getCodecCompatibleName(trackCodec, _this3.appendSource);
  7392. }
  7393. var mimeType = container + ";codecs=" + trackCodec;
  7394. _this3.appendChangeType(trackName, mimeType);
  7395. _this3.log("switching codec " + currentCodecFull + " to " + trackCodec);
  7396. _this3.tracks[trackName] = {
  7397. buffer: track.buffer,
  7398. codec: codec,
  7399. container: container,
  7400. levelCodec: levelCodec,
  7401. metadata: metadata,
  7402. id: id
  7403. };
  7404. }
  7405. }
  7406. } else {
  7407. // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks
  7408. _this3.pendingTracks[trackName] = data[trackName];
  7409. }
  7410. });
  7411. // if sourcebuffers already created, do nothing ...
  7412. if (sourceBufferCount) {
  7413. return;
  7414. }
  7415. var bufferCodecEventsExpected = Math.max(this.bufferCodecEventsExpected - 1, 0);
  7416. if (this.bufferCodecEventsExpected !== bufferCodecEventsExpected) {
  7417. this.log(bufferCodecEventsExpected + " bufferCodec event(s) expected " + trackNames.join(','));
  7418. this.bufferCodecEventsExpected = bufferCodecEventsExpected;
  7419. }
  7420. if (this.mediaSource && this.mediaSource.readyState === 'open') {
  7421. this.checkPendingTracks();
  7422. }
  7423. };
  7424. _proto.appendChangeType = function appendChangeType(type, mimeType) {
  7425. var _this4 = this;
  7426. var operationQueue = this.operationQueue;
  7427. var operation = {
  7428. execute: function execute() {
  7429. var sb = _this4.sourceBuffer[type];
  7430. if (sb) {
  7431. _this4.log("changing " + type + " sourceBuffer type to " + mimeType);
  7432. sb.changeType(mimeType);
  7433. }
  7434. operationQueue.shiftAndExecuteNext(type);
  7435. },
  7436. onStart: function onStart() {},
  7437. onComplete: function onComplete() {},
  7438. onError: function onError(error) {
  7439. _this4.warn("Failed to change " + type + " SourceBuffer type", error);
  7440. }
  7441. };
  7442. operationQueue.append(operation, type, !!this.pendingTracks[type]);
  7443. };
  7444. _proto.onBufferAppending = function onBufferAppending(event, eventData) {
  7445. var _this5 = this;
  7446. var hls = this.hls,
  7447. operationQueue = this.operationQueue,
  7448. tracks = this.tracks;
  7449. var data = eventData.data,
  7450. type = eventData.type,
  7451. frag = eventData.frag,
  7452. part = eventData.part,
  7453. chunkMeta = eventData.chunkMeta;
  7454. var chunkStats = chunkMeta.buffering[type];
  7455. var bufferAppendingStart = self.performance.now();
  7456. chunkStats.start = bufferAppendingStart;
  7457. var fragBuffering = frag.stats.buffering;
  7458. var partBuffering = part ? part.stats.buffering : null;
  7459. if (fragBuffering.start === 0) {
  7460. fragBuffering.start = bufferAppendingStart;
  7461. }
  7462. if (partBuffering && partBuffering.start === 0) {
  7463. partBuffering.start = bufferAppendingStart;
  7464. }
  7465. // TODO: Only update timestampOffset when audio/mpeg fragment or part is not contiguous with previously appended
  7466. // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)
  7467. // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`
  7468. // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos).
  7469. // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486
  7470. var audioTrack = tracks.audio;
  7471. var checkTimestampOffset = false;
  7472. if (type === 'audio' && (audioTrack == null ? void 0 : audioTrack.container) === 'audio/mpeg') {
  7473. checkTimestampOffset = !this.lastMpegAudioChunk || chunkMeta.id === 1 || this.lastMpegAudioChunk.sn !== chunkMeta.sn;
  7474. this.lastMpegAudioChunk = chunkMeta;
  7475. }
  7476. var fragStart = frag.start;
  7477. var operation = {
  7478. execute: function execute() {
  7479. chunkStats.executeStart = self.performance.now();
  7480. if (checkTimestampOffset) {
  7481. var sb = _this5.sourceBuffer[type];
  7482. if (sb) {
  7483. var delta = fragStart - sb.timestampOffset;
  7484. if (Math.abs(delta) >= 0.1) {
  7485. _this5.log("Updating audio SourceBuffer timestampOffset to " + fragStart + " (delta: " + delta + ") sn: " + frag.sn + ")");
  7486. sb.timestampOffset = fragStart;
  7487. }
  7488. }
  7489. }
  7490. _this5.appendExecutor(data, type);
  7491. },
  7492. onStart: function onStart() {
  7493. // logger.debug(`[buffer-controller]: ${type} SourceBuffer updatestart`);
  7494. },
  7495. onComplete: function onComplete() {
  7496. // logger.debug(`[buffer-controller]: ${type} SourceBuffer updateend`);
  7497. var end = self.performance.now();
  7498. chunkStats.executeEnd = chunkStats.end = end;
  7499. if (fragBuffering.first === 0) {
  7500. fragBuffering.first = end;
  7501. }
  7502. if (partBuffering && partBuffering.first === 0) {
  7503. partBuffering.first = end;
  7504. }
  7505. var sourceBuffer = _this5.sourceBuffer;
  7506. var timeRanges = {};
  7507. for (var _type in sourceBuffer) {
  7508. timeRanges[_type] = BufferHelper.getBuffered(sourceBuffer[_type]);
  7509. }
  7510. _this5.appendErrors[type] = 0;
  7511. if (type === 'audio' || type === 'video') {
  7512. _this5.appendErrors.audiovideo = 0;
  7513. } else {
  7514. _this5.appendErrors.audio = 0;
  7515. _this5.appendErrors.video = 0;
  7516. }
  7517. _this5.hls.trigger(Events.BUFFER_APPENDED, {
  7518. type: type,
  7519. frag: frag,
  7520. part: part,
  7521. chunkMeta: chunkMeta,
  7522. parent: frag.type,
  7523. timeRanges: timeRanges
  7524. });
  7525. },
  7526. onError: function onError(error) {
  7527. // in case any error occured while appending, put back segment in segments table
  7528. var event = {
  7529. type: ErrorTypes.MEDIA_ERROR,
  7530. parent: frag.type,
  7531. details: ErrorDetails.BUFFER_APPEND_ERROR,
  7532. sourceBufferName: type,
  7533. frag: frag,
  7534. part: part,
  7535. chunkMeta: chunkMeta,
  7536. error: error,
  7537. err: error,
  7538. fatal: false
  7539. };
  7540. if (error.code === DOMException.QUOTA_EXCEEDED_ERR) {
  7541. // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
  7542. // let's stop appending any segments, and report BUFFER_FULL_ERROR error
  7543. event.details = ErrorDetails.BUFFER_FULL_ERROR;
  7544. } else {
  7545. var appendErrorCount = ++_this5.appendErrors[type];
  7546. event.details = ErrorDetails.BUFFER_APPEND_ERROR;
  7547. /* with UHD content, we could get loop of quota exceeded error until
  7548. browser is able to evict some data from sourcebuffer. Retrying can help recover.
  7549. */
  7550. _this5.warn("Failed " + appendErrorCount + "/" + hls.config.appendErrorMaxRetry + " times to append segment in \"" + type + "\" sourceBuffer");
  7551. if (appendErrorCount >= hls.config.appendErrorMaxRetry) {
  7552. event.fatal = true;
  7553. }
  7554. }
  7555. hls.trigger(Events.ERROR, event);
  7556. }
  7557. };
  7558. operationQueue.append(operation, type, !!this.pendingTracks[type]);
  7559. };
  7560. _proto.onBufferFlushing = function onBufferFlushing(event, data) {
  7561. var _this6 = this;
  7562. var operationQueue = this.operationQueue;
  7563. var flushOperation = function flushOperation(type) {
  7564. return {
  7565. execute: _this6.removeExecutor.bind(_this6, type, data.startOffset, data.endOffset),
  7566. onStart: function onStart() {
  7567. // logger.debug(`[buffer-controller]: Started flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
  7568. },
  7569. onComplete: function onComplete() {
  7570. // logger.debug(`[buffer-controller]: Finished flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
  7571. _this6.hls.trigger(Events.BUFFER_FLUSHED, {
  7572. type: type
  7573. });
  7574. },
  7575. onError: function onError(error) {
  7576. _this6.warn("Failed to remove from " + type + " SourceBuffer", error);
  7577. }
  7578. };
  7579. };
  7580. if (data.type) {
  7581. operationQueue.append(flushOperation(data.type), data.type);
  7582. } else {
  7583. this.getSourceBufferTypes().forEach(function (type) {
  7584. operationQueue.append(flushOperation(type), type);
  7585. });
  7586. }
  7587. };
  7588. _proto.onFragParsed = function onFragParsed(event, data) {
  7589. var _this7 = this;
  7590. var frag = data.frag,
  7591. part = data.part;
  7592. var buffersAppendedTo = [];
  7593. var elementaryStreams = part ? part.elementaryStreams : frag.elementaryStreams;
  7594. if (elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO]) {
  7595. buffersAppendedTo.push('audiovideo');
  7596. } else {
  7597. if (elementaryStreams[ElementaryStreamTypes.AUDIO]) {
  7598. buffersAppendedTo.push('audio');
  7599. }
  7600. if (elementaryStreams[ElementaryStreamTypes.VIDEO]) {
  7601. buffersAppendedTo.push('video');
  7602. }
  7603. }
  7604. var onUnblocked = function onUnblocked() {
  7605. var now = self.performance.now();
  7606. frag.stats.buffering.end = now;
  7607. if (part) {
  7608. part.stats.buffering.end = now;
  7609. }
  7610. var stats = part ? part.stats : frag.stats;
  7611. _this7.hls.trigger(Events.FRAG_BUFFERED, {
  7612. frag: frag,
  7613. part: part,
  7614. stats: stats,
  7615. id: frag.type
  7616. });
  7617. };
  7618. if (buffersAppendedTo.length === 0) {
  7619. this.warn("Fragments must have at least one ElementaryStreamType set. type: " + frag.type + " level: " + frag.level + " sn: " + frag.sn);
  7620. }
  7621. this.blockBuffers(onUnblocked, buffersAppendedTo);
  7622. };
  7623. _proto.onFragChanged = function onFragChanged(event, data) {
  7624. this.trimBuffers();
  7625. }
  7626. // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()
  7627. // an undefined data.type will mark all buffers as EOS.
  7628. ;
  7629. _proto.onBufferEos = function onBufferEos(event, data) {
  7630. var _this8 = this;
  7631. var ended = this.getSourceBufferTypes().reduce(function (acc, type) {
  7632. var sb = _this8.sourceBuffer[type];
  7633. if (sb && (!data.type || data.type === type)) {
  7634. sb.ending = true;
  7635. if (!sb.ended) {
  7636. sb.ended = true;
  7637. _this8.log(type + " sourceBuffer now EOS");
  7638. }
  7639. }
  7640. return acc && !!(!sb || sb.ended);
  7641. }, true);
  7642. if (ended) {
  7643. this.log("Queueing mediaSource.endOfStream()");
  7644. this.blockBuffers(function () {
  7645. _this8.getSourceBufferTypes().forEach(function (type) {
  7646. var sb = _this8.sourceBuffer[type];
  7647. if (sb) {
  7648. sb.ending = false;
  7649. }
  7650. });
  7651. var mediaSource = _this8.mediaSource;
  7652. if (!mediaSource || mediaSource.readyState !== 'open') {
  7653. if (mediaSource) {
  7654. _this8.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: " + mediaSource.readyState);
  7655. }
  7656. return;
  7657. }
  7658. _this8.log("Calling mediaSource.endOfStream()");
  7659. // Allow this to throw and be caught by the enqueueing function
  7660. mediaSource.endOfStream();
  7661. });
  7662. }
  7663. };
  7664. _proto.onLevelUpdated = function onLevelUpdated(event, _ref) {
  7665. var details = _ref.details;
  7666. if (!details.fragments.length) {
  7667. return;
  7668. }
  7669. this.details = details;
  7670. if (this.getSourceBufferTypes().length) {
  7671. this.blockBuffers(this.updateMediaElementDuration.bind(this));
  7672. } else {
  7673. this.updateMediaElementDuration();
  7674. }
  7675. };
  7676. _proto.trimBuffers = function trimBuffers() {
  7677. var hls = this.hls,
  7678. details = this.details,
  7679. media = this.media;
  7680. if (!media || details === null) {
  7681. return;
  7682. }
  7683. var sourceBufferTypes = this.getSourceBufferTypes();
  7684. if (!sourceBufferTypes.length) {
  7685. return;
  7686. }
  7687. var config = hls.config;
  7688. var currentTime = media.currentTime;
  7689. var targetDuration = details.levelTargetDuration;
  7690. // Support for deprecated liveBackBufferLength
  7691. var backBufferLength = details.live && config.liveBackBufferLength !== null ? config.liveBackBufferLength : config.backBufferLength;
  7692. if (isFiniteNumber(backBufferLength) && backBufferLength > 0) {
  7693. var maxBackBufferLength = Math.max(backBufferLength, targetDuration);
  7694. var targetBackBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration - maxBackBufferLength;
  7695. this.flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition);
  7696. }
  7697. if (isFiniteNumber(config.frontBufferFlushThreshold) && config.frontBufferFlushThreshold > 0) {
  7698. var frontBufferLength = Math.max(config.maxBufferLength, config.frontBufferFlushThreshold);
  7699. var maxFrontBufferLength = Math.max(frontBufferLength, targetDuration);
  7700. var targetFrontBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration + maxFrontBufferLength;
  7701. this.flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition);
  7702. }
  7703. };
  7704. _proto.flushBackBuffer = function flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition) {
  7705. var _this9 = this;
  7706. var details = this.details,
  7707. sourceBuffer = this.sourceBuffer;
  7708. var sourceBufferTypes = this.getSourceBufferTypes();
  7709. sourceBufferTypes.forEach(function (type) {
  7710. var sb = sourceBuffer[type];
  7711. if (sb) {
  7712. var buffered = BufferHelper.getBuffered(sb);
  7713. // when target buffer start exceeds actual buffer start
  7714. if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
  7715. _this9.hls.trigger(Events.BACK_BUFFER_REACHED, {
  7716. bufferEnd: targetBackBufferPosition
  7717. });
  7718. // Support for deprecated event:
  7719. if (details != null && details.live) {
  7720. _this9.hls.trigger(Events.LIVE_BACK_BUFFER_REACHED, {
  7721. bufferEnd: targetBackBufferPosition
  7722. });
  7723. } else if (sb.ended && buffered.end(buffered.length - 1) - currentTime < targetDuration * 2) {
  7724. _this9.log("Cannot flush " + type + " back buffer while SourceBuffer is in ended state");
  7725. return;
  7726. }
  7727. _this9.hls.trigger(Events.BUFFER_FLUSHING, {
  7728. startOffset: 0,
  7729. endOffset: targetBackBufferPosition,
  7730. type: type
  7731. });
  7732. }
  7733. }
  7734. });
  7735. };
  7736. _proto.flushFrontBuffer = function flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition) {
  7737. var _this10 = this;
  7738. var sourceBuffer = this.sourceBuffer;
  7739. var sourceBufferTypes = this.getSourceBufferTypes();
  7740. sourceBufferTypes.forEach(function (type) {
  7741. var sb = sourceBuffer[type];
  7742. if (sb) {
  7743. var buffered = BufferHelper.getBuffered(sb);
  7744. var numBufferedRanges = buffered.length;
  7745. // The buffer is either empty or contiguous
  7746. if (numBufferedRanges < 2) {
  7747. return;
  7748. }
  7749. var bufferStart = buffered.start(numBufferedRanges - 1);
  7750. var bufferEnd = buffered.end(numBufferedRanges - 1);
  7751. // No flush if we can tolerate the current buffer length or the current buffer range we would flush is contiguous with current position
  7752. if (targetFrontBufferPosition > bufferStart || currentTime >= bufferStart && currentTime <= bufferEnd) {
  7753. return;
  7754. } else if (sb.ended && currentTime - bufferEnd < 2 * targetDuration) {
  7755. _this10.log("Cannot flush " + type + " front buffer while SourceBuffer is in ended state");
  7756. return;
  7757. }
  7758. _this10.hls.trigger(Events.BUFFER_FLUSHING, {
  7759. startOffset: bufferStart,
  7760. endOffset: Infinity,
  7761. type: type
  7762. });
  7763. }
  7764. });
  7765. }
  7766. /**
  7767. * Update Media Source duration to current level duration or override to Infinity if configuration parameter
  7768. * 'liveDurationInfinity` is set to `true`
  7769. * More details: https://github.com/video-dev/hls.js/issues/355
  7770. */;
  7771. _proto.updateMediaElementDuration = function updateMediaElementDuration() {
  7772. if (!this.details || !this.media || !this.mediaSource || this.mediaSource.readyState !== 'open') {
  7773. return;
  7774. }
  7775. var details = this.details,
  7776. hls = this.hls,
  7777. media = this.media,
  7778. mediaSource = this.mediaSource;
  7779. var levelDuration = details.fragments[0].start + details.totalduration;
  7780. var mediaDuration = media.duration;
  7781. var msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : 0;
  7782. if (details.live && hls.config.liveDurationInfinity) {
  7783. // Override duration to Infinity
  7784. mediaSource.duration = Infinity;
  7785. this.updateSeekableRange(details);
  7786. } else if (levelDuration > msDuration && levelDuration > mediaDuration || !isFiniteNumber(mediaDuration)) {
  7787. // levelDuration was the last value we set.
  7788. // not using mediaSource.duration as the browser may tweak this value
  7789. // only update Media Source duration if its value increase, this is to avoid
  7790. // flushing already buffered portion when switching between quality level
  7791. this.log("Updating Media Source duration to " + levelDuration.toFixed(3));
  7792. mediaSource.duration = levelDuration;
  7793. }
  7794. };
  7795. _proto.updateSeekableRange = function updateSeekableRange(levelDetails) {
  7796. var mediaSource = this.mediaSource;
  7797. var fragments = levelDetails.fragments;
  7798. var len = fragments.length;
  7799. if (len && levelDetails.live && mediaSource != null && mediaSource.setLiveSeekableRange) {
  7800. var start = Math.max(0, fragments[0].start);
  7801. var end = Math.max(start, start + levelDetails.totalduration);
  7802. this.log("Media Source duration is set to " + mediaSource.duration + ". Setting seekable range to " + start + "-" + end + ".");
  7803. mediaSource.setLiveSeekableRange(start, end);
  7804. }
  7805. };
  7806. _proto.checkPendingTracks = function checkPendingTracks() {
  7807. var bufferCodecEventsExpected = this.bufferCodecEventsExpected,
  7808. operationQueue = this.operationQueue,
  7809. pendingTracks = this.pendingTracks;
  7810. // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.
  7811. // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after
  7812. // data has been appended to existing ones.
  7813. // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.
  7814. var pendingTracksCount = Object.keys(pendingTracks).length;
  7815. if (pendingTracksCount && (!bufferCodecEventsExpected || pendingTracksCount === 2 || 'audiovideo' in pendingTracks)) {
  7816. // ok, let's create them now !
  7817. this.createSourceBuffers(pendingTracks);
  7818. this.pendingTracks = {};
  7819. // append any pending segments now !
  7820. var buffers = this.getSourceBufferTypes();
  7821. if (buffers.length) {
  7822. this.hls.trigger(Events.BUFFER_CREATED, {
  7823. tracks: this.tracks
  7824. });
  7825. buffers.forEach(function (type) {
  7826. operationQueue.executeNext(type);
  7827. });
  7828. } else {
  7829. var error = new Error('could not create source buffer for media codec(s)');
  7830. this.hls.trigger(Events.ERROR, {
  7831. type: ErrorTypes.MEDIA_ERROR,
  7832. details: ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,
  7833. fatal: true,
  7834. error: error,
  7835. reason: error.message
  7836. });
  7837. }
  7838. }
  7839. };
  7840. _proto.createSourceBuffers = function createSourceBuffers(tracks) {
  7841. var _this11 = this;
  7842. var sourceBuffer = this.sourceBuffer,
  7843. mediaSource = this.mediaSource;
  7844. if (!mediaSource) {
  7845. throw Error('createSourceBuffers called when mediaSource was null');
  7846. }
  7847. var _loop = function _loop(trackName) {
  7848. if (!sourceBuffer[trackName]) {
  7849. var _track$levelCodec;
  7850. var track = tracks[trackName];
  7851. if (!track) {
  7852. throw Error("source buffer exists for track " + trackName + ", however track does not");
  7853. }
  7854. // use levelCodec as first priority unless it contains multiple comma-separated codec values
  7855. var codec = ((_track$levelCodec = track.levelCodec) == null ? void 0 : _track$levelCodec.indexOf(',')) === -1 ? track.levelCodec : track.codec;
  7856. if (codec) {
  7857. if (trackName.slice(0, 5) === 'audio') {
  7858. codec = getCodecCompatibleName(codec, _this11.appendSource);
  7859. }
  7860. }
  7861. var mimeType = track.container + ";codecs=" + codec;
  7862. _this11.log("creating sourceBuffer(" + mimeType + ")");
  7863. try {
  7864. var sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);
  7865. var sbName = trackName;
  7866. _this11.addBufferListener(sbName, 'updatestart', _this11._onSBUpdateStart);
  7867. _this11.addBufferListener(sbName, 'updateend', _this11._onSBUpdateEnd);
  7868. _this11.addBufferListener(sbName, 'error', _this11._onSBUpdateError);
  7869. // ManagedSourceBuffer bufferedchange event
  7870. if (_this11.appendSource) {
  7871. _this11.addBufferListener(sbName, 'bufferedchange', function (type, event) {
  7872. // If media was ejected check for a change. Added ranges are redundant with changes on 'updateend' event.
  7873. var removedRanges = event.removedRanges;
  7874. if (removedRanges != null && removedRanges.length) {
  7875. _this11.hls.trigger(Events.BUFFER_FLUSHED, {
  7876. type: trackName
  7877. });
  7878. }
  7879. });
  7880. }
  7881. _this11.tracks[trackName] = {
  7882. buffer: sb,
  7883. codec: codec,
  7884. container: track.container,
  7885. levelCodec: track.levelCodec,
  7886. metadata: track.metadata,
  7887. id: track.id
  7888. };
  7889. } catch (err) {
  7890. _this11.error("error while trying to add sourceBuffer: " + err.message);
  7891. _this11.hls.trigger(Events.ERROR, {
  7892. type: ErrorTypes.MEDIA_ERROR,
  7893. details: ErrorDetails.BUFFER_ADD_CODEC_ERROR,
  7894. fatal: false,
  7895. error: err,
  7896. sourceBufferName: trackName,
  7897. mimeType: mimeType
  7898. });
  7899. }
  7900. }
  7901. };
  7902. for (var trackName in tracks) {
  7903. _loop(trackName);
  7904. }
  7905. };
  7906. _proto._onSBUpdateStart = function _onSBUpdateStart(type) {
  7907. var operationQueue = this.operationQueue;
  7908. var operation = operationQueue.current(type);
  7909. operation.onStart();
  7910. };
  7911. _proto._onSBUpdateEnd = function _onSBUpdateEnd(type) {
  7912. var _this$mediaSource2;
  7913. if (((_this$mediaSource2 = this.mediaSource) == null ? void 0 : _this$mediaSource2.readyState) === 'closed') {
  7914. this.resetBuffer(type);
  7915. return;
  7916. }
  7917. var operationQueue = this.operationQueue;
  7918. var operation = operationQueue.current(type);
  7919. operation.onComplete();
  7920. operationQueue.shiftAndExecuteNext(type);
  7921. };
  7922. _proto._onSBUpdateError = function _onSBUpdateError(type, event) {
  7923. var _this$mediaSource3;
  7924. var error = new Error(type + " SourceBuffer error. MediaSource readyState: " + ((_this$mediaSource3 = this.mediaSource) == null ? void 0 : _this$mediaSource3.readyState));
  7925. this.error("" + error, event);
  7926. // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
  7927. // SourceBuffer errors are not necessarily fatal; if so, the HTMLMediaElement will fire an error event
  7928. this.hls.trigger(Events.ERROR, {
  7929. type: ErrorTypes.MEDIA_ERROR,
  7930. details: ErrorDetails.BUFFER_APPENDING_ERROR,
  7931. sourceBufferName: type,
  7932. error: error,
  7933. fatal: false
  7934. });
  7935. // updateend is always fired after error, so we'll allow that to shift the current operation off of the queue
  7936. var operation = this.operationQueue.current(type);
  7937. if (operation) {
  7938. operation.onError(error);
  7939. }
  7940. }
  7941. // This method must result in an updateend event; if remove is not called, _onSBUpdateEnd must be called manually
  7942. ;
  7943. _proto.removeExecutor = function removeExecutor(type, startOffset, endOffset) {
  7944. var media = this.media,
  7945. mediaSource = this.mediaSource,
  7946. operationQueue = this.operationQueue,
  7947. sourceBuffer = this.sourceBuffer;
  7948. var sb = sourceBuffer[type];
  7949. if (!media || !mediaSource || !sb) {
  7950. this.warn("Attempting to remove from the " + type + " SourceBuffer, but it does not exist");
  7951. operationQueue.shiftAndExecuteNext(type);
  7952. return;
  7953. }
  7954. var mediaDuration = isFiniteNumber(media.duration) ? media.duration : Infinity;
  7955. var msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : Infinity;
  7956. var removeStart = Math.max(0, startOffset);
  7957. var removeEnd = Math.min(endOffset, mediaDuration, msDuration);
  7958. if (removeEnd > removeStart && (!sb.ending || sb.ended)) {
  7959. sb.ended = false;
  7960. this.log("Removing [" + removeStart + "," + removeEnd + "] from the " + type + " SourceBuffer");
  7961. sb.remove(removeStart, removeEnd);
  7962. } else {
  7963. // Cycle the queue
  7964. operationQueue.shiftAndExecuteNext(type);
  7965. }
  7966. }
  7967. // This method must result in an updateend event; if append is not called, _onSBUpdateEnd must be called manually
  7968. ;
  7969. _proto.appendExecutor = function appendExecutor(data, type) {
  7970. var sb = this.sourceBuffer[type];
  7971. if (!sb) {
  7972. if (!this.pendingTracks[type]) {
  7973. throw new Error("Attempting to append to the " + type + " SourceBuffer, but it does not exist");
  7974. }
  7975. return;
  7976. }
  7977. sb.ended = false;
  7978. sb.appendBuffer(data);
  7979. }
  7980. // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises
  7981. // resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue
  7982. // upon completion, since we already do it here
  7983. ;
  7984. _proto.blockBuffers = function blockBuffers(onUnblocked, buffers) {
  7985. var _this12 = this;
  7986. if (buffers === void 0) {
  7987. buffers = this.getSourceBufferTypes();
  7988. }
  7989. if (!buffers.length) {
  7990. this.log('Blocking operation requested, but no SourceBuffers exist');
  7991. Promise.resolve().then(onUnblocked);
  7992. return;
  7993. }
  7994. var operationQueue = this.operationQueue;
  7995. // logger.debug(`[buffer-controller]: Blocking ${buffers} SourceBuffer`);
  7996. var blockingOperations = buffers.map(function (type) {
  7997. return operationQueue.appendBlocker(type);
  7998. });
  7999. Promise.all(blockingOperations).then(function () {
  8000. // logger.debug(`[buffer-controller]: Blocking operation resolved; unblocking ${buffers} SourceBuffer`);
  8001. onUnblocked();
  8002. buffers.forEach(function (type) {
  8003. var sb = _this12.sourceBuffer[type];
  8004. // Only cycle the queue if the SB is not updating. There's a bug in Chrome which sets the SB updating flag to
  8005. // true when changing the MediaSource duration (https://bugs.chromium.org/p/chromium/issues/detail?id=959359&can=2&q=mediasource%20duration)
  8006. // While this is a workaround, it's probably useful to have around
  8007. if (!(sb != null && sb.updating)) {
  8008. operationQueue.shiftAndExecuteNext(type);
  8009. }
  8010. });
  8011. });
  8012. };
  8013. _proto.getSourceBufferTypes = function getSourceBufferTypes() {
  8014. return Object.keys(this.sourceBuffer);
  8015. };
  8016. _proto.addBufferListener = function addBufferListener(type, event, fn) {
  8017. var buffer = this.sourceBuffer[type];
  8018. if (!buffer) {
  8019. return;
  8020. }
  8021. var listener = fn.bind(this, type);
  8022. this.listeners[type].push({
  8023. event: event,
  8024. listener: listener
  8025. });
  8026. buffer.addEventListener(event, listener);
  8027. };
  8028. _proto.removeBufferListeners = function removeBufferListeners(type) {
  8029. var buffer = this.sourceBuffer[type];
  8030. if (!buffer) {
  8031. return;
  8032. }
  8033. this.listeners[type].forEach(function (l) {
  8034. buffer.removeEventListener(l.event, l.listener);
  8035. });
  8036. };
  8037. _createClass(BufferController, [{
  8038. key: "mediaSrc",
  8039. get: function get() {
  8040. var _this$media;
  8041. var media = ((_this$media = this.media) == null ? void 0 : _this$media.firstChild) || this.media;
  8042. return media == null ? void 0 : media.src;
  8043. }
  8044. }]);
  8045. return BufferController;
  8046. }();
  8047. function removeSourceChildren(node) {
  8048. var sourceChildren = node.querySelectorAll('source');
  8049. [].slice.call(sourceChildren).forEach(function (source) {
  8050. node.removeChild(source);
  8051. });
  8052. }
  8053. function addSource(media, url) {
  8054. var source = self.document.createElement('source');
  8055. source.type = 'video/mp4';
  8056. source.src = url;
  8057. media.appendChild(source);
  8058. }
  8059. var CapLevelController = /*#__PURE__*/function () {
  8060. function CapLevelController(hls) {
  8061. this.hls = void 0;
  8062. this.autoLevelCapping = void 0;
  8063. this.firstLevel = void 0;
  8064. this.media = void 0;
  8065. this.restrictedLevels = void 0;
  8066. this.timer = void 0;
  8067. this.clientRect = void 0;
  8068. this.streamController = void 0;
  8069. this.hls = hls;
  8070. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  8071. this.firstLevel = -1;
  8072. this.media = null;
  8073. this.restrictedLevels = [];
  8074. this.timer = undefined;
  8075. this.clientRect = null;
  8076. this.registerListeners();
  8077. }
  8078. var _proto = CapLevelController.prototype;
  8079. _proto.setStreamController = function setStreamController(streamController) {
  8080. this.streamController = streamController;
  8081. };
  8082. _proto.destroy = function destroy() {
  8083. if (this.hls) {
  8084. this.unregisterListener();
  8085. }
  8086. if (this.timer) {
  8087. this.stopCapping();
  8088. }
  8089. this.media = null;
  8090. this.clientRect = null;
  8091. // @ts-ignore
  8092. this.hls = this.streamController = null;
  8093. };
  8094. _proto.registerListeners = function registerListeners() {
  8095. var hls = this.hls;
  8096. hls.on(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  8097. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  8098. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  8099. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  8100. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  8101. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  8102. };
  8103. _proto.unregisterListener = function unregisterListener() {
  8104. var hls = this.hls;
  8105. hls.off(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  8106. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  8107. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  8108. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  8109. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  8110. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  8111. };
  8112. _proto.onFpsDropLevelCapping = function onFpsDropLevelCapping(event, data) {
  8113. // Don't add a restricted level more than once
  8114. var level = this.hls.levels[data.droppedLevel];
  8115. if (this.isLevelAllowed(level)) {
  8116. this.restrictedLevels.push({
  8117. bitrate: level.bitrate,
  8118. height: level.height,
  8119. width: level.width
  8120. });
  8121. }
  8122. };
  8123. _proto.onMediaAttaching = function onMediaAttaching(event, data) {
  8124. this.media = data.media instanceof HTMLVideoElement ? data.media : null;
  8125. this.clientRect = null;
  8126. if (this.timer && this.hls.levels.length) {
  8127. this.detectPlayerSize();
  8128. }
  8129. };
  8130. _proto.onManifestParsed = function onManifestParsed(event, data) {
  8131. var hls = this.hls;
  8132. this.restrictedLevels = [];
  8133. this.firstLevel = data.firstLevel;
  8134. if (hls.config.capLevelToPlayerSize && data.video) {
  8135. // Start capping immediately if the manifest has signaled video codecs
  8136. this.startCapping();
  8137. }
  8138. };
  8139. _proto.onLevelsUpdated = function onLevelsUpdated(event, data) {
  8140. if (this.timer && isFiniteNumber(this.autoLevelCapping)) {
  8141. this.detectPlayerSize();
  8142. }
  8143. }
  8144. // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted
  8145. // to the first level
  8146. ;
  8147. _proto.onBufferCodecs = function onBufferCodecs(event, data) {
  8148. var hls = this.hls;
  8149. if (hls.config.capLevelToPlayerSize && data.video) {
  8150. // If the manifest did not signal a video codec capping has been deferred until we're certain video is present
  8151. this.startCapping();
  8152. }
  8153. };
  8154. _proto.onMediaDetaching = function onMediaDetaching() {
  8155. this.stopCapping();
  8156. };
  8157. _proto.detectPlayerSize = function detectPlayerSize() {
  8158. if (this.media) {
  8159. if (this.mediaHeight <= 0 || this.mediaWidth <= 0) {
  8160. this.clientRect = null;
  8161. return;
  8162. }
  8163. var levels = this.hls.levels;
  8164. if (levels.length) {
  8165. var hls = this.hls;
  8166. var maxLevel = this.getMaxLevel(levels.length - 1);
  8167. if (maxLevel !== this.autoLevelCapping) {
  8168. logger.log("Setting autoLevelCapping to " + maxLevel + ": " + levels[maxLevel].height + "p@" + levels[maxLevel].bitrate + " for media " + this.mediaWidth + "x" + this.mediaHeight);
  8169. }
  8170. hls.autoLevelCapping = maxLevel;
  8171. if (hls.autoLevelCapping > this.autoLevelCapping && this.streamController) {
  8172. // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch
  8173. // usually happen when the user go to the fullscreen mode.
  8174. this.streamController.nextLevelSwitch();
  8175. }
  8176. this.autoLevelCapping = hls.autoLevelCapping;
  8177. }
  8178. }
  8179. }
  8180. /*
  8181. * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
  8182. */;
  8183. _proto.getMaxLevel = function getMaxLevel(capLevelIndex) {
  8184. var _this = this;
  8185. var levels = this.hls.levels;
  8186. if (!levels.length) {
  8187. return -1;
  8188. }
  8189. var validLevels = levels.filter(function (level, index) {
  8190. return _this.isLevelAllowed(level) && index <= capLevelIndex;
  8191. });
  8192. this.clientRect = null;
  8193. return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
  8194. };
  8195. _proto.startCapping = function startCapping() {
  8196. if (this.timer) {
  8197. // Don't reset capping if started twice; this can happen if the manifest signals a video codec
  8198. return;
  8199. }
  8200. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  8201. self.clearInterval(this.timer);
  8202. this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1000);
  8203. this.detectPlayerSize();
  8204. };
  8205. _proto.stopCapping = function stopCapping() {
  8206. this.restrictedLevels = [];
  8207. this.firstLevel = -1;
  8208. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  8209. if (this.timer) {
  8210. self.clearInterval(this.timer);
  8211. this.timer = undefined;
  8212. }
  8213. };
  8214. _proto.getDimensions = function getDimensions() {
  8215. if (this.clientRect) {
  8216. return this.clientRect;
  8217. }
  8218. var media = this.media;
  8219. var boundsRect = {
  8220. width: 0,
  8221. height: 0
  8222. };
  8223. if (media) {
  8224. var clientRect = media.getBoundingClientRect();
  8225. boundsRect.width = clientRect.width;
  8226. boundsRect.height = clientRect.height;
  8227. if (!boundsRect.width && !boundsRect.height) {
  8228. // When the media element has no width or height (equivalent to not being in the DOM),
  8229. // then use its width and height attributes (media.width, media.height)
  8230. boundsRect.width = clientRect.right - clientRect.left || media.width || 0;
  8231. boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;
  8232. }
  8233. }
  8234. this.clientRect = boundsRect;
  8235. return boundsRect;
  8236. };
  8237. _proto.isLevelAllowed = function isLevelAllowed(level) {
  8238. var restrictedLevels = this.restrictedLevels;
  8239. return !restrictedLevels.some(function (restrictedLevel) {
  8240. return level.bitrate === restrictedLevel.bitrate && level.width === restrictedLevel.width && level.height === restrictedLevel.height;
  8241. });
  8242. };
  8243. CapLevelController.getMaxLevelByMediaSize = function getMaxLevelByMediaSize(levels, width, height) {
  8244. if (!(levels != null && levels.length)) {
  8245. return -1;
  8246. }
  8247. // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next
  8248. // to determine whether we've chosen the greatest bandwidth for the media's dimensions
  8249. var atGreatestBandwidth = function atGreatestBandwidth(curLevel, nextLevel) {
  8250. if (!nextLevel) {
  8251. return true;
  8252. }
  8253. return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
  8254. };
  8255. // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to
  8256. // the max level
  8257. var maxLevelIndex = levels.length - 1;
  8258. // Prevent changes in aspect-ratio from causing capping to toggle back and forth
  8259. var squareSize = Math.max(width, height);
  8260. for (var i = 0; i < levels.length; i += 1) {
  8261. var level = levels[i];
  8262. if ((level.width >= squareSize || level.height >= squareSize) && atGreatestBandwidth(level, levels[i + 1])) {
  8263. maxLevelIndex = i;
  8264. break;
  8265. }
  8266. }
  8267. return maxLevelIndex;
  8268. };
  8269. _createClass(CapLevelController, [{
  8270. key: "mediaWidth",
  8271. get: function get() {
  8272. return this.getDimensions().width * this.contentScaleFactor;
  8273. }
  8274. }, {
  8275. key: "mediaHeight",
  8276. get: function get() {
  8277. return this.getDimensions().height * this.contentScaleFactor;
  8278. }
  8279. }, {
  8280. key: "contentScaleFactor",
  8281. get: function get() {
  8282. var pixelRatio = 1;
  8283. if (!this.hls.config.ignoreDevicePixelRatio) {
  8284. try {
  8285. pixelRatio = self.devicePixelRatio;
  8286. } catch (e) {
  8287. /* no-op */
  8288. }
  8289. }
  8290. return pixelRatio;
  8291. }
  8292. }]);
  8293. return CapLevelController;
  8294. }();
  8295. var FPSController = /*#__PURE__*/function () {
  8296. function FPSController(hls) {
  8297. this.hls = void 0;
  8298. this.isVideoPlaybackQualityAvailable = false;
  8299. this.timer = void 0;
  8300. this.media = null;
  8301. this.lastTime = void 0;
  8302. this.lastDroppedFrames = 0;
  8303. this.lastDecodedFrames = 0;
  8304. // stream controller must be provided as a dependency!
  8305. this.streamController = void 0;
  8306. this.hls = hls;
  8307. this.registerListeners();
  8308. }
  8309. var _proto = FPSController.prototype;
  8310. _proto.setStreamController = function setStreamController(streamController) {
  8311. this.streamController = streamController;
  8312. };
  8313. _proto.registerListeners = function registerListeners() {
  8314. this.hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  8315. };
  8316. _proto.unregisterListeners = function unregisterListeners() {
  8317. this.hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  8318. };
  8319. _proto.destroy = function destroy() {
  8320. if (this.timer) {
  8321. clearInterval(this.timer);
  8322. }
  8323. this.unregisterListeners();
  8324. this.isVideoPlaybackQualityAvailable = false;
  8325. this.media = null;
  8326. };
  8327. _proto.onMediaAttaching = function onMediaAttaching(event, data) {
  8328. var config = this.hls.config;
  8329. if (config.capLevelOnFPSDrop) {
  8330. var media = data.media instanceof self.HTMLVideoElement ? data.media : null;
  8331. this.media = media;
  8332. if (media && typeof media.getVideoPlaybackQuality === 'function') {
  8333. this.isVideoPlaybackQualityAvailable = true;
  8334. }
  8335. self.clearInterval(this.timer);
  8336. this.timer = self.setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
  8337. }
  8338. };
  8339. _proto.checkFPS = function checkFPS(video, decodedFrames, droppedFrames) {
  8340. var currentTime = performance.now();
  8341. if (decodedFrames) {
  8342. if (this.lastTime) {
  8343. var currentPeriod = currentTime - this.lastTime;
  8344. var currentDropped = droppedFrames - this.lastDroppedFrames;
  8345. var currentDecoded = decodedFrames - this.lastDecodedFrames;
  8346. var droppedFPS = 1000 * currentDropped / currentPeriod;
  8347. var hls = this.hls;
  8348. hls.trigger(Events.FPS_DROP, {
  8349. currentDropped: currentDropped,
  8350. currentDecoded: currentDecoded,
  8351. totalDroppedFrames: droppedFrames
  8352. });
  8353. if (droppedFPS > 0) {
  8354. // logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));
  8355. if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
  8356. var currentLevel = hls.currentLevel;
  8357. logger.warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);
  8358. if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
  8359. currentLevel = currentLevel - 1;
  8360. hls.trigger(Events.FPS_DROP_LEVEL_CAPPING, {
  8361. level: currentLevel,
  8362. droppedLevel: hls.currentLevel
  8363. });
  8364. hls.autoLevelCapping = currentLevel;
  8365. this.streamController.nextLevelSwitch();
  8366. }
  8367. }
  8368. }
  8369. }
  8370. this.lastTime = currentTime;
  8371. this.lastDroppedFrames = droppedFrames;
  8372. this.lastDecodedFrames = decodedFrames;
  8373. }
  8374. };
  8375. _proto.checkFPSInterval = function checkFPSInterval() {
  8376. var video = this.media;
  8377. if (video) {
  8378. if (this.isVideoPlaybackQualityAvailable) {
  8379. var videoPlaybackQuality = video.getVideoPlaybackQuality();
  8380. this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
  8381. } else {
  8382. // HTMLVideoElement doesn't include the webkit types
  8383. this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
  8384. }
  8385. }
  8386. };
  8387. return FPSController;
  8388. }();
  8389. var PATHWAY_PENALTY_DURATION_MS = 300000;
  8390. var ContentSteeringController = /*#__PURE__*/function () {
  8391. function ContentSteeringController(hls) {
  8392. this.hls = void 0;
  8393. this.log = void 0;
  8394. this.loader = null;
  8395. this.uri = null;
  8396. this.pathwayId = '.';
  8397. this.pathwayPriority = null;
  8398. this.timeToLoad = 300;
  8399. this.reloadTimer = -1;
  8400. this.updated = 0;
  8401. this.started = false;
  8402. this.enabled = true;
  8403. this.levels = null;
  8404. this.audioTracks = null;
  8405. this.subtitleTracks = null;
  8406. this.penalizedPathways = {};
  8407. this.hls = hls;
  8408. this.log = logger.log.bind(logger, "[content-steering]:");
  8409. this.registerListeners();
  8410. }
  8411. var _proto = ContentSteeringController.prototype;
  8412. _proto.registerListeners = function registerListeners() {
  8413. var hls = this.hls;
  8414. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  8415. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  8416. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  8417. hls.on(Events.ERROR, this.onError, this);
  8418. };
  8419. _proto.unregisterListeners = function unregisterListeners() {
  8420. var hls = this.hls;
  8421. if (!hls) {
  8422. return;
  8423. }
  8424. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  8425. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  8426. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  8427. hls.off(Events.ERROR, this.onError, this);
  8428. };
  8429. _proto.startLoad = function startLoad() {
  8430. this.started = true;
  8431. this.clearTimeout();
  8432. if (this.enabled && this.uri) {
  8433. if (this.updated) {
  8434. var ttl = this.timeToLoad * 1000 - (performance.now() - this.updated);
  8435. if (ttl > 0) {
  8436. this.scheduleRefresh(this.uri, ttl);
  8437. return;
  8438. }
  8439. }
  8440. this.loadSteeringManifest(this.uri);
  8441. }
  8442. };
  8443. _proto.stopLoad = function stopLoad() {
  8444. this.started = false;
  8445. if (this.loader) {
  8446. this.loader.destroy();
  8447. this.loader = null;
  8448. }
  8449. this.clearTimeout();
  8450. };
  8451. _proto.clearTimeout = function clearTimeout() {
  8452. if (this.reloadTimer !== -1) {
  8453. self.clearTimeout(this.reloadTimer);
  8454. this.reloadTimer = -1;
  8455. }
  8456. };
  8457. _proto.destroy = function destroy() {
  8458. this.unregisterListeners();
  8459. this.stopLoad();
  8460. // @ts-ignore
  8461. this.hls = null;
  8462. this.levels = this.audioTracks = this.subtitleTracks = null;
  8463. };
  8464. _proto.removeLevel = function removeLevel(levelToRemove) {
  8465. var levels = this.levels;
  8466. if (levels) {
  8467. this.levels = levels.filter(function (level) {
  8468. return level !== levelToRemove;
  8469. });
  8470. }
  8471. };
  8472. _proto.onManifestLoading = function onManifestLoading() {
  8473. this.stopLoad();
  8474. this.enabled = true;
  8475. this.timeToLoad = 300;
  8476. this.updated = 0;
  8477. this.uri = null;
  8478. this.pathwayId = '.';
  8479. this.levels = this.audioTracks = this.subtitleTracks = null;
  8480. };
  8481. _proto.onManifestLoaded = function onManifestLoaded(event, data) {
  8482. var contentSteering = data.contentSteering;
  8483. if (contentSteering === null) {
  8484. return;
  8485. }
  8486. this.pathwayId = contentSteering.pathwayId;
  8487. this.uri = contentSteering.uri;
  8488. if (this.started) {
  8489. this.startLoad();
  8490. }
  8491. };
  8492. _proto.onManifestParsed = function onManifestParsed(event, data) {
  8493. this.audioTracks = data.audioTracks;
  8494. this.subtitleTracks = data.subtitleTracks;
  8495. };
  8496. _proto.onError = function onError(event, data) {
  8497. var errorAction = data.errorAction;
  8498. if ((errorAction == null ? void 0 : errorAction.action) === NetworkErrorAction.SendAlternateToPenaltyBox && errorAction.flags === ErrorActionFlags.MoveAllAlternatesMatchingHost) {
  8499. var levels = this.levels;
  8500. var pathwayPriority = this.pathwayPriority;
  8501. var errorPathway = this.pathwayId;
  8502. if (data.context) {
  8503. var _data$context = data.context,
  8504. groupId = _data$context.groupId,
  8505. _pathwayId = _data$context.pathwayId,
  8506. type = _data$context.type;
  8507. if (groupId && levels) {
  8508. errorPathway = this.getPathwayForGroupId(groupId, type, errorPathway);
  8509. } else if (_pathwayId) {
  8510. errorPathway = _pathwayId;
  8511. }
  8512. }
  8513. if (!(errorPathway in this.penalizedPathways)) {
  8514. this.penalizedPathways[errorPathway] = performance.now();
  8515. }
  8516. if (!pathwayPriority && levels) {
  8517. // If PATHWAY-PRIORITY was not provided, list pathways for error handling
  8518. pathwayPriority = levels.reduce(function (pathways, level) {
  8519. if (pathways.indexOf(level.pathwayId) === -1) {
  8520. pathways.push(level.pathwayId);
  8521. }
  8522. return pathways;
  8523. }, []);
  8524. }
  8525. if (pathwayPriority && pathwayPriority.length > 1) {
  8526. this.updatePathwayPriority(pathwayPriority);
  8527. errorAction.resolved = this.pathwayId !== errorPathway;
  8528. }
  8529. if (!errorAction.resolved) {
  8530. 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));
  8531. }
  8532. }
  8533. };
  8534. _proto.filterParsedLevels = function filterParsedLevels(levels) {
  8535. // Filter levels to only include those that are in the initial pathway
  8536. this.levels = levels;
  8537. var pathwayLevels = this.getLevelsForPathway(this.pathwayId);
  8538. if (pathwayLevels.length === 0) {
  8539. var _pathwayId2 = levels[0].pathwayId;
  8540. this.log("No levels found in Pathway " + this.pathwayId + ". Setting initial Pathway to \"" + _pathwayId2 + "\"");
  8541. pathwayLevels = this.getLevelsForPathway(_pathwayId2);
  8542. this.pathwayId = _pathwayId2;
  8543. }
  8544. if (pathwayLevels.length !== levels.length) {
  8545. this.log("Found " + pathwayLevels.length + "/" + levels.length + " levels in Pathway \"" + this.pathwayId + "\"");
  8546. return pathwayLevels;
  8547. }
  8548. return levels;
  8549. };
  8550. _proto.getLevelsForPathway = function getLevelsForPathway(pathwayId) {
  8551. if (this.levels === null) {
  8552. return [];
  8553. }
  8554. return this.levels.filter(function (level) {
  8555. return pathwayId === level.pathwayId;
  8556. });
  8557. };
  8558. _proto.updatePathwayPriority = function updatePathwayPriority(pathwayPriority) {
  8559. this.pathwayPriority = pathwayPriority;
  8560. var levels;
  8561. // Evaluate if we should remove the pathway from the penalized list
  8562. var penalizedPathways = this.penalizedPathways;
  8563. var now = performance.now();
  8564. Object.keys(penalizedPathways).forEach(function (pathwayId) {
  8565. if (now - penalizedPathways[pathwayId] > PATHWAY_PENALTY_DURATION_MS) {
  8566. delete penalizedPathways[pathwayId];
  8567. }
  8568. });
  8569. for (var i = 0; i < pathwayPriority.length; i++) {
  8570. var _pathwayId3 = pathwayPriority[i];
  8571. if (_pathwayId3 in penalizedPathways) {
  8572. continue;
  8573. }
  8574. if (_pathwayId3 === this.pathwayId) {
  8575. return;
  8576. }
  8577. var selectedIndex = this.hls.nextLoadLevel;
  8578. var selectedLevel = this.hls.levels[selectedIndex];
  8579. levels = this.getLevelsForPathway(_pathwayId3);
  8580. if (levels.length > 0) {
  8581. this.log("Setting Pathway to \"" + _pathwayId3 + "\"");
  8582. this.pathwayId = _pathwayId3;
  8583. reassignFragmentLevelIndexes(levels);
  8584. this.hls.trigger(Events.LEVELS_UPDATED, {
  8585. levels: levels
  8586. });
  8587. // Set LevelController's level to trigger LEVEL_SWITCHING which loads playlist if needed
  8588. var levelAfterChange = this.hls.levels[selectedIndex];
  8589. if (selectedLevel && levelAfterChange && this.levels) {
  8590. if (levelAfterChange.attrs['STABLE-VARIANT-ID'] !== selectedLevel.attrs['STABLE-VARIANT-ID'] && levelAfterChange.bitrate !== selectedLevel.bitrate) {
  8591. this.log("Unstable Pathways change from bitrate " + selectedLevel.bitrate + " to " + levelAfterChange.bitrate);
  8592. }
  8593. this.hls.nextLoadLevel = selectedIndex;
  8594. }
  8595. break;
  8596. }
  8597. }
  8598. };
  8599. _proto.getPathwayForGroupId = function getPathwayForGroupId(groupId, type, defaultPathway) {
  8600. var levels = this.getLevelsForPathway(defaultPathway).concat(this.levels || []);
  8601. for (var i = 0; i < levels.length; i++) {
  8602. if (type === PlaylistContextType.AUDIO_TRACK && levels[i].hasAudioGroup(groupId) || type === PlaylistContextType.SUBTITLE_TRACK && levels[i].hasSubtitleGroup(groupId)) {
  8603. return levels[i].pathwayId;
  8604. }
  8605. }
  8606. return defaultPathway;
  8607. };
  8608. _proto.clonePathways = function clonePathways(pathwayClones) {
  8609. var _this = this;
  8610. var levels = this.levels;
  8611. if (!levels) {
  8612. return;
  8613. }
  8614. var audioGroupCloneMap = {};
  8615. var subtitleGroupCloneMap = {};
  8616. pathwayClones.forEach(function (pathwayClone) {
  8617. var cloneId = pathwayClone.ID,
  8618. baseId = pathwayClone['BASE-ID'],
  8619. uriReplacement = pathwayClone['URI-REPLACEMENT'];
  8620. if (levels.some(function (level) {
  8621. return level.pathwayId === cloneId;
  8622. })) {
  8623. return;
  8624. }
  8625. var clonedVariants = _this.getLevelsForPathway(baseId).map(function (baseLevel) {
  8626. var attributes = new AttrList(baseLevel.attrs);
  8627. attributes['PATHWAY-ID'] = cloneId;
  8628. var clonedAudioGroupId = attributes.AUDIO && attributes.AUDIO + "_clone_" + cloneId;
  8629. var clonedSubtitleGroupId = attributes.SUBTITLES && attributes.SUBTITLES + "_clone_" + cloneId;
  8630. if (clonedAudioGroupId) {
  8631. audioGroupCloneMap[attributes.AUDIO] = clonedAudioGroupId;
  8632. attributes.AUDIO = clonedAudioGroupId;
  8633. }
  8634. if (clonedSubtitleGroupId) {
  8635. subtitleGroupCloneMap[attributes.SUBTITLES] = clonedSubtitleGroupId;
  8636. attributes.SUBTITLES = clonedSubtitleGroupId;
  8637. }
  8638. var url = performUriReplacement(baseLevel.uri, attributes['STABLE-VARIANT-ID'], 'PER-VARIANT-URIS', uriReplacement);
  8639. var clonedLevel = new Level({
  8640. attrs: attributes,
  8641. audioCodec: baseLevel.audioCodec,
  8642. bitrate: baseLevel.bitrate,
  8643. height: baseLevel.height,
  8644. name: baseLevel.name,
  8645. url: url,
  8646. videoCodec: baseLevel.videoCodec,
  8647. width: baseLevel.width
  8648. });
  8649. if (baseLevel.audioGroups) {
  8650. for (var i = 1; i < baseLevel.audioGroups.length; i++) {
  8651. clonedLevel.addGroupId('audio', baseLevel.audioGroups[i] + "_clone_" + cloneId);
  8652. }
  8653. }
  8654. if (baseLevel.subtitleGroups) {
  8655. for (var _i = 1; _i < baseLevel.subtitleGroups.length; _i++) {
  8656. clonedLevel.addGroupId('text', baseLevel.subtitleGroups[_i] + "_clone_" + cloneId);
  8657. }
  8658. }
  8659. return clonedLevel;
  8660. });
  8661. levels.push.apply(levels, clonedVariants);
  8662. cloneRenditionGroups(_this.audioTracks, audioGroupCloneMap, uriReplacement, cloneId);
  8663. cloneRenditionGroups(_this.subtitleTracks, subtitleGroupCloneMap, uriReplacement, cloneId);
  8664. });
  8665. };
  8666. _proto.loadSteeringManifest = function loadSteeringManifest(uri) {
  8667. var _this2 = this;
  8668. var config = this.hls.config;
  8669. var Loader = config.loader;
  8670. if (this.loader) {
  8671. this.loader.destroy();
  8672. }
  8673. this.loader = new Loader(config);
  8674. var url;
  8675. try {
  8676. url = new self.URL(uri);
  8677. } catch (error) {
  8678. this.enabled = false;
  8679. this.log("Failed to parse Steering Manifest URI: " + uri);
  8680. return;
  8681. }
  8682. if (url.protocol !== 'data:') {
  8683. var throughput = (this.hls.bandwidthEstimate || config.abrEwmaDefaultEstimate) | 0;
  8684. url.searchParams.set('_HLS_pathway', this.pathwayId);
  8685. url.searchParams.set('_HLS_throughput', '' + throughput);
  8686. }
  8687. var context = {
  8688. responseType: 'json',
  8689. url: url.href
  8690. };
  8691. var loadPolicy = config.steeringManifestLoadPolicy.default;
  8692. var legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  8693. var loaderConfig = {
  8694. loadPolicy: loadPolicy,
  8695. timeout: loadPolicy.maxLoadTimeMs,
  8696. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  8697. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  8698. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  8699. };
  8700. var callbacks = {
  8701. onSuccess: function onSuccess(response, stats, context, networkDetails) {
  8702. _this2.log("Loaded steering manifest: \"" + url + "\"");
  8703. var steeringData = response.data;
  8704. if (steeringData.VERSION !== 1) {
  8705. _this2.log("Steering VERSION " + steeringData.VERSION + " not supported!");
  8706. return;
  8707. }
  8708. _this2.updated = performance.now();
  8709. _this2.timeToLoad = steeringData.TTL;
  8710. var reloadUri = steeringData['RELOAD-URI'],
  8711. pathwayClones = steeringData['PATHWAY-CLONES'],
  8712. pathwayPriority = steeringData['PATHWAY-PRIORITY'];
  8713. if (reloadUri) {
  8714. try {
  8715. _this2.uri = new self.URL(reloadUri, url).href;
  8716. } catch (error) {
  8717. _this2.enabled = false;
  8718. _this2.log("Failed to parse Steering Manifest RELOAD-URI: " + reloadUri);
  8719. return;
  8720. }
  8721. }
  8722. _this2.scheduleRefresh(_this2.uri || context.url);
  8723. if (pathwayClones) {
  8724. _this2.clonePathways(pathwayClones);
  8725. }
  8726. var loadedSteeringData = {
  8727. steeringManifest: steeringData,
  8728. url: url.toString()
  8729. };
  8730. _this2.hls.trigger(Events.STEERING_MANIFEST_LOADED, loadedSteeringData);
  8731. if (pathwayPriority) {
  8732. _this2.updatePathwayPriority(pathwayPriority);
  8733. }
  8734. },
  8735. onError: function onError(error, context, networkDetails, stats) {
  8736. _this2.log("Error loading steering manifest: " + error.code + " " + error.text + " (" + context.url + ")");
  8737. _this2.stopLoad();
  8738. if (error.code === 410) {
  8739. _this2.enabled = false;
  8740. _this2.log("Steering manifest " + context.url + " no longer available");
  8741. return;
  8742. }
  8743. var ttl = _this2.timeToLoad * 1000;
  8744. if (error.code === 429) {
  8745. var loader = _this2.loader;
  8746. if (typeof (loader == null ? void 0 : loader.getResponseHeader) === 'function') {
  8747. var retryAfter = loader.getResponseHeader('Retry-After');
  8748. if (retryAfter) {
  8749. ttl = parseFloat(retryAfter) * 1000;
  8750. }
  8751. }
  8752. _this2.log("Steering manifest " + context.url + " rate limited");
  8753. return;
  8754. }
  8755. _this2.scheduleRefresh(_this2.uri || context.url, ttl);
  8756. },
  8757. onTimeout: function onTimeout(stats, context, networkDetails) {
  8758. _this2.log("Timeout loading steering manifest (" + context.url + ")");
  8759. _this2.scheduleRefresh(_this2.uri || context.url);
  8760. }
  8761. };
  8762. this.log("Requesting steering manifest: " + url);
  8763. this.loader.load(context, loaderConfig, callbacks);
  8764. };
  8765. _proto.scheduleRefresh = function scheduleRefresh(uri, ttlMs) {
  8766. var _this3 = this;
  8767. if (ttlMs === void 0) {
  8768. ttlMs = this.timeToLoad * 1000;
  8769. }
  8770. this.clearTimeout();
  8771. this.reloadTimer = self.setTimeout(function () {
  8772. var _this3$hls;
  8773. var media = (_this3$hls = _this3.hls) == null ? void 0 : _this3$hls.media;
  8774. if (media && !media.ended) {
  8775. _this3.loadSteeringManifest(uri);
  8776. return;
  8777. }
  8778. _this3.scheduleRefresh(uri, _this3.timeToLoad * 1000);
  8779. }, ttlMs);
  8780. };
  8781. return ContentSteeringController;
  8782. }();
  8783. function cloneRenditionGroups(tracks, groupCloneMap, uriReplacement, cloneId) {
  8784. if (!tracks) {
  8785. return;
  8786. }
  8787. Object.keys(groupCloneMap).forEach(function (audioGroupId) {
  8788. var clonedTracks = tracks.filter(function (track) {
  8789. return track.groupId === audioGroupId;
  8790. }).map(function (track) {
  8791. var clonedTrack = _extends({}, track);
  8792. clonedTrack.details = undefined;
  8793. clonedTrack.attrs = new AttrList(clonedTrack.attrs);
  8794. clonedTrack.url = clonedTrack.attrs.URI = performUriReplacement(track.url, track.attrs['STABLE-RENDITION-ID'], 'PER-RENDITION-URIS', uriReplacement);
  8795. clonedTrack.groupId = clonedTrack.attrs['GROUP-ID'] = groupCloneMap[audioGroupId];
  8796. clonedTrack.attrs['PATHWAY-ID'] = cloneId;
  8797. return clonedTrack;
  8798. });
  8799. tracks.push.apply(tracks, clonedTracks);
  8800. });
  8801. }
  8802. function performUriReplacement(uri, stableId, perOptionKey, uriReplacement) {
  8803. var host = uriReplacement.HOST,
  8804. params = uriReplacement.PARAMS,
  8805. perOptionUris = uriReplacement[perOptionKey];
  8806. var perVariantUri;
  8807. if (stableId) {
  8808. perVariantUri = perOptionUris == null ? void 0 : perOptionUris[stableId];
  8809. if (perVariantUri) {
  8810. uri = perVariantUri;
  8811. }
  8812. }
  8813. var url = new self.URL(uri);
  8814. if (host && !perVariantUri) {
  8815. url.host = host;
  8816. }
  8817. if (params) {
  8818. Object.keys(params).sort().forEach(function (key) {
  8819. if (key) {
  8820. url.searchParams.set(key, params[key]);
  8821. }
  8822. });
  8823. }
  8824. return url.href;
  8825. }
  8826. var AGE_HEADER_LINE_REGEX = /^age:\s*[\d.]+\s*$/im;
  8827. var XhrLoader = /*#__PURE__*/function () {
  8828. function XhrLoader(config) {
  8829. this.xhrSetup = void 0;
  8830. this.requestTimeout = void 0;
  8831. this.retryTimeout = void 0;
  8832. this.retryDelay = void 0;
  8833. this.config = null;
  8834. this.callbacks = null;
  8835. this.context = null;
  8836. this.loader = null;
  8837. this.stats = void 0;
  8838. this.xhrSetup = config ? config.xhrSetup || null : null;
  8839. this.stats = new LoadStats();
  8840. this.retryDelay = 0;
  8841. }
  8842. var _proto = XhrLoader.prototype;
  8843. _proto.destroy = function destroy() {
  8844. this.callbacks = null;
  8845. this.abortInternal();
  8846. this.loader = null;
  8847. this.config = null;
  8848. this.context = null;
  8849. this.xhrSetup = null;
  8850. };
  8851. _proto.abortInternal = function abortInternal() {
  8852. var loader = this.loader;
  8853. self.clearTimeout(this.requestTimeout);
  8854. self.clearTimeout(this.retryTimeout);
  8855. if (loader) {
  8856. loader.onreadystatechange = null;
  8857. loader.onprogress = null;
  8858. if (loader.readyState !== 4) {
  8859. this.stats.aborted = true;
  8860. loader.abort();
  8861. }
  8862. }
  8863. };
  8864. _proto.abort = function abort() {
  8865. var _this$callbacks;
  8866. this.abortInternal();
  8867. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  8868. this.callbacks.onAbort(this.stats, this.context, this.loader);
  8869. }
  8870. };
  8871. _proto.load = function load(context, config, callbacks) {
  8872. if (this.stats.loading.start) {
  8873. throw new Error('Loader can only be used once.');
  8874. }
  8875. this.stats.loading.start = self.performance.now();
  8876. this.context = context;
  8877. this.config = config;
  8878. this.callbacks = callbacks;
  8879. this.loadInternal();
  8880. };
  8881. _proto.loadInternal = function loadInternal() {
  8882. var _this = this;
  8883. var config = this.config,
  8884. context = this.context;
  8885. if (!config || !context) {
  8886. return;
  8887. }
  8888. var xhr = this.loader = new self.XMLHttpRequest();
  8889. var stats = this.stats;
  8890. stats.loading.first = 0;
  8891. stats.loaded = 0;
  8892. stats.aborted = false;
  8893. var xhrSetup = this.xhrSetup;
  8894. if (xhrSetup) {
  8895. Promise.resolve().then(function () {
  8896. if (_this.loader !== xhr || _this.stats.aborted) return;
  8897. return xhrSetup(xhr, context.url);
  8898. }).catch(function (error) {
  8899. if (_this.loader !== xhr || _this.stats.aborted) return;
  8900. xhr.open('GET', context.url, true);
  8901. return xhrSetup(xhr, context.url);
  8902. }).then(function () {
  8903. if (_this.loader !== xhr || _this.stats.aborted) return;
  8904. _this.openAndSendXhr(xhr, context, config);
  8905. }).catch(function (error) {
  8906. // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
  8907. _this.callbacks.onError({
  8908. code: xhr.status,
  8909. text: error.message
  8910. }, context, xhr, stats);
  8911. return;
  8912. });
  8913. } else {
  8914. this.openAndSendXhr(xhr, context, config);
  8915. }
  8916. };
  8917. _proto.openAndSendXhr = function openAndSendXhr(xhr, context, config) {
  8918. if (!xhr.readyState) {
  8919. xhr.open('GET', context.url, true);
  8920. }
  8921. var headers = context.headers;
  8922. var _config$loadPolicy = config.loadPolicy,
  8923. maxTimeToFirstByteMs = _config$loadPolicy.maxTimeToFirstByteMs,
  8924. maxLoadTimeMs = _config$loadPolicy.maxLoadTimeMs;
  8925. if (headers) {
  8926. for (var header in headers) {
  8927. xhr.setRequestHeader(header, headers[header]);
  8928. }
  8929. }
  8930. if (context.rangeEnd) {
  8931. xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));
  8932. }
  8933. xhr.onreadystatechange = this.readystatechange.bind(this);
  8934. xhr.onprogress = this.loadprogress.bind(this);
  8935. xhr.responseType = context.responseType;
  8936. // setup timeout before we perform request
  8937. self.clearTimeout(this.requestTimeout);
  8938. config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  8939. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);
  8940. xhr.send();
  8941. };
  8942. _proto.readystatechange = function readystatechange() {
  8943. var context = this.context,
  8944. xhr = this.loader,
  8945. stats = this.stats;
  8946. if (!context || !xhr) {
  8947. return;
  8948. }
  8949. var readyState = xhr.readyState;
  8950. var config = this.config;
  8951. // don't proceed if xhr has been aborted
  8952. if (stats.aborted) {
  8953. return;
  8954. }
  8955. // >= HEADERS_RECEIVED
  8956. if (readyState >= 2) {
  8957. if (stats.loading.first === 0) {
  8958. stats.loading.first = Math.max(self.performance.now(), stats.loading.start);
  8959. // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet
  8960. if (config.timeout !== config.loadPolicy.maxLoadTimeMs) {
  8961. self.clearTimeout(this.requestTimeout);
  8962. config.timeout = config.loadPolicy.maxLoadTimeMs;
  8963. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.loadPolicy.maxLoadTimeMs - (stats.loading.first - stats.loading.start));
  8964. }
  8965. }
  8966. if (readyState === 4) {
  8967. self.clearTimeout(this.requestTimeout);
  8968. xhr.onreadystatechange = null;
  8969. xhr.onprogress = null;
  8970. var _status = xhr.status;
  8971. // http status between 200 to 299 are all successful
  8972. var useResponse = xhr.responseType !== 'text';
  8973. if (_status >= 200 && _status < 300 && (useResponse && xhr.response || xhr.responseText !== null)) {
  8974. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  8975. var data = useResponse ? xhr.response : xhr.responseText;
  8976. var len = xhr.responseType === 'arraybuffer' ? data.byteLength : data.length;
  8977. stats.loaded = stats.total = len;
  8978. stats.bwEstimate = stats.total * 8000 / (stats.loading.end - stats.loading.first);
  8979. if (!this.callbacks) {
  8980. return;
  8981. }
  8982. var onProgress = this.callbacks.onProgress;
  8983. if (onProgress) {
  8984. onProgress(stats, context, data, xhr);
  8985. }
  8986. if (!this.callbacks) {
  8987. return;
  8988. }
  8989. var response = {
  8990. url: xhr.responseURL,
  8991. data: data,
  8992. code: _status
  8993. };
  8994. this.callbacks.onSuccess(response, stats, context, xhr);
  8995. } else {
  8996. var retryConfig = config.loadPolicy.errorRetry;
  8997. var retryCount = stats.retry;
  8998. // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error
  8999. var _response = {
  9000. url: context.url,
  9001. data: undefined,
  9002. code: _status
  9003. };
  9004. if (shouldRetry(retryConfig, retryCount, false, _response)) {
  9005. this.retry(retryConfig);
  9006. } else {
  9007. logger.error(_status + " while loading " + context.url);
  9008. this.callbacks.onError({
  9009. code: _status,
  9010. text: xhr.statusText
  9011. }, context, xhr, stats);
  9012. }
  9013. }
  9014. }
  9015. }
  9016. };
  9017. _proto.loadtimeout = function loadtimeout() {
  9018. if (!this.config) return;
  9019. var retryConfig = this.config.loadPolicy.timeoutRetry;
  9020. var retryCount = this.stats.retry;
  9021. if (shouldRetry(retryConfig, retryCount, true)) {
  9022. this.retry(retryConfig);
  9023. } else {
  9024. var _this$context;
  9025. logger.warn("timeout while loading " + ((_this$context = this.context) == null ? void 0 : _this$context.url));
  9026. var callbacks = this.callbacks;
  9027. if (callbacks) {
  9028. this.abortInternal();
  9029. callbacks.onTimeout(this.stats, this.context, this.loader);
  9030. }
  9031. }
  9032. };
  9033. _proto.retry = function retry(retryConfig) {
  9034. var context = this.context,
  9035. stats = this.stats;
  9036. this.retryDelay = getRetryDelay(retryConfig, stats.retry);
  9037. stats.retry++;
  9038. logger.warn((status ? 'HTTP Status ' + status : 'Timeout') + " while loading " + (context == null ? void 0 : context.url) + ", retrying " + stats.retry + "/" + retryConfig.maxNumRetry + " in " + this.retryDelay + "ms");
  9039. // abort and reset internal state
  9040. this.abortInternal();
  9041. this.loader = null;
  9042. // schedule retry
  9043. self.clearTimeout(this.retryTimeout);
  9044. this.retryTimeout = self.setTimeout(this.loadInternal.bind(this), this.retryDelay);
  9045. };
  9046. _proto.loadprogress = function loadprogress(event) {
  9047. var stats = this.stats;
  9048. stats.loaded = event.loaded;
  9049. if (event.lengthComputable) {
  9050. stats.total = event.total;
  9051. }
  9052. };
  9053. _proto.getCacheAge = function getCacheAge() {
  9054. var result = null;
  9055. if (this.loader && AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())) {
  9056. var ageHeader = this.loader.getResponseHeader('age');
  9057. result = ageHeader ? parseFloat(ageHeader) : null;
  9058. }
  9059. return result;
  9060. };
  9061. _proto.getResponseHeader = function getResponseHeader(name) {
  9062. if (this.loader && new RegExp("^" + name + ":\\s*[\\d.]+\\s*$", 'im').test(this.loader.getAllResponseHeaders())) {
  9063. return this.loader.getResponseHeader(name);
  9064. }
  9065. return null;
  9066. };
  9067. return XhrLoader;
  9068. }();
  9069. var ChunkCache = /*#__PURE__*/function () {
  9070. function ChunkCache() {
  9071. this.chunks = [];
  9072. this.dataLength = 0;
  9073. }
  9074. var _proto = ChunkCache.prototype;
  9075. _proto.push = function push(chunk) {
  9076. this.chunks.push(chunk);
  9077. this.dataLength += chunk.length;
  9078. };
  9079. _proto.flush = function flush() {
  9080. var chunks = this.chunks,
  9081. dataLength = this.dataLength;
  9082. var result;
  9083. if (!chunks.length) {
  9084. return new Uint8Array(0);
  9085. } else if (chunks.length === 1) {
  9086. result = chunks[0];
  9087. } else {
  9088. result = concatUint8Arrays(chunks, dataLength);
  9089. }
  9090. this.reset();
  9091. return result;
  9092. };
  9093. _proto.reset = function reset() {
  9094. this.chunks.length = 0;
  9095. this.dataLength = 0;
  9096. };
  9097. return ChunkCache;
  9098. }();
  9099. function concatUint8Arrays(chunks, dataLength) {
  9100. var result = new Uint8Array(dataLength);
  9101. var offset = 0;
  9102. for (var i = 0; i < chunks.length; i++) {
  9103. var chunk = chunks[i];
  9104. result.set(chunk, offset);
  9105. offset += chunk.length;
  9106. }
  9107. return result;
  9108. }
  9109. function fetchSupported() {
  9110. if (
  9111. // @ts-ignore
  9112. self.fetch && self.AbortController && self.ReadableStream && self.Request) {
  9113. try {
  9114. new self.ReadableStream({}); // eslint-disable-line no-new
  9115. return true;
  9116. } catch (e) {
  9117. /* noop */
  9118. }
  9119. }
  9120. return false;
  9121. }
  9122. var BYTERANGE = /(\d+)-(\d+)\/(\d+)/;
  9123. var FetchLoader = /*#__PURE__*/function () {
  9124. function FetchLoader(config /* HlsConfig */) {
  9125. this.fetchSetup = void 0;
  9126. this.requestTimeout = void 0;
  9127. this.request = null;
  9128. this.response = null;
  9129. this.controller = void 0;
  9130. this.context = null;
  9131. this.config = null;
  9132. this.callbacks = null;
  9133. this.stats = void 0;
  9134. this.loader = null;
  9135. this.fetchSetup = config.fetchSetup || getRequest;
  9136. this.controller = new self.AbortController();
  9137. this.stats = new LoadStats();
  9138. }
  9139. var _proto = FetchLoader.prototype;
  9140. _proto.destroy = function destroy() {
  9141. this.loader = this.callbacks = this.context = this.config = this.request = null;
  9142. this.abortInternal();
  9143. this.response = null;
  9144. // @ts-ignore
  9145. this.fetchSetup = this.controller = this.stats = null;
  9146. };
  9147. _proto.abortInternal = function abortInternal() {
  9148. if (this.controller && !this.stats.loading.end) {
  9149. this.stats.aborted = true;
  9150. this.controller.abort();
  9151. }
  9152. };
  9153. _proto.abort = function abort() {
  9154. var _this$callbacks;
  9155. this.abortInternal();
  9156. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  9157. this.callbacks.onAbort(this.stats, this.context, this.response);
  9158. }
  9159. };
  9160. _proto.load = function load(context, config, callbacks) {
  9161. var _this = this;
  9162. var stats = this.stats;
  9163. if (stats.loading.start) {
  9164. throw new Error('Loader can only be used once.');
  9165. }
  9166. stats.loading.start = self.performance.now();
  9167. var initParams = getRequestParameters(context, this.controller.signal);
  9168. var onProgress = callbacks.onProgress;
  9169. var isArrayBuffer = context.responseType === 'arraybuffer';
  9170. var LENGTH = isArrayBuffer ? 'byteLength' : 'length';
  9171. var _config$loadPolicy = config.loadPolicy,
  9172. maxTimeToFirstByteMs = _config$loadPolicy.maxTimeToFirstByteMs,
  9173. maxLoadTimeMs = _config$loadPolicy.maxLoadTimeMs;
  9174. this.context = context;
  9175. this.config = config;
  9176. this.callbacks = callbacks;
  9177. this.request = this.fetchSetup(context, initParams);
  9178. self.clearTimeout(this.requestTimeout);
  9179. config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  9180. this.requestTimeout = self.setTimeout(function () {
  9181. _this.abortInternal();
  9182. callbacks.onTimeout(stats, context, _this.response);
  9183. }, config.timeout);
  9184. self.fetch(this.request).then(function (response) {
  9185. _this.response = _this.loader = response;
  9186. var first = Math.max(self.performance.now(), stats.loading.start);
  9187. self.clearTimeout(_this.requestTimeout);
  9188. config.timeout = maxLoadTimeMs;
  9189. _this.requestTimeout = self.setTimeout(function () {
  9190. _this.abortInternal();
  9191. callbacks.onTimeout(stats, context, _this.response);
  9192. }, maxLoadTimeMs - (first - stats.loading.start));
  9193. if (!response.ok) {
  9194. var status = response.status,
  9195. statusText = response.statusText;
  9196. throw new FetchError(statusText || 'fetch, bad network response', status, response);
  9197. }
  9198. stats.loading.first = first;
  9199. stats.total = getContentLength(response.headers) || stats.total;
  9200. if (onProgress && isFiniteNumber(config.highWaterMark)) {
  9201. return _this.loadProgressively(response, stats, context, config.highWaterMark, onProgress);
  9202. }
  9203. if (isArrayBuffer) {
  9204. return response.arrayBuffer();
  9205. }
  9206. if (context.responseType === 'json') {
  9207. return response.json();
  9208. }
  9209. return response.text();
  9210. }).then(function (responseData) {
  9211. var response = _this.response;
  9212. if (!response) {
  9213. throw new Error('loader destroyed');
  9214. }
  9215. self.clearTimeout(_this.requestTimeout);
  9216. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  9217. var total = responseData[LENGTH];
  9218. if (total) {
  9219. stats.loaded = stats.total = total;
  9220. }
  9221. var loaderResponse = {
  9222. url: response.url,
  9223. data: responseData,
  9224. code: response.status
  9225. };
  9226. if (onProgress && !isFiniteNumber(config.highWaterMark)) {
  9227. onProgress(stats, context, responseData, response);
  9228. }
  9229. callbacks.onSuccess(loaderResponse, stats, context, response);
  9230. }).catch(function (error) {
  9231. self.clearTimeout(_this.requestTimeout);
  9232. if (stats.aborted) {
  9233. return;
  9234. }
  9235. // CORS errors result in an undefined code. Set it to 0 here to align with XHR's behavior
  9236. // when destroying, 'error' itself can be undefined
  9237. var code = !error ? 0 : error.code || 0;
  9238. var text = !error ? null : error.message;
  9239. callbacks.onError({
  9240. code: code,
  9241. text: text
  9242. }, context, error ? error.details : null, stats);
  9243. });
  9244. };
  9245. _proto.getCacheAge = function getCacheAge() {
  9246. var result = null;
  9247. if (this.response) {
  9248. var ageHeader = this.response.headers.get('age');
  9249. result = ageHeader ? parseFloat(ageHeader) : null;
  9250. }
  9251. return result;
  9252. };
  9253. _proto.getResponseHeader = function getResponseHeader(name) {
  9254. return this.response ? this.response.headers.get(name) : null;
  9255. };
  9256. _proto.loadProgressively = function loadProgressively(response, stats, context, highWaterMark, onProgress) {
  9257. if (highWaterMark === void 0) {
  9258. highWaterMark = 0;
  9259. }
  9260. var chunkCache = new ChunkCache();
  9261. var reader = response.body.getReader();
  9262. var pump = function pump() {
  9263. return reader.read().then(function (data) {
  9264. if (data.done) {
  9265. if (chunkCache.dataLength) {
  9266. onProgress(stats, context, chunkCache.flush(), response);
  9267. }
  9268. return Promise.resolve(new ArrayBuffer(0));
  9269. }
  9270. var chunk = data.value;
  9271. var len = chunk.length;
  9272. stats.loaded += len;
  9273. if (len < highWaterMark || chunkCache.dataLength) {
  9274. // The current chunk is too small to to be emitted or the cache already has data
  9275. // Push it to the cache
  9276. chunkCache.push(chunk);
  9277. if (chunkCache.dataLength >= highWaterMark) {
  9278. // flush in order to join the typed arrays
  9279. onProgress(stats, context, chunkCache.flush(), response);
  9280. }
  9281. } else {
  9282. // If there's nothing cached already, and the chache is large enough
  9283. // just emit the progress event
  9284. onProgress(stats, context, chunk, response);
  9285. }
  9286. return pump();
  9287. }).catch(function () {
  9288. /* aborted */
  9289. return Promise.reject();
  9290. });
  9291. };
  9292. return pump();
  9293. };
  9294. return FetchLoader;
  9295. }();
  9296. function getRequestParameters(context, signal) {
  9297. var initParams = {
  9298. method: 'GET',
  9299. mode: 'cors',
  9300. credentials: 'same-origin',
  9301. signal: signal,
  9302. headers: new self.Headers(_extends({}, context.headers))
  9303. };
  9304. if (context.rangeEnd) {
  9305. initParams.headers.set('Range', 'bytes=' + context.rangeStart + '-' + String(context.rangeEnd - 1));
  9306. }
  9307. return initParams;
  9308. }
  9309. function getByteRangeLength(byteRangeHeader) {
  9310. var result = BYTERANGE.exec(byteRangeHeader);
  9311. if (result) {
  9312. return parseInt(result[2]) - parseInt(result[1]) + 1;
  9313. }
  9314. }
  9315. function getContentLength(headers) {
  9316. var contentRange = headers.get('Content-Range');
  9317. if (contentRange) {
  9318. var byteRangeLength = getByteRangeLength(contentRange);
  9319. if (isFiniteNumber(byteRangeLength)) {
  9320. return byteRangeLength;
  9321. }
  9322. }
  9323. var contentLength = headers.get('Content-Length');
  9324. if (contentLength) {
  9325. return parseInt(contentLength);
  9326. }
  9327. }
  9328. function getRequest(context, initParams) {
  9329. return new self.Request(context.url, initParams);
  9330. }
  9331. var FetchError = /*#__PURE__*/function (_Error) {
  9332. _inheritsLoose(FetchError, _Error);
  9333. function FetchError(message, code, details) {
  9334. var _this2;
  9335. _this2 = _Error.call(this, message) || this;
  9336. _this2.code = void 0;
  9337. _this2.details = void 0;
  9338. _this2.code = code;
  9339. _this2.details = details;
  9340. return _this2;
  9341. }
  9342. return FetchError;
  9343. }( /*#__PURE__*/_wrapNativeSuper(Error));
  9344. /**
  9345. * @deprecated use fragLoadPolicy.default
  9346. */
  9347. /**
  9348. * @deprecated use manifestLoadPolicy.default and playlistLoadPolicy.default
  9349. */
  9350. var defaultLoadPolicy = {
  9351. maxTimeToFirstByteMs: 8000,
  9352. maxLoadTimeMs: 20000,
  9353. timeoutRetry: null,
  9354. errorRetry: null
  9355. };
  9356. /**
  9357. * @ignore
  9358. * If possible, keep hlsDefaultConfig shallow
  9359. * It is cloned whenever a new Hls instance is created, by keeping the config
  9360. * shallow the properties are cloned, and we don't end up manipulating the default
  9361. */
  9362. var hlsDefaultConfig = _objectSpread2(_objectSpread2({
  9363. autoStartLoad: true,
  9364. // used by stream-controller
  9365. startPosition: -1,
  9366. // used by stream-controller
  9367. defaultAudioCodec: undefined,
  9368. // used by stream-controller
  9369. debug: false,
  9370. // used by logger
  9371. capLevelOnFPSDrop: false,
  9372. // used by fps-controller
  9373. capLevelToPlayerSize: false,
  9374. // used by cap-level-controller
  9375. ignoreDevicePixelRatio: false,
  9376. // used by cap-level-controller
  9377. preferManagedMediaSource: true,
  9378. initialLiveManifestSize: 1,
  9379. // used by stream-controller
  9380. maxBufferLength: 30,
  9381. // used by stream-controller
  9382. backBufferLength: Infinity,
  9383. // used by buffer-controller
  9384. frontBufferFlushThreshold: Infinity,
  9385. maxBufferSize: 60 * 1000 * 1000,
  9386. // used by stream-controller
  9387. maxBufferHole: 0.1,
  9388. // used by stream-controller
  9389. highBufferWatchdogPeriod: 2,
  9390. // used by stream-controller
  9391. nudgeOffset: 0.1,
  9392. // used by stream-controller
  9393. nudgeMaxRetry: 3,
  9394. // used by stream-controller
  9395. maxFragLookUpTolerance: 0.25,
  9396. // used by stream-controller
  9397. liveSyncDurationCount: 3,
  9398. // used by latency-controller
  9399. liveMaxLatencyDurationCount: Infinity,
  9400. // used by latency-controller
  9401. liveSyncDuration: undefined,
  9402. // used by latency-controller
  9403. liveMaxLatencyDuration: undefined,
  9404. // used by latency-controller
  9405. maxLiveSyncPlaybackRate: 1,
  9406. // used by latency-controller
  9407. liveDurationInfinity: false,
  9408. // used by buffer-controller
  9409. /**
  9410. * @deprecated use backBufferLength
  9411. */
  9412. liveBackBufferLength: null,
  9413. // used by buffer-controller
  9414. maxMaxBufferLength: 600,
  9415. // used by stream-controller
  9416. enableWorker: true,
  9417. // used by transmuxer
  9418. workerPath: null,
  9419. // used by transmuxer
  9420. enableSoftwareAES: true,
  9421. // used by decrypter
  9422. startLevel: undefined,
  9423. // used by level-controller
  9424. startFragPrefetch: false,
  9425. // used by stream-controller
  9426. fpsDroppedMonitoringPeriod: 5000,
  9427. // used by fps-controller
  9428. fpsDroppedMonitoringThreshold: 0.2,
  9429. // used by fps-controller
  9430. appendErrorMaxRetry: 3,
  9431. // used by buffer-controller
  9432. loader: XhrLoader,
  9433. // loader: FetchLoader,
  9434. fLoader: undefined,
  9435. // used by fragment-loader
  9436. pLoader: undefined,
  9437. // used by playlist-loader
  9438. xhrSetup: undefined,
  9439. // used by xhr-loader
  9440. licenseXhrSetup: undefined,
  9441. // used by eme-controller
  9442. licenseResponseCallback: undefined,
  9443. // used by eme-controller
  9444. abrController: AbrController,
  9445. bufferController: BufferController,
  9446. capLevelController: CapLevelController,
  9447. errorController: ErrorController,
  9448. fpsController: FPSController,
  9449. stretchShortVideoTrack: false,
  9450. // used by mp4-remuxer
  9451. maxAudioFramesDrift: 1,
  9452. // used by mp4-remuxer
  9453. forceKeyFrameOnDiscontinuity: true,
  9454. // used by ts-demuxer
  9455. abrEwmaFastLive: 3,
  9456. // used by abr-controller
  9457. abrEwmaSlowLive: 9,
  9458. // used by abr-controller
  9459. abrEwmaFastVoD: 3,
  9460. // used by abr-controller
  9461. abrEwmaSlowVoD: 9,
  9462. // used by abr-controller
  9463. abrEwmaDefaultEstimate: 5e5,
  9464. // 500 kbps // used by abr-controller
  9465. abrEwmaDefaultEstimateMax: 5e6,
  9466. // 5 mbps
  9467. abrBandWidthFactor: 0.95,
  9468. // used by abr-controller
  9469. abrBandWidthUpFactor: 0.7,
  9470. // used by abr-controller
  9471. abrMaxWithRealBitrate: false,
  9472. // used by abr-controller
  9473. maxStarvationDelay: 4,
  9474. // used by abr-controller
  9475. maxLoadingDelay: 4,
  9476. // used by abr-controller
  9477. minAutoBitrate: 0,
  9478. // used by hls
  9479. emeEnabled: false,
  9480. // used by eme-controller
  9481. widevineLicenseUrl: undefined,
  9482. // used by eme-controller
  9483. drmSystems: {},
  9484. // used by eme-controller
  9485. drmSystemOptions: {},
  9486. // used by eme-controller
  9487. requestMediaKeySystemAccessFunc: null,
  9488. // used by eme-controller
  9489. testBandwidth: true,
  9490. progressive: false,
  9491. lowLatencyMode: true,
  9492. cmcd: undefined,
  9493. enableDateRangeMetadataCues: true,
  9494. enableEmsgMetadataCues: true,
  9495. enableID3MetadataCues: true,
  9496. useMediaCapabilities: false,
  9497. certLoadPolicy: {
  9498. default: defaultLoadPolicy
  9499. },
  9500. keyLoadPolicy: {
  9501. default: {
  9502. maxTimeToFirstByteMs: 8000,
  9503. maxLoadTimeMs: 20000,
  9504. timeoutRetry: {
  9505. maxNumRetry: 1,
  9506. retryDelayMs: 1000,
  9507. maxRetryDelayMs: 20000,
  9508. backoff: 'linear'
  9509. },
  9510. errorRetry: {
  9511. maxNumRetry: 8,
  9512. retryDelayMs: 1000,
  9513. maxRetryDelayMs: 20000,
  9514. backoff: 'linear'
  9515. }
  9516. }
  9517. },
  9518. manifestLoadPolicy: {
  9519. default: {
  9520. maxTimeToFirstByteMs: Infinity,
  9521. maxLoadTimeMs: 20000,
  9522. timeoutRetry: {
  9523. maxNumRetry: 2,
  9524. retryDelayMs: 0,
  9525. maxRetryDelayMs: 0
  9526. },
  9527. errorRetry: {
  9528. maxNumRetry: 1,
  9529. retryDelayMs: 1000,
  9530. maxRetryDelayMs: 8000
  9531. }
  9532. }
  9533. },
  9534. playlistLoadPolicy: {
  9535. default: {
  9536. maxTimeToFirstByteMs: 10000,
  9537. maxLoadTimeMs: 20000,
  9538. timeoutRetry: {
  9539. maxNumRetry: 2,
  9540. retryDelayMs: 0,
  9541. maxRetryDelayMs: 0
  9542. },
  9543. errorRetry: {
  9544. maxNumRetry: 2,
  9545. retryDelayMs: 1000,
  9546. maxRetryDelayMs: 8000
  9547. }
  9548. }
  9549. },
  9550. fragLoadPolicy: {
  9551. default: {
  9552. maxTimeToFirstByteMs: 10000,
  9553. maxLoadTimeMs: 120000,
  9554. timeoutRetry: {
  9555. maxNumRetry: 4,
  9556. retryDelayMs: 0,
  9557. maxRetryDelayMs: 0
  9558. },
  9559. errorRetry: {
  9560. maxNumRetry: 6,
  9561. retryDelayMs: 1000,
  9562. maxRetryDelayMs: 8000
  9563. }
  9564. }
  9565. },
  9566. steeringManifestLoadPolicy: {
  9567. default: {
  9568. maxTimeToFirstByteMs: 10000,
  9569. maxLoadTimeMs: 20000,
  9570. timeoutRetry: {
  9571. maxNumRetry: 2,
  9572. retryDelayMs: 0,
  9573. maxRetryDelayMs: 0
  9574. },
  9575. errorRetry: {
  9576. maxNumRetry: 1,
  9577. retryDelayMs: 1000,
  9578. maxRetryDelayMs: 8000
  9579. }
  9580. }
  9581. },
  9582. // These default settings are deprecated in favor of the above policies
  9583. // and are maintained for backwards compatibility
  9584. manifestLoadingTimeOut: 10000,
  9585. manifestLoadingMaxRetry: 1,
  9586. manifestLoadingRetryDelay: 1000,
  9587. manifestLoadingMaxRetryTimeout: 64000,
  9588. levelLoadingTimeOut: 10000,
  9589. levelLoadingMaxRetry: 4,
  9590. levelLoadingRetryDelay: 1000,
  9591. levelLoadingMaxRetryTimeout: 64000,
  9592. fragLoadingTimeOut: 20000,
  9593. fragLoadingMaxRetry: 6,
  9594. fragLoadingRetryDelay: 1000,
  9595. fragLoadingMaxRetryTimeout: 64000
  9596. }, timelineConfig()), {}, {
  9597. subtitleStreamController: undefined,
  9598. subtitleTrackController: undefined,
  9599. timelineController: undefined,
  9600. audioStreamController: undefined,
  9601. audioTrackController: undefined,
  9602. emeController: undefined,
  9603. cmcdController: undefined,
  9604. contentSteeringController: ContentSteeringController
  9605. });
  9606. function timelineConfig() {
  9607. return {
  9608. cueHandler: Cues,
  9609. // used by timeline-controller
  9610. enableWebVTT: false,
  9611. // used by timeline-controller
  9612. enableIMSC1: false,
  9613. // used by timeline-controller
  9614. enableCEA708Captions: false,
  9615. // used by timeline-controller
  9616. captionsTextTrack1Label: 'English',
  9617. // used by timeline-controller
  9618. captionsTextTrack1LanguageCode: 'en',
  9619. // used by timeline-controller
  9620. captionsTextTrack2Label: 'Spanish',
  9621. // used by timeline-controller
  9622. captionsTextTrack2LanguageCode: 'es',
  9623. // used by timeline-controller
  9624. captionsTextTrack3Label: 'Unknown CC',
  9625. // used by timeline-controller
  9626. captionsTextTrack3LanguageCode: '',
  9627. // used by timeline-controller
  9628. captionsTextTrack4Label: 'Unknown CC',
  9629. // used by timeline-controller
  9630. captionsTextTrack4LanguageCode: '',
  9631. // used by timeline-controller
  9632. renderTextTracksNatively: true
  9633. };
  9634. }
  9635. /**
  9636. * @ignore
  9637. */
  9638. function mergeConfig(defaultConfig, userConfig) {
  9639. if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {
  9640. throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");
  9641. }
  9642. if (userConfig.liveMaxLatencyDurationCount !== undefined && (userConfig.liveSyncDurationCount === undefined || userConfig.liveMaxLatencyDurationCount <= userConfig.liveSyncDurationCount)) {
  9643. throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');
  9644. }
  9645. if (userConfig.liveMaxLatencyDuration !== undefined && (userConfig.liveSyncDuration === undefined || userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)) {
  9646. throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');
  9647. }
  9648. var defaultsCopy = deepCpy(defaultConfig);
  9649. // Backwards compatibility with deprecated config values
  9650. var deprecatedSettingTypes = ['manifest', 'level', 'frag'];
  9651. var deprecatedSettings = ['TimeOut', 'MaxRetry', 'RetryDelay', 'MaxRetryTimeout'];
  9652. deprecatedSettingTypes.forEach(function (type) {
  9653. var policyName = (type === 'level' ? 'playlist' : type) + "LoadPolicy";
  9654. var policyNotSet = userConfig[policyName] === undefined;
  9655. var report = [];
  9656. deprecatedSettings.forEach(function (setting) {
  9657. var deprecatedSetting = type + "Loading" + setting;
  9658. var value = userConfig[deprecatedSetting];
  9659. if (value !== undefined && policyNotSet) {
  9660. report.push(deprecatedSetting);
  9661. var settings = defaultsCopy[policyName].default;
  9662. userConfig[policyName] = {
  9663. default: settings
  9664. };
  9665. switch (setting) {
  9666. case 'TimeOut':
  9667. settings.maxLoadTimeMs = value;
  9668. settings.maxTimeToFirstByteMs = value;
  9669. break;
  9670. case 'MaxRetry':
  9671. settings.errorRetry.maxNumRetry = value;
  9672. settings.timeoutRetry.maxNumRetry = value;
  9673. break;
  9674. case 'RetryDelay':
  9675. settings.errorRetry.retryDelayMs = value;
  9676. settings.timeoutRetry.retryDelayMs = value;
  9677. break;
  9678. case 'MaxRetryTimeout':
  9679. settings.errorRetry.maxRetryDelayMs = value;
  9680. settings.timeoutRetry.maxRetryDelayMs = value;
  9681. break;
  9682. }
  9683. }
  9684. });
  9685. if (report.length) {
  9686. logger.warn("hls.js config: \"" + report.join('", "') + "\" setting(s) are deprecated, use \"" + policyName + "\": " + JSON.stringify(userConfig[policyName]));
  9687. }
  9688. });
  9689. return _objectSpread2(_objectSpread2({}, defaultsCopy), userConfig);
  9690. }
  9691. function deepCpy(obj) {
  9692. if (obj && typeof obj === 'object') {
  9693. if (Array.isArray(obj)) {
  9694. return obj.map(deepCpy);
  9695. }
  9696. return Object.keys(obj).reduce(function (result, key) {
  9697. result[key] = deepCpy(obj[key]);
  9698. return result;
  9699. }, {});
  9700. }
  9701. return obj;
  9702. }
  9703. /**
  9704. * @ignore
  9705. */
  9706. function enableStreamingMode(config) {
  9707. var currentLoader = config.loader;
  9708. if (currentLoader !== FetchLoader && currentLoader !== XhrLoader) {
  9709. // If a developer has configured their own loader, respect that choice
  9710. logger.log('[config]: Custom loader detected, cannot enable progressive streaming');
  9711. config.progressive = false;
  9712. } else {
  9713. var canStreamProgressively = fetchSupported();
  9714. if (canStreamProgressively) {
  9715. config.loader = FetchLoader;
  9716. config.progressive = true;
  9717. config.enableSoftwareAES = true;
  9718. logger.log('[config]: Progressive streaming enabled, using FetchLoader');
  9719. }
  9720. }
  9721. }
  9722. var chromeOrFirefox;
  9723. var LevelController = /*#__PURE__*/function (_BasePlaylistControll) {
  9724. _inheritsLoose(LevelController, _BasePlaylistControll);
  9725. function LevelController(hls, contentSteeringController) {
  9726. var _this;
  9727. _this = _BasePlaylistControll.call(this, hls, '[level-controller]') || this;
  9728. _this._levels = [];
  9729. _this._firstLevel = -1;
  9730. _this._maxAutoLevel = -1;
  9731. _this._startLevel = void 0;
  9732. _this.currentLevel = null;
  9733. _this.currentLevelIndex = -1;
  9734. _this.manualLevelIndex = -1;
  9735. _this.steering = void 0;
  9736. _this.onParsedComplete = void 0;
  9737. _this.steering = contentSteeringController;
  9738. _this._registerListeners();
  9739. return _this;
  9740. }
  9741. var _proto = LevelController.prototype;
  9742. _proto._registerListeners = function _registerListeners() {
  9743. var hls = this.hls;
  9744. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  9745. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  9746. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  9747. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  9748. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  9749. hls.on(Events.ERROR, this.onError, this);
  9750. };
  9751. _proto._unregisterListeners = function _unregisterListeners() {
  9752. var hls = this.hls;
  9753. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  9754. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  9755. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  9756. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  9757. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  9758. hls.off(Events.ERROR, this.onError, this);
  9759. };
  9760. _proto.destroy = function destroy() {
  9761. this._unregisterListeners();
  9762. this.steering = null;
  9763. this.resetLevels();
  9764. _BasePlaylistControll.prototype.destroy.call(this);
  9765. };
  9766. _proto.stopLoad = function stopLoad() {
  9767. var levels = this._levels;
  9768. // clean up live level details to force reload them, and reset load errors
  9769. levels.forEach(function (level) {
  9770. level.loadError = 0;
  9771. level.fragmentError = 0;
  9772. });
  9773. _BasePlaylistControll.prototype.stopLoad.call(this);
  9774. };
  9775. _proto.resetLevels = function resetLevels() {
  9776. this._startLevel = undefined;
  9777. this.manualLevelIndex = -1;
  9778. this.currentLevelIndex = -1;
  9779. this.currentLevel = null;
  9780. this._levels = [];
  9781. this._maxAutoLevel = -1;
  9782. };
  9783. _proto.onManifestLoading = function onManifestLoading(event, data) {
  9784. this.resetLevels();
  9785. };
  9786. _proto.onManifestLoaded = function onManifestLoaded(event, data) {
  9787. var preferManagedMediaSource = this.hls.config.preferManagedMediaSource;
  9788. var levels = [];
  9789. var redundantSet = {};
  9790. var generatePathwaySet = {};
  9791. var resolutionFound = false;
  9792. var videoCodecFound = false;
  9793. var audioCodecFound = false;
  9794. data.levels.forEach(function (levelParsed) {
  9795. var _audioCodec, _videoCodec;
  9796. var attributes = levelParsed.attrs;
  9797. // erase audio codec info if browser does not support mp4a.40.34.
  9798. // demuxer will autodetect codec and fallback to mpeg/audio
  9799. var audioCodec = levelParsed.audioCodec,
  9800. videoCodec = levelParsed.videoCodec;
  9801. if (((_audioCodec = audioCodec) == null ? void 0 : _audioCodec.indexOf('mp4a.40.34')) !== -1) {
  9802. chromeOrFirefox || (chromeOrFirefox = /chrome|firefox/i.test(navigator.userAgent));
  9803. if (chromeOrFirefox) {
  9804. levelParsed.audioCodec = audioCodec = undefined;
  9805. }
  9806. }
  9807. if (audioCodec) {
  9808. levelParsed.audioCodec = audioCodec = getCodecCompatibleName(audioCodec, preferManagedMediaSource);
  9809. }
  9810. if (((_videoCodec = videoCodec) == null ? void 0 : _videoCodec.indexOf('avc1')) === 0) {
  9811. videoCodec = levelParsed.videoCodec = convertAVC1ToAVCOTI(videoCodec);
  9812. }
  9813. // only keep levels with supported audio/video codecs
  9814. var width = levelParsed.width,
  9815. height = levelParsed.height,
  9816. unknownCodecs = levelParsed.unknownCodecs;
  9817. resolutionFound || (resolutionFound = !!(width && height));
  9818. videoCodecFound || (videoCodecFound = !!videoCodec);
  9819. audioCodecFound || (audioCodecFound = !!audioCodec);
  9820. if (unknownCodecs != null && unknownCodecs.length || audioCodec && !areCodecsMediaSourceSupported(audioCodec, 'audio', preferManagedMediaSource) || videoCodec && !areCodecsMediaSourceSupported(videoCodec, 'video', preferManagedMediaSource)) {
  9821. return;
  9822. }
  9823. var CODECS = attributes.CODECS,
  9824. FRAMERATE = attributes['FRAME-RATE'],
  9825. HDCP = attributes['HDCP-LEVEL'],
  9826. PATHWAY = attributes['PATHWAY-ID'],
  9827. RESOLUTION = attributes.RESOLUTION,
  9828. VIDEO_RANGE = attributes['VIDEO-RANGE'];
  9829. var contentSteeringPrefix = (PATHWAY || '.') + "-";
  9830. var levelKey = "" + contentSteeringPrefix + levelParsed.bitrate + "-" + RESOLUTION + "-" + FRAMERATE + "-" + CODECS + "-" + VIDEO_RANGE + "-" + HDCP;
  9831. if (!redundantSet[levelKey]) {
  9832. var level = new Level(levelParsed);
  9833. redundantSet[levelKey] = level;
  9834. generatePathwaySet[levelKey] = 1;
  9835. levels.push(level);
  9836. } else if (redundantSet[levelKey].uri !== levelParsed.url && !levelParsed.attrs['PATHWAY-ID']) {
  9837. // Assign Pathway IDs to Redundant Streams (default Pathways is ".". Redundant Streams "..", "...", and so on.)
  9838. // Content Steering controller to handles Pathway fallback on error
  9839. var pathwayCount = generatePathwaySet[levelKey] += 1;
  9840. levelParsed.attrs['PATHWAY-ID'] = new Array(pathwayCount + 1).join('.');
  9841. var _level = new Level(levelParsed);
  9842. redundantSet[levelKey] = _level;
  9843. levels.push(_level);
  9844. } else {
  9845. redundantSet[levelKey].addGroupId('audio', attributes.AUDIO);
  9846. redundantSet[levelKey].addGroupId('text', attributes.SUBTITLES);
  9847. }
  9848. });
  9849. this.filterAndSortMediaOptions(levels, data, resolutionFound, videoCodecFound, audioCodecFound);
  9850. };
  9851. _proto.filterAndSortMediaOptions = function filterAndSortMediaOptions(filteredLevels, data, resolutionFound, videoCodecFound, audioCodecFound) {
  9852. var _this2 = this;
  9853. var audioTracks = [];
  9854. var subtitleTracks = [];
  9855. var levels = filteredLevels;
  9856. // remove audio-only and invalid video-range levels if we also have levels with video codecs or RESOLUTION signalled
  9857. if ((resolutionFound || videoCodecFound) && audioCodecFound) {
  9858. levels = levels.filter(function (_ref) {
  9859. var videoCodec = _ref.videoCodec,
  9860. videoRange = _ref.videoRange,
  9861. width = _ref.width,
  9862. height = _ref.height;
  9863. return (!!videoCodec || !!(width && height)) && isVideoRange(videoRange);
  9864. });
  9865. }
  9866. if (levels.length === 0) {
  9867. // Dispatch error after MANIFEST_LOADED is done propagating
  9868. Promise.resolve().then(function () {
  9869. if (_this2.hls) {
  9870. if (data.levels.length) {
  9871. _this2.warn("One or more CODECS in variant not supported: " + JSON.stringify(data.levels[0].attrs));
  9872. }
  9873. var error = new Error('no level with compatible codecs found in manifest');
  9874. _this2.hls.trigger(Events.ERROR, {
  9875. type: ErrorTypes.MEDIA_ERROR,
  9876. details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,
  9877. fatal: true,
  9878. url: data.url,
  9879. error: error,
  9880. reason: error.message
  9881. });
  9882. }
  9883. });
  9884. return;
  9885. }
  9886. if (data.audioTracks) {
  9887. var preferManagedMediaSource = this.hls.config.preferManagedMediaSource;
  9888. audioTracks = data.audioTracks.filter(function (track) {
  9889. return !track.audioCodec || areCodecsMediaSourceSupported(track.audioCodec, 'audio', preferManagedMediaSource);
  9890. });
  9891. // Assign ids after filtering as array indices by group-id
  9892. assignTrackIdsByGroup(audioTracks);
  9893. }
  9894. if (data.subtitles) {
  9895. subtitleTracks = data.subtitles;
  9896. assignTrackIdsByGroup(subtitleTracks);
  9897. }
  9898. // start bitrate is the first bitrate of the manifest
  9899. var unsortedLevels = levels.slice(0);
  9900. // sort levels from lowest to highest
  9901. levels.sort(function (a, b) {
  9902. if (a.attrs['HDCP-LEVEL'] !== b.attrs['HDCP-LEVEL']) {
  9903. return (a.attrs['HDCP-LEVEL'] || '') > (b.attrs['HDCP-LEVEL'] || '') ? 1 : -1;
  9904. }
  9905. // sort on height before bitrate for cap-level-controller
  9906. if (resolutionFound && a.height !== b.height) {
  9907. return a.height - b.height;
  9908. }
  9909. if (a.frameRate !== b.frameRate) {
  9910. return a.frameRate - b.frameRate;
  9911. }
  9912. if (a.videoRange !== b.videoRange) {
  9913. return VideoRangeValues.indexOf(a.videoRange) - VideoRangeValues.indexOf(b.videoRange);
  9914. }
  9915. if (a.videoCodec !== b.videoCodec) {
  9916. var valueA = videoCodecPreferenceValue(a.videoCodec);
  9917. var valueB = videoCodecPreferenceValue(b.videoCodec);
  9918. if (valueA !== valueB) {
  9919. return valueB - valueA;
  9920. }
  9921. }
  9922. if (a.uri === b.uri && a.codecSet !== b.codecSet) {
  9923. var _valueA = codecsSetSelectionPreferenceValue(a.codecSet);
  9924. var _valueB = codecsSetSelectionPreferenceValue(b.codecSet);
  9925. if (_valueA !== _valueB) {
  9926. return _valueB - _valueA;
  9927. }
  9928. }
  9929. if (a.averageBitrate !== b.averageBitrate) {
  9930. return a.averageBitrate - b.averageBitrate;
  9931. }
  9932. return 0;
  9933. });
  9934. var firstLevelInPlaylist = unsortedLevels[0];
  9935. if (this.steering) {
  9936. levels = this.steering.filterParsedLevels(levels);
  9937. if (levels.length !== unsortedLevels.length) {
  9938. for (var i = 0; i < unsortedLevels.length; i++) {
  9939. if (unsortedLevels[i].pathwayId === levels[0].pathwayId) {
  9940. firstLevelInPlaylist = unsortedLevels[i];
  9941. break;
  9942. }
  9943. }
  9944. }
  9945. }
  9946. this._levels = levels;
  9947. // find index of first level in sorted levels
  9948. for (var _i = 0; _i < levels.length; _i++) {
  9949. if (levels[_i] === firstLevelInPlaylist) {
  9950. var _this$hls$userConfig;
  9951. this._firstLevel = _i;
  9952. var firstLevelBitrate = firstLevelInPlaylist.bitrate;
  9953. var bandwidthEstimate = this.hls.bandwidthEstimate;
  9954. this.log("manifest loaded, " + levels.length + " level(s) found, first bitrate: " + firstLevelBitrate);
  9955. // Update default bwe to first variant bitrate as long it has not been configured or set
  9956. if (((_this$hls$userConfig = this.hls.userConfig) == null ? void 0 : _this$hls$userConfig.abrEwmaDefaultEstimate) === undefined) {
  9957. var startingBwEstimate = Math.min(firstLevelBitrate, this.hls.config.abrEwmaDefaultEstimateMax);
  9958. if (startingBwEstimate > bandwidthEstimate && bandwidthEstimate === hlsDefaultConfig.abrEwmaDefaultEstimate) {
  9959. this.hls.bandwidthEstimate = startingBwEstimate;
  9960. }
  9961. }
  9962. break;
  9963. }
  9964. }
  9965. // Audio is only alternate if manifest include a URI along with the audio group tag,
  9966. // and this is not an audio-only stream where levels contain audio-only
  9967. var audioOnly = audioCodecFound && !videoCodecFound;
  9968. var edata = {
  9969. levels: levels,
  9970. audioTracks: audioTracks,
  9971. subtitleTracks: subtitleTracks,
  9972. sessionData: data.sessionData,
  9973. sessionKeys: data.sessionKeys,
  9974. firstLevel: this._firstLevel,
  9975. stats: data.stats,
  9976. audio: audioCodecFound,
  9977. video: videoCodecFound,
  9978. altAudio: !audioOnly && audioTracks.some(function (t) {
  9979. return !!t.url;
  9980. })
  9981. };
  9982. this.hls.trigger(Events.MANIFEST_PARSED, edata);
  9983. // Initiate loading after all controllers have received MANIFEST_PARSED
  9984. if (this.hls.config.autoStartLoad || this.hls.forceStartLoad) {
  9985. this.hls.startLoad(this.hls.config.startPosition);
  9986. }
  9987. };
  9988. _proto.onError = function onError(event, data) {
  9989. if (data.fatal || !data.context) {
  9990. return;
  9991. }
  9992. if (data.context.type === PlaylistContextType.LEVEL && data.context.level === this.level) {
  9993. this.checkRetry(data);
  9994. }
  9995. }
  9996. // reset errors on the successful load of a fragment
  9997. ;
  9998. _proto.onFragBuffered = function onFragBuffered(event, _ref2) {
  9999. var frag = _ref2.frag;
  10000. if (frag !== undefined && frag.type === PlaylistLevelType.MAIN) {
  10001. var el = frag.elementaryStreams;
  10002. if (!Object.keys(el).some(function (type) {
  10003. return !!el[type];
  10004. })) {
  10005. return;
  10006. }
  10007. var level = this._levels[frag.level];
  10008. if (level != null && level.loadError) {
  10009. this.log("Resetting level error count of " + level.loadError + " on frag buffered");
  10010. level.loadError = 0;
  10011. }
  10012. }
  10013. };
  10014. _proto.onLevelLoaded = function onLevelLoaded(event, data) {
  10015. var _data$deliveryDirecti2;
  10016. var level = data.level,
  10017. details = data.details;
  10018. var curLevel = this._levels[level];
  10019. if (!curLevel) {
  10020. var _data$deliveryDirecti;
  10021. this.warn("Invalid level index " + level);
  10022. if ((_data$deliveryDirecti = data.deliveryDirectives) != null && _data$deliveryDirecti.skip) {
  10023. details.deltaUpdateFailed = true;
  10024. }
  10025. return;
  10026. }
  10027. // only process level loaded events matching with expected level
  10028. if (level === this.currentLevelIndex) {
  10029. // reset level load error counter on successful level loaded only if there is no issues with fragments
  10030. if (curLevel.fragmentError === 0) {
  10031. curLevel.loadError = 0;
  10032. }
  10033. this.playlistLoaded(level, data, curLevel.details);
  10034. } else if ((_data$deliveryDirecti2 = data.deliveryDirectives) != null && _data$deliveryDirecti2.skip) {
  10035. // received a delta playlist update that cannot be merged
  10036. details.deltaUpdateFailed = true;
  10037. }
  10038. };
  10039. _proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {
  10040. _BasePlaylistControll.prototype.loadPlaylist.call(this);
  10041. var currentLevelIndex = this.currentLevelIndex;
  10042. var currentLevel = this.currentLevel;
  10043. if (currentLevel && this.shouldLoadPlaylist(currentLevel)) {
  10044. var url = currentLevel.uri;
  10045. if (hlsUrlParameters) {
  10046. try {
  10047. url = hlsUrlParameters.addDirectives(url);
  10048. } catch (error) {
  10049. this.warn("Could not construct new URL with HLS Delivery Directives: " + error);
  10050. }
  10051. }
  10052. var pathwayId = currentLevel.attrs['PATHWAY-ID'];
  10053. 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);
  10054. // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
  10055. // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);
  10056. this.clearTimer();
  10057. this.hls.trigger(Events.LEVEL_LOADING, {
  10058. url: url,
  10059. level: currentLevelIndex,
  10060. pathwayId: currentLevel.attrs['PATHWAY-ID'],
  10061. id: 0,
  10062. // Deprecated Level urlId
  10063. deliveryDirectives: hlsUrlParameters || null
  10064. });
  10065. }
  10066. };
  10067. _proto.removeLevel = function removeLevel(levelIndex) {
  10068. var _this3 = this,
  10069. _this$currentLevel;
  10070. var levels = this._levels.filter(function (level, index) {
  10071. if (index !== levelIndex) {
  10072. return true;
  10073. }
  10074. if (_this3.steering) {
  10075. _this3.steering.removeLevel(level);
  10076. }
  10077. if (level === _this3.currentLevel) {
  10078. _this3.currentLevel = null;
  10079. _this3.currentLevelIndex = -1;
  10080. if (level.details) {
  10081. level.details.fragments.forEach(function (f) {
  10082. return f.level = -1;
  10083. });
  10084. }
  10085. }
  10086. return false;
  10087. });
  10088. reassignFragmentLevelIndexes(levels);
  10089. this._levels = levels;
  10090. if (this.currentLevelIndex > -1 && (_this$currentLevel = this.currentLevel) != null && _this$currentLevel.details) {
  10091. this.currentLevelIndex = this.currentLevel.details.fragments[0].level;
  10092. }
  10093. this.hls.trigger(Events.LEVELS_UPDATED, {
  10094. levels: levels
  10095. });
  10096. };
  10097. _proto.onLevelsUpdated = function onLevelsUpdated(event, _ref3) {
  10098. var levels = _ref3.levels;
  10099. this._levels = levels;
  10100. };
  10101. _proto.checkMaxAutoUpdated = function checkMaxAutoUpdated() {
  10102. var _this$hls = this.hls,
  10103. autoLevelCapping = _this$hls.autoLevelCapping,
  10104. maxAutoLevel = _this$hls.maxAutoLevel,
  10105. maxHdcpLevel = _this$hls.maxHdcpLevel;
  10106. if (this._maxAutoLevel !== maxAutoLevel) {
  10107. this._maxAutoLevel = maxAutoLevel;
  10108. this.hls.trigger(Events.MAX_AUTO_LEVEL_UPDATED, {
  10109. autoLevelCapping: autoLevelCapping,
  10110. levels: this.levels,
  10111. maxAutoLevel: maxAutoLevel,
  10112. minAutoLevel: this.hls.minAutoLevel,
  10113. maxHdcpLevel: maxHdcpLevel
  10114. });
  10115. }
  10116. };
  10117. _createClass(LevelController, [{
  10118. key: "levels",
  10119. get: function get() {
  10120. if (this._levels.length === 0) {
  10121. return null;
  10122. }
  10123. return this._levels;
  10124. }
  10125. }, {
  10126. key: "level",
  10127. get: function get() {
  10128. return this.currentLevelIndex;
  10129. },
  10130. set: function set(newLevel) {
  10131. var levels = this._levels;
  10132. if (levels.length === 0) {
  10133. return;
  10134. }
  10135. // check if level idx is valid
  10136. if (newLevel < 0 || newLevel >= levels.length) {
  10137. // invalid level id given, trigger error
  10138. var error = new Error('invalid level idx');
  10139. var fatal = newLevel < 0;
  10140. this.hls.trigger(Events.ERROR, {
  10141. type: ErrorTypes.OTHER_ERROR,
  10142. details: ErrorDetails.LEVEL_SWITCH_ERROR,
  10143. level: newLevel,
  10144. fatal: fatal,
  10145. error: error,
  10146. reason: error.message
  10147. });
  10148. if (fatal) {
  10149. return;
  10150. }
  10151. newLevel = Math.min(newLevel, levels.length - 1);
  10152. }
  10153. var lastLevelIndex = this.currentLevelIndex;
  10154. var lastLevel = this.currentLevel;
  10155. var lastPathwayId = lastLevel ? lastLevel.attrs['PATHWAY-ID'] : undefined;
  10156. var level = levels[newLevel];
  10157. var pathwayId = level.attrs['PATHWAY-ID'];
  10158. this.currentLevelIndex = newLevel;
  10159. this.currentLevel = level;
  10160. if (lastLevelIndex === newLevel && level.details && lastLevel && lastPathwayId === pathwayId) {
  10161. return;
  10162. }
  10163. 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 : ''));
  10164. var levelSwitchingData = {
  10165. level: newLevel,
  10166. attrs: level.attrs,
  10167. details: level.details,
  10168. bitrate: level.bitrate,
  10169. averageBitrate: level.averageBitrate,
  10170. maxBitrate: level.maxBitrate,
  10171. realBitrate: level.realBitrate,
  10172. width: level.width,
  10173. height: level.height,
  10174. codecSet: level.codecSet,
  10175. audioCodec: level.audioCodec,
  10176. videoCodec: level.videoCodec,
  10177. audioGroups: level.audioGroups,
  10178. subtitleGroups: level.subtitleGroups,
  10179. loaded: level.loaded,
  10180. loadError: level.loadError,
  10181. fragmentError: level.fragmentError,
  10182. name: level.name,
  10183. id: level.id,
  10184. uri: level.uri,
  10185. url: level.url,
  10186. urlId: 0,
  10187. audioGroupIds: level.audioGroupIds,
  10188. textGroupIds: level.textGroupIds
  10189. };
  10190. this.hls.trigger(Events.LEVEL_SWITCHING, levelSwitchingData);
  10191. // check if we need to load playlist for this level
  10192. var levelDetails = level.details;
  10193. if (!levelDetails || levelDetails.live) {
  10194. // level not retrieved yet, or live playlist we need to (re)load it
  10195. var hlsUrlParameters = this.switchParams(level.uri, lastLevel == null ? void 0 : lastLevel.details, levelDetails);
  10196. this.loadPlaylist(hlsUrlParameters);
  10197. }
  10198. }
  10199. }, {
  10200. key: "manualLevel",
  10201. get: function get() {
  10202. return this.manualLevelIndex;
  10203. },
  10204. set: function set(newLevel) {
  10205. this.manualLevelIndex = newLevel;
  10206. if (this._startLevel === undefined) {
  10207. this._startLevel = newLevel;
  10208. }
  10209. if (newLevel !== -1) {
  10210. this.level = newLevel;
  10211. }
  10212. }
  10213. }, {
  10214. key: "firstLevel",
  10215. get: function get() {
  10216. return this._firstLevel;
  10217. },
  10218. set: function set(newLevel) {
  10219. this._firstLevel = newLevel;
  10220. }
  10221. }, {
  10222. key: "startLevel",
  10223. get: function get() {
  10224. // Setting hls.startLevel (this._startLevel) overrides config.startLevel
  10225. if (this._startLevel === undefined) {
  10226. var configStartLevel = this.hls.config.startLevel;
  10227. if (configStartLevel !== undefined) {
  10228. return configStartLevel;
  10229. }
  10230. return this.hls.firstAutoLevel;
  10231. }
  10232. return this._startLevel;
  10233. },
  10234. set: function set(newLevel) {
  10235. this._startLevel = newLevel;
  10236. }
  10237. }, {
  10238. key: "nextLoadLevel",
  10239. get: function get() {
  10240. if (this.manualLevelIndex !== -1) {
  10241. return this.manualLevelIndex;
  10242. } else {
  10243. return this.hls.nextAutoLevel;
  10244. }
  10245. },
  10246. set: function set(nextLevel) {
  10247. this.level = nextLevel;
  10248. if (this.manualLevelIndex === -1) {
  10249. this.hls.nextAutoLevel = nextLevel;
  10250. }
  10251. }
  10252. }]);
  10253. return LevelController;
  10254. }(BasePlaylistController);
  10255. function assignTrackIdsByGroup(tracks) {
  10256. var groups = {};
  10257. tracks.forEach(function (track) {
  10258. var groupId = track.groupId || '';
  10259. track.id = groups[groupId] = groups[groupId] || 0;
  10260. groups[groupId]++;
  10261. });
  10262. }
  10263. var FragmentState = {
  10264. NOT_LOADED: "NOT_LOADED",
  10265. APPENDING: "APPENDING",
  10266. PARTIAL: "PARTIAL",
  10267. OK: "OK"
  10268. };
  10269. var FragmentTracker = /*#__PURE__*/function () {
  10270. function FragmentTracker(hls) {
  10271. this.activePartLists = Object.create(null);
  10272. this.endListFragments = Object.create(null);
  10273. this.fragments = Object.create(null);
  10274. this.timeRanges = Object.create(null);
  10275. this.bufferPadding = 0.2;
  10276. this.hls = void 0;
  10277. this.hasGaps = false;
  10278. this.hls = hls;
  10279. this._registerListeners();
  10280. }
  10281. var _proto = FragmentTracker.prototype;
  10282. _proto._registerListeners = function _registerListeners() {
  10283. var hls = this.hls;
  10284. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  10285. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  10286. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  10287. };
  10288. _proto._unregisterListeners = function _unregisterListeners() {
  10289. var hls = this.hls;
  10290. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  10291. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  10292. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  10293. };
  10294. _proto.destroy = function destroy() {
  10295. this._unregisterListeners();
  10296. // @ts-ignore
  10297. this.fragments =
  10298. // @ts-ignore
  10299. this.activePartLists =
  10300. // @ts-ignore
  10301. this.endListFragments = this.timeRanges = null;
  10302. }
  10303. /**
  10304. * Return a Fragment or Part with an appended range that matches the position and levelType
  10305. * Otherwise, return null
  10306. */;
  10307. _proto.getAppendedFrag = function getAppendedFrag(position, levelType) {
  10308. var activeParts = this.activePartLists[levelType];
  10309. if (activeParts) {
  10310. for (var i = activeParts.length; i--;) {
  10311. var activePart = activeParts[i];
  10312. if (!activePart) {
  10313. break;
  10314. }
  10315. var appendedPTS = activePart.end;
  10316. if (activePart.start <= position && appendedPTS !== null && position <= appendedPTS) {
  10317. return activePart;
  10318. }
  10319. }
  10320. }
  10321. return this.getBufferedFrag(position, levelType);
  10322. }
  10323. /**
  10324. * Return a buffered Fragment that matches the position and levelType.
  10325. * A buffered Fragment is one whose loading, parsing and appending is done (completed or "partial" meaning aborted).
  10326. * If not found any Fragment, return null
  10327. */;
  10328. _proto.getBufferedFrag = function getBufferedFrag(position, levelType) {
  10329. var fragments = this.fragments;
  10330. var keys = Object.keys(fragments);
  10331. for (var i = keys.length; i--;) {
  10332. var fragmentEntity = fragments[keys[i]];
  10333. if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === levelType && fragmentEntity.buffered) {
  10334. var frag = fragmentEntity.body;
  10335. if (frag.start <= position && position <= frag.end) {
  10336. return frag;
  10337. }
  10338. }
  10339. }
  10340. return null;
  10341. }
  10342. /**
  10343. * Partial fragments effected by coded frame eviction will be removed
  10344. * The browser will unload parts of the buffer to free up memory for new buffer data
  10345. * 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)
  10346. */;
  10347. _proto.detectEvictedFragments = function detectEvictedFragments(elementaryStream, timeRange, playlistType, appendedPart) {
  10348. var _this = this;
  10349. if (this.timeRanges) {
  10350. this.timeRanges[elementaryStream] = timeRange;
  10351. }
  10352. // Check if any flagged fragments have been unloaded
  10353. // excluding anything newer than appendedPartSn
  10354. var appendedPartSn = (appendedPart == null ? void 0 : appendedPart.fragment.sn) || -1;
  10355. Object.keys(this.fragments).forEach(function (key) {
  10356. var fragmentEntity = _this.fragments[key];
  10357. if (!fragmentEntity) {
  10358. return;
  10359. }
  10360. if (appendedPartSn >= fragmentEntity.body.sn) {
  10361. return;
  10362. }
  10363. if (!fragmentEntity.buffered && !fragmentEntity.loaded) {
  10364. if (fragmentEntity.body.type === playlistType) {
  10365. _this.removeFragment(fragmentEntity.body);
  10366. }
  10367. return;
  10368. }
  10369. var esData = fragmentEntity.range[elementaryStream];
  10370. if (!esData) {
  10371. return;
  10372. }
  10373. esData.time.some(function (time) {
  10374. var isNotBuffered = !_this.isTimeBuffered(time.startPTS, time.endPTS, timeRange);
  10375. if (isNotBuffered) {
  10376. // Unregister partial fragment as it needs to load again to be reused
  10377. _this.removeFragment(fragmentEntity.body);
  10378. }
  10379. return isNotBuffered;
  10380. });
  10381. });
  10382. }
  10383. /**
  10384. * Checks if the fragment passed in is loaded in the buffer properly
  10385. * Partially loaded fragments will be registered as a partial fragment
  10386. */;
  10387. _proto.detectPartialFragments = function detectPartialFragments(data) {
  10388. var _this2 = this;
  10389. var timeRanges = this.timeRanges;
  10390. var frag = data.frag,
  10391. part = data.part;
  10392. if (!timeRanges || frag.sn === 'initSegment') {
  10393. return;
  10394. }
  10395. var fragKey = getFragmentKey(frag);
  10396. var fragmentEntity = this.fragments[fragKey];
  10397. if (!fragmentEntity || fragmentEntity.buffered && frag.gap) {
  10398. return;
  10399. }
  10400. var isFragHint = !frag.relurl;
  10401. Object.keys(timeRanges).forEach(function (elementaryStream) {
  10402. var streamInfo = frag.elementaryStreams[elementaryStream];
  10403. if (!streamInfo) {
  10404. return;
  10405. }
  10406. var timeRange = timeRanges[elementaryStream];
  10407. var partial = isFragHint || streamInfo.partial === true;
  10408. fragmentEntity.range[elementaryStream] = _this2.getBufferedTimes(frag, part, partial, timeRange);
  10409. });
  10410. fragmentEntity.loaded = null;
  10411. if (Object.keys(fragmentEntity.range).length) {
  10412. fragmentEntity.buffered = true;
  10413. var endList = fragmentEntity.body.endList = frag.endList || fragmentEntity.body.endList;
  10414. if (endList) {
  10415. this.endListFragments[fragmentEntity.body.type] = fragmentEntity;
  10416. }
  10417. if (!isPartial(fragmentEntity)) {
  10418. // Remove older fragment parts from lookup after frag is tracked as buffered
  10419. this.removeParts(frag.sn - 1, frag.type);
  10420. }
  10421. } else {
  10422. // remove fragment if nothing was appended
  10423. this.removeFragment(fragmentEntity.body);
  10424. }
  10425. };
  10426. _proto.removeParts = function removeParts(snToKeep, levelType) {
  10427. var activeParts = this.activePartLists[levelType];
  10428. if (!activeParts) {
  10429. return;
  10430. }
  10431. this.activePartLists[levelType] = activeParts.filter(function (part) {
  10432. return part.fragment.sn >= snToKeep;
  10433. });
  10434. };
  10435. _proto.fragBuffered = function fragBuffered(frag, force) {
  10436. var fragKey = getFragmentKey(frag);
  10437. var fragmentEntity = this.fragments[fragKey];
  10438. if (!fragmentEntity && force) {
  10439. fragmentEntity = this.fragments[fragKey] = {
  10440. body: frag,
  10441. appendedPTS: null,
  10442. loaded: null,
  10443. buffered: false,
  10444. range: Object.create(null)
  10445. };
  10446. if (frag.gap) {
  10447. this.hasGaps = true;
  10448. }
  10449. }
  10450. if (fragmentEntity) {
  10451. fragmentEntity.loaded = null;
  10452. fragmentEntity.buffered = true;
  10453. }
  10454. };
  10455. _proto.getBufferedTimes = function getBufferedTimes(fragment, part, partial, timeRange) {
  10456. var buffered = {
  10457. time: [],
  10458. partial: partial
  10459. };
  10460. var startPTS = fragment.start;
  10461. var endPTS = fragment.end;
  10462. var minEndPTS = fragment.minEndPTS || endPTS;
  10463. var maxStartPTS = fragment.maxStartPTS || startPTS;
  10464. for (var i = 0; i < timeRange.length; i++) {
  10465. var startTime = timeRange.start(i) - this.bufferPadding;
  10466. var endTime = timeRange.end(i) + this.bufferPadding;
  10467. if (maxStartPTS >= startTime && minEndPTS <= endTime) {
  10468. // Fragment is entirely contained in buffer
  10469. // No need to check the other timeRange times since it's completely playable
  10470. buffered.time.push({
  10471. startPTS: Math.max(startPTS, timeRange.start(i)),
  10472. endPTS: Math.min(endPTS, timeRange.end(i))
  10473. });
  10474. break;
  10475. } else if (startPTS < endTime && endPTS > startTime) {
  10476. var start = Math.max(startPTS, timeRange.start(i));
  10477. var end = Math.min(endPTS, timeRange.end(i));
  10478. if (end > start) {
  10479. buffered.partial = true;
  10480. // Check for intersection with buffer
  10481. // Get playable sections of the fragment
  10482. buffered.time.push({
  10483. startPTS: start,
  10484. endPTS: end
  10485. });
  10486. }
  10487. } else if (endPTS <= startTime) {
  10488. // No need to check the rest of the timeRange as it is in order
  10489. break;
  10490. }
  10491. }
  10492. return buffered;
  10493. }
  10494. /**
  10495. * Gets the partial fragment for a certain time
  10496. */;
  10497. _proto.getPartialFragment = function getPartialFragment(time) {
  10498. var bestFragment = null;
  10499. var timePadding;
  10500. var startTime;
  10501. var endTime;
  10502. var bestOverlap = 0;
  10503. var bufferPadding = this.bufferPadding,
  10504. fragments = this.fragments;
  10505. Object.keys(fragments).forEach(function (key) {
  10506. var fragmentEntity = fragments[key];
  10507. if (!fragmentEntity) {
  10508. return;
  10509. }
  10510. if (isPartial(fragmentEntity)) {
  10511. startTime = fragmentEntity.body.start - bufferPadding;
  10512. endTime = fragmentEntity.body.end + bufferPadding;
  10513. if (time >= startTime && time <= endTime) {
  10514. // Use the fragment that has the most padding from start and end time
  10515. timePadding = Math.min(time - startTime, endTime - time);
  10516. if (bestOverlap <= timePadding) {
  10517. bestFragment = fragmentEntity.body;
  10518. bestOverlap = timePadding;
  10519. }
  10520. }
  10521. }
  10522. });
  10523. return bestFragment;
  10524. };
  10525. _proto.isEndListAppended = function isEndListAppended(type) {
  10526. var lastFragmentEntity = this.endListFragments[type];
  10527. return lastFragmentEntity !== undefined && (lastFragmentEntity.buffered || isPartial(lastFragmentEntity));
  10528. };
  10529. _proto.getState = function getState(fragment) {
  10530. var fragKey = getFragmentKey(fragment);
  10531. var fragmentEntity = this.fragments[fragKey];
  10532. if (fragmentEntity) {
  10533. if (!fragmentEntity.buffered) {
  10534. return FragmentState.APPENDING;
  10535. } else if (isPartial(fragmentEntity)) {
  10536. return FragmentState.PARTIAL;
  10537. } else {
  10538. return FragmentState.OK;
  10539. }
  10540. }
  10541. return FragmentState.NOT_LOADED;
  10542. };
  10543. _proto.isTimeBuffered = function isTimeBuffered(startPTS, endPTS, timeRange) {
  10544. var startTime;
  10545. var endTime;
  10546. for (var i = 0; i < timeRange.length; i++) {
  10547. startTime = timeRange.start(i) - this.bufferPadding;
  10548. endTime = timeRange.end(i) + this.bufferPadding;
  10549. if (startPTS >= startTime && endPTS <= endTime) {
  10550. return true;
  10551. }
  10552. if (endPTS <= startTime) {
  10553. // No need to check the rest of the timeRange as it is in order
  10554. return false;
  10555. }
  10556. }
  10557. return false;
  10558. };
  10559. _proto.onFragLoaded = function onFragLoaded(event, data) {
  10560. var frag = data.frag,
  10561. part = data.part;
  10562. // don't track initsegment (for which sn is not a number)
  10563. // don't track frags used for bitrateTest, they're irrelevant.
  10564. if (frag.sn === 'initSegment' || frag.bitrateTest) {
  10565. return;
  10566. }
  10567. // Fragment entity `loaded` FragLoadedData is null when loading parts
  10568. var loaded = part ? null : data;
  10569. var fragKey = getFragmentKey(frag);
  10570. this.fragments[fragKey] = {
  10571. body: frag,
  10572. appendedPTS: null,
  10573. loaded: loaded,
  10574. buffered: false,
  10575. range: Object.create(null)
  10576. };
  10577. };
  10578. _proto.onBufferAppended = function onBufferAppended(event, data) {
  10579. var _this3 = this;
  10580. var frag = data.frag,
  10581. part = data.part,
  10582. timeRanges = data.timeRanges;
  10583. if (frag.sn === 'initSegment') {
  10584. return;
  10585. }
  10586. var playlistType = frag.type;
  10587. if (part) {
  10588. var activeParts = this.activePartLists[playlistType];
  10589. if (!activeParts) {
  10590. this.activePartLists[playlistType] = activeParts = [];
  10591. }
  10592. activeParts.push(part);
  10593. }
  10594. // Store the latest timeRanges loaded in the buffer
  10595. this.timeRanges = timeRanges;
  10596. Object.keys(timeRanges).forEach(function (elementaryStream) {
  10597. var timeRange = timeRanges[elementaryStream];
  10598. _this3.detectEvictedFragments(elementaryStream, timeRange, playlistType, part);
  10599. });
  10600. };
  10601. _proto.onFragBuffered = function onFragBuffered(event, data) {
  10602. this.detectPartialFragments(data);
  10603. };
  10604. _proto.hasFragment = function hasFragment(fragment) {
  10605. var fragKey = getFragmentKey(fragment);
  10606. return !!this.fragments[fragKey];
  10607. };
  10608. _proto.hasParts = function hasParts(type) {
  10609. var _this$activePartLists;
  10610. return !!((_this$activePartLists = this.activePartLists[type]) != null && _this$activePartLists.length);
  10611. };
  10612. _proto.removeFragmentsInRange = function removeFragmentsInRange(start, end, playlistType, withGapOnly, unbufferedOnly) {
  10613. var _this4 = this;
  10614. if (withGapOnly && !this.hasGaps) {
  10615. return;
  10616. }
  10617. Object.keys(this.fragments).forEach(function (key) {
  10618. var fragmentEntity = _this4.fragments[key];
  10619. if (!fragmentEntity) {
  10620. return;
  10621. }
  10622. var frag = fragmentEntity.body;
  10623. if (frag.type !== playlistType || withGapOnly && !frag.gap) {
  10624. return;
  10625. }
  10626. if (frag.start < end && frag.end > start && (fragmentEntity.buffered || unbufferedOnly)) {
  10627. _this4.removeFragment(frag);
  10628. }
  10629. });
  10630. };
  10631. _proto.removeFragment = function removeFragment(fragment) {
  10632. var fragKey = getFragmentKey(fragment);
  10633. fragment.stats.loaded = 0;
  10634. fragment.clearElementaryStreamInfo();
  10635. var activeParts = this.activePartLists[fragment.type];
  10636. if (activeParts) {
  10637. var snToRemove = fragment.sn;
  10638. this.activePartLists[fragment.type] = activeParts.filter(function (part) {
  10639. return part.fragment.sn !== snToRemove;
  10640. });
  10641. }
  10642. delete this.fragments[fragKey];
  10643. if (fragment.endList) {
  10644. delete this.endListFragments[fragment.type];
  10645. }
  10646. };
  10647. _proto.removeAllFragments = function removeAllFragments() {
  10648. this.fragments = Object.create(null);
  10649. this.endListFragments = Object.create(null);
  10650. this.activePartLists = Object.create(null);
  10651. this.hasGaps = false;
  10652. };
  10653. return FragmentTracker;
  10654. }();
  10655. function isPartial(fragmentEntity) {
  10656. var _fragmentEntity$range, _fragmentEntity$range2, _fragmentEntity$range3;
  10657. 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));
  10658. }
  10659. function getFragmentKey(fragment) {
  10660. return fragment.type + "_" + fragment.level + "_" + fragment.sn;
  10661. }
  10662. var MIN_CHUNK_SIZE = Math.pow(2, 17); // 128kb
  10663. var FragmentLoader = /*#__PURE__*/function () {
  10664. function FragmentLoader(config) {
  10665. this.config = void 0;
  10666. this.loader = null;
  10667. this.partLoadTimeout = -1;
  10668. this.config = config;
  10669. }
  10670. var _proto = FragmentLoader.prototype;
  10671. _proto.destroy = function destroy() {
  10672. if (this.loader) {
  10673. this.loader.destroy();
  10674. this.loader = null;
  10675. }
  10676. };
  10677. _proto.abort = function abort() {
  10678. if (this.loader) {
  10679. // Abort the loader for current fragment. Only one may load at any given time
  10680. this.loader.abort();
  10681. }
  10682. };
  10683. _proto.load = function load(frag, _onProgress) {
  10684. var _this = this;
  10685. var url = frag.url;
  10686. if (!url) {
  10687. return Promise.reject(new LoadError({
  10688. type: ErrorTypes.NETWORK_ERROR,
  10689. details: ErrorDetails.FRAG_LOAD_ERROR,
  10690. fatal: false,
  10691. frag: frag,
  10692. error: new Error("Fragment does not have a " + (url ? 'part list' : 'url')),
  10693. networkDetails: null
  10694. }));
  10695. }
  10696. this.abort();
  10697. var config = this.config;
  10698. var FragmentILoader = config.fLoader;
  10699. var DefaultILoader = config.loader;
  10700. return new Promise(function (resolve, reject) {
  10701. if (_this.loader) {
  10702. _this.loader.destroy();
  10703. }
  10704. if (frag.gap) {
  10705. if (frag.tagList.some(function (tags) {
  10706. return tags[0] === 'GAP';
  10707. })) {
  10708. reject(createGapLoadError(frag));
  10709. return;
  10710. } else {
  10711. // Reset temporary treatment as GAP tag
  10712. frag.gap = false;
  10713. }
  10714. }
  10715. var loader = _this.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  10716. var loaderContext = createLoaderContext(frag);
  10717. var loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
  10718. var loaderConfig = {
  10719. loadPolicy: loadPolicy,
  10720. timeout: loadPolicy.maxLoadTimeMs,
  10721. maxRetry: 0,
  10722. retryDelay: 0,
  10723. maxRetryDelay: 0,
  10724. highWaterMark: frag.sn === 'initSegment' ? Infinity : MIN_CHUNK_SIZE
  10725. };
  10726. // Assign frag stats to the loader's stats reference
  10727. frag.stats = loader.stats;
  10728. loader.load(loaderContext, loaderConfig, {
  10729. onSuccess: function onSuccess(response, stats, context, networkDetails) {
  10730. _this.resetLoader(frag, loader);
  10731. var payload = response.data;
  10732. if (context.resetIV && frag.decryptdata) {
  10733. frag.decryptdata.iv = new Uint8Array(payload.slice(0, 16));
  10734. payload = payload.slice(16);
  10735. }
  10736. resolve({
  10737. frag: frag,
  10738. part: null,
  10739. payload: payload,
  10740. networkDetails: networkDetails
  10741. });
  10742. },
  10743. onError: function onError(response, context, networkDetails, stats) {
  10744. _this.resetLoader(frag, loader);
  10745. reject(new LoadError({
  10746. type: ErrorTypes.NETWORK_ERROR,
  10747. details: ErrorDetails.FRAG_LOAD_ERROR,
  10748. fatal: false,
  10749. frag: frag,
  10750. response: _objectSpread2({
  10751. url: url,
  10752. data: undefined
  10753. }, response),
  10754. error: new Error("HTTP Error " + response.code + " " + response.text),
  10755. networkDetails: networkDetails,
  10756. stats: stats
  10757. }));
  10758. },
  10759. onAbort: function onAbort(stats, context, networkDetails) {
  10760. _this.resetLoader(frag, loader);
  10761. reject(new LoadError({
  10762. type: ErrorTypes.NETWORK_ERROR,
  10763. details: ErrorDetails.INTERNAL_ABORTED,
  10764. fatal: false,
  10765. frag: frag,
  10766. error: new Error('Aborted'),
  10767. networkDetails: networkDetails,
  10768. stats: stats
  10769. }));
  10770. },
  10771. onTimeout: function onTimeout(stats, context, networkDetails) {
  10772. _this.resetLoader(frag, loader);
  10773. reject(new LoadError({
  10774. type: ErrorTypes.NETWORK_ERROR,
  10775. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  10776. fatal: false,
  10777. frag: frag,
  10778. error: new Error("Timeout after " + loaderConfig.timeout + "ms"),
  10779. networkDetails: networkDetails,
  10780. stats: stats
  10781. }));
  10782. },
  10783. onProgress: function onProgress(stats, context, data, networkDetails) {
  10784. if (_onProgress) {
  10785. _onProgress({
  10786. frag: frag,
  10787. part: null,
  10788. payload: data,
  10789. networkDetails: networkDetails
  10790. });
  10791. }
  10792. }
  10793. });
  10794. });
  10795. };
  10796. _proto.loadPart = function loadPart(frag, part, onProgress) {
  10797. var _this2 = this;
  10798. this.abort();
  10799. var config = this.config;
  10800. var FragmentILoader = config.fLoader;
  10801. var DefaultILoader = config.loader;
  10802. return new Promise(function (resolve, reject) {
  10803. if (_this2.loader) {
  10804. _this2.loader.destroy();
  10805. }
  10806. if (frag.gap || part.gap) {
  10807. reject(createGapLoadError(frag, part));
  10808. return;
  10809. }
  10810. var loader = _this2.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  10811. var loaderContext = createLoaderContext(frag, part);
  10812. // Should we define another load policy for parts?
  10813. var loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
  10814. var loaderConfig = {
  10815. loadPolicy: loadPolicy,
  10816. timeout: loadPolicy.maxLoadTimeMs,
  10817. maxRetry: 0,
  10818. retryDelay: 0,
  10819. maxRetryDelay: 0,
  10820. highWaterMark: MIN_CHUNK_SIZE
  10821. };
  10822. // Assign part stats to the loader's stats reference
  10823. part.stats = loader.stats;
  10824. loader.load(loaderContext, loaderConfig, {
  10825. onSuccess: function onSuccess(response, stats, context, networkDetails) {
  10826. _this2.resetLoader(frag, loader);
  10827. _this2.updateStatsFromPart(frag, part);
  10828. var partLoadedData = {
  10829. frag: frag,
  10830. part: part,
  10831. payload: response.data,
  10832. networkDetails: networkDetails
  10833. };
  10834. onProgress(partLoadedData);
  10835. resolve(partLoadedData);
  10836. },
  10837. onError: function onError(response, context, networkDetails, stats) {
  10838. _this2.resetLoader(frag, loader);
  10839. reject(new LoadError({
  10840. type: ErrorTypes.NETWORK_ERROR,
  10841. details: ErrorDetails.FRAG_LOAD_ERROR,
  10842. fatal: false,
  10843. frag: frag,
  10844. part: part,
  10845. response: _objectSpread2({
  10846. url: loaderContext.url,
  10847. data: undefined
  10848. }, response),
  10849. error: new Error("HTTP Error " + response.code + " " + response.text),
  10850. networkDetails: networkDetails,
  10851. stats: stats
  10852. }));
  10853. },
  10854. onAbort: function onAbort(stats, context, networkDetails) {
  10855. frag.stats.aborted = part.stats.aborted;
  10856. _this2.resetLoader(frag, loader);
  10857. reject(new LoadError({
  10858. type: ErrorTypes.NETWORK_ERROR,
  10859. details: ErrorDetails.INTERNAL_ABORTED,
  10860. fatal: false,
  10861. frag: frag,
  10862. part: part,
  10863. error: new Error('Aborted'),
  10864. networkDetails: networkDetails,
  10865. stats: stats
  10866. }));
  10867. },
  10868. onTimeout: function onTimeout(stats, context, networkDetails) {
  10869. _this2.resetLoader(frag, loader);
  10870. reject(new LoadError({
  10871. type: ErrorTypes.NETWORK_ERROR,
  10872. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  10873. fatal: false,
  10874. frag: frag,
  10875. part: part,
  10876. error: new Error("Timeout after " + loaderConfig.timeout + "ms"),
  10877. networkDetails: networkDetails,
  10878. stats: stats
  10879. }));
  10880. }
  10881. });
  10882. });
  10883. };
  10884. _proto.updateStatsFromPart = function updateStatsFromPart(frag, part) {
  10885. var fragStats = frag.stats;
  10886. var partStats = part.stats;
  10887. var partTotal = partStats.total;
  10888. fragStats.loaded += partStats.loaded;
  10889. if (partTotal) {
  10890. var estTotalParts = Math.round(frag.duration / part.duration);
  10891. var estLoadedParts = Math.min(Math.round(fragStats.loaded / partTotal), estTotalParts);
  10892. var estRemainingParts = estTotalParts - estLoadedParts;
  10893. var estRemainingBytes = estRemainingParts * Math.round(fragStats.loaded / estLoadedParts);
  10894. fragStats.total = fragStats.loaded + estRemainingBytes;
  10895. } else {
  10896. fragStats.total = Math.max(fragStats.loaded, fragStats.total);
  10897. }
  10898. var fragLoading = fragStats.loading;
  10899. var partLoading = partStats.loading;
  10900. if (fragLoading.start) {
  10901. // add to fragment loader latency
  10902. fragLoading.first += partLoading.first - partLoading.start;
  10903. } else {
  10904. fragLoading.start = partLoading.start;
  10905. fragLoading.first = partLoading.first;
  10906. }
  10907. fragLoading.end = partLoading.end;
  10908. };
  10909. _proto.resetLoader = function resetLoader(frag, loader) {
  10910. frag.loader = null;
  10911. if (this.loader === loader) {
  10912. self.clearTimeout(this.partLoadTimeout);
  10913. this.loader = null;
  10914. }
  10915. loader.destroy();
  10916. };
  10917. return FragmentLoader;
  10918. }();
  10919. function createLoaderContext(frag, part) {
  10920. if (part === void 0) {
  10921. part = null;
  10922. }
  10923. var segment = part || frag;
  10924. var loaderContext = {
  10925. frag: frag,
  10926. part: part,
  10927. responseType: 'arraybuffer',
  10928. url: segment.url,
  10929. headers: {},
  10930. rangeStart: 0,
  10931. rangeEnd: 0
  10932. };
  10933. var start = segment.byteRangeStartOffset;
  10934. var end = segment.byteRangeEndOffset;
  10935. if (isFiniteNumber(start) && isFiniteNumber(end)) {
  10936. var _frag$decryptdata;
  10937. var byteRangeStart = start;
  10938. var byteRangeEnd = end;
  10939. if (frag.sn === 'initSegment' && ((_frag$decryptdata = frag.decryptdata) == null ? void 0 : _frag$decryptdata.method) === 'AES-128') {
  10940. // MAP segment encrypted with method 'AES-128', when served with HTTP Range,
  10941. // has the unencrypted size specified in the range.
  10942. // Ref: https://tools.ietf.org/html/draft-pantos-hls-rfc8216bis-08#section-6.3.6
  10943. var fragmentLen = end - start;
  10944. if (fragmentLen % 16) {
  10945. byteRangeEnd = end + (16 - fragmentLen % 16);
  10946. }
  10947. if (start !== 0) {
  10948. loaderContext.resetIV = true;
  10949. byteRangeStart = start - 16;
  10950. }
  10951. }
  10952. loaderContext.rangeStart = byteRangeStart;
  10953. loaderContext.rangeEnd = byteRangeEnd;
  10954. }
  10955. return loaderContext;
  10956. }
  10957. function createGapLoadError(frag, part) {
  10958. var error = new Error("GAP " + (frag.gap ? 'tag' : 'attribute') + " found");
  10959. var errorData = {
  10960. type: ErrorTypes.MEDIA_ERROR,
  10961. details: ErrorDetails.FRAG_GAP,
  10962. fatal: false,
  10963. frag: frag,
  10964. error: error,
  10965. networkDetails: null
  10966. };
  10967. if (part) {
  10968. errorData.part = part;
  10969. }
  10970. (part ? part : frag).stats.aborted = true;
  10971. return new LoadError(errorData);
  10972. }
  10973. var LoadError = /*#__PURE__*/function (_Error) {
  10974. _inheritsLoose(LoadError, _Error);
  10975. function LoadError(data) {
  10976. var _this3;
  10977. _this3 = _Error.call(this, data.error.message) || this;
  10978. _this3.data = void 0;
  10979. _this3.data = data;
  10980. return _this3;
  10981. }
  10982. return LoadError;
  10983. }( /*#__PURE__*/_wrapNativeSuper(Error));
  10984. var KeyLoader = /*#__PURE__*/function () {
  10985. function KeyLoader(config) {
  10986. this.config = void 0;
  10987. this.keyUriToKeyInfo = {};
  10988. this.emeController = null;
  10989. this.config = config;
  10990. }
  10991. var _proto = KeyLoader.prototype;
  10992. _proto.abort = function abort(type) {
  10993. for (var uri in this.keyUriToKeyInfo) {
  10994. var loader = this.keyUriToKeyInfo[uri].loader;
  10995. if (loader) {
  10996. var _loader$context;
  10997. if (type && type !== ((_loader$context = loader.context) == null ? void 0 : _loader$context.frag.type)) {
  10998. return;
  10999. }
  11000. loader.abort();
  11001. }
  11002. }
  11003. };
  11004. _proto.detach = function detach() {
  11005. for (var uri in this.keyUriToKeyInfo) {
  11006. var keyInfo = this.keyUriToKeyInfo[uri];
  11007. // Remove cached EME keys on detach
  11008. if (keyInfo.mediaKeySessionContext || keyInfo.decryptdata.isCommonEncryption) {
  11009. delete this.keyUriToKeyInfo[uri];
  11010. }
  11011. }
  11012. };
  11013. _proto.destroy = function destroy() {
  11014. this.detach();
  11015. for (var uri in this.keyUriToKeyInfo) {
  11016. var loader = this.keyUriToKeyInfo[uri].loader;
  11017. if (loader) {
  11018. loader.destroy();
  11019. }
  11020. }
  11021. this.keyUriToKeyInfo = {};
  11022. };
  11023. _proto.createKeyLoadError = function createKeyLoadError(frag, details, error, networkDetails, response) {
  11024. if (details === void 0) {
  11025. details = ErrorDetails.KEY_LOAD_ERROR;
  11026. }
  11027. return new LoadError({
  11028. type: ErrorTypes.NETWORK_ERROR,
  11029. details: details,
  11030. fatal: false,
  11031. frag: frag,
  11032. response: response,
  11033. error: error,
  11034. networkDetails: networkDetails
  11035. });
  11036. };
  11037. _proto.loadClear = function loadClear(loadingFrag, encryptedFragments) {
  11038. var _this = this;
  11039. if (this.emeController && this.config.emeEnabled) {
  11040. // access key-system with nearest key on start (loaidng frag is unencrypted)
  11041. var sn = loadingFrag.sn,
  11042. cc = loadingFrag.cc;
  11043. var _loop = function _loop() {
  11044. var frag = encryptedFragments[i];
  11045. if (cc <= frag.cc && (sn === 'initSegment' || frag.sn === 'initSegment' || sn < frag.sn)) {
  11046. _this.emeController.selectKeySystemFormat(frag).then(function (keySystemFormat) {
  11047. frag.setKeyFormat(keySystemFormat);
  11048. });
  11049. return 1; // break
  11050. }
  11051. };
  11052. for (var i = 0; i < encryptedFragments.length; i++) {
  11053. if (_loop()) break;
  11054. }
  11055. }
  11056. };
  11057. _proto.load = function load(frag) {
  11058. var _this2 = this;
  11059. if (!frag.decryptdata && frag.encrypted && this.emeController) {
  11060. // Multiple keys, but none selected, resolve in eme-controller
  11061. return this.emeController.selectKeySystemFormat(frag).then(function (keySystemFormat) {
  11062. return _this2.loadInternal(frag, keySystemFormat);
  11063. });
  11064. }
  11065. return this.loadInternal(frag);
  11066. };
  11067. _proto.loadInternal = function loadInternal(frag, keySystemFormat) {
  11068. var _keyInfo, _keyInfo2;
  11069. if (keySystemFormat) {
  11070. frag.setKeyFormat(keySystemFormat);
  11071. }
  11072. var decryptdata = frag.decryptdata;
  11073. if (!decryptdata) {
  11074. var error = new Error(keySystemFormat ? "Expected frag.decryptdata to be defined after setting format " + keySystemFormat : 'Missing decryption data on fragment in onKeyLoading');
  11075. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, error));
  11076. }
  11077. var uri = decryptdata.uri;
  11078. if (!uri) {
  11079. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error("Invalid key URI: \"" + uri + "\"")));
  11080. }
  11081. var keyInfo = this.keyUriToKeyInfo[uri];
  11082. if ((_keyInfo = keyInfo) != null && _keyInfo.decryptdata.key) {
  11083. decryptdata.key = keyInfo.decryptdata.key;
  11084. return Promise.resolve({
  11085. frag: frag,
  11086. keyInfo: keyInfo
  11087. });
  11088. }
  11089. // Return key load promise as long as it does not have a mediakey session with an unusable key status
  11090. if ((_keyInfo2 = keyInfo) != null && _keyInfo2.keyLoadPromise) {
  11091. var _keyInfo$mediaKeySess;
  11092. switch ((_keyInfo$mediaKeySess = keyInfo.mediaKeySessionContext) == null ? void 0 : _keyInfo$mediaKeySess.keyStatus) {
  11093. case undefined:
  11094. case 'status-pending':
  11095. case 'usable':
  11096. case 'usable-in-future':
  11097. return keyInfo.keyLoadPromise.then(function (keyLoadedData) {
  11098. // Return the correct fragment with updated decryptdata key and loaded keyInfo
  11099. decryptdata.key = keyLoadedData.keyInfo.decryptdata.key;
  11100. return {
  11101. frag: frag,
  11102. keyInfo: keyInfo
  11103. };
  11104. });
  11105. }
  11106. // If we have a key session and status and it is not pending or usable, continue
  11107. // This will go back to the eme-controller for expired keys to get a new keyLoadPromise
  11108. }
  11109. // Load the key or return the loading promise
  11110. keyInfo = this.keyUriToKeyInfo[uri] = {
  11111. decryptdata: decryptdata,
  11112. keyLoadPromise: null,
  11113. loader: null,
  11114. mediaKeySessionContext: null
  11115. };
  11116. switch (decryptdata.method) {
  11117. case 'ISO-23001-7':
  11118. case 'SAMPLE-AES':
  11119. case 'SAMPLE-AES-CENC':
  11120. case 'SAMPLE-AES-CTR':
  11121. if (decryptdata.keyFormat === 'identity') {
  11122. // loadKeyHTTP handles http(s) and data URLs
  11123. return this.loadKeyHTTP(keyInfo, frag);
  11124. }
  11125. return this.loadKeyEME(keyInfo, frag);
  11126. case 'AES-128':
  11127. return this.loadKeyHTTP(keyInfo, frag);
  11128. default:
  11129. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error("Key supplied with unsupported METHOD: \"" + decryptdata.method + "\"")));
  11130. }
  11131. };
  11132. _proto.loadKeyEME = function loadKeyEME(keyInfo, frag) {
  11133. var keyLoadedData = {
  11134. frag: frag,
  11135. keyInfo: keyInfo
  11136. };
  11137. if (this.emeController && this.config.emeEnabled) {
  11138. var keySessionContextPromise = this.emeController.loadKey(keyLoadedData);
  11139. if (keySessionContextPromise) {
  11140. return (keyInfo.keyLoadPromise = keySessionContextPromise.then(function (keySessionContext) {
  11141. keyInfo.mediaKeySessionContext = keySessionContext;
  11142. return keyLoadedData;
  11143. })).catch(function (error) {
  11144. // Remove promise for license renewal or retry
  11145. keyInfo.keyLoadPromise = null;
  11146. throw error;
  11147. });
  11148. }
  11149. }
  11150. return Promise.resolve(keyLoadedData);
  11151. };
  11152. _proto.loadKeyHTTP = function loadKeyHTTP(keyInfo, frag) {
  11153. var _this3 = this;
  11154. var config = this.config;
  11155. var Loader = config.loader;
  11156. var keyLoader = new Loader(config);
  11157. frag.keyLoader = keyInfo.loader = keyLoader;
  11158. return keyInfo.keyLoadPromise = new Promise(function (resolve, reject) {
  11159. var loaderContext = {
  11160. keyInfo: keyInfo,
  11161. frag: frag,
  11162. responseType: 'arraybuffer',
  11163. url: keyInfo.decryptdata.uri
  11164. };
  11165. // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,
  11166. // key-loader will trigger an error and rely on stream-controller to handle retry logic.
  11167. // this will also align retry logic with fragment-loader
  11168. var loadPolicy = config.keyLoadPolicy.default;
  11169. var loaderConfig = {
  11170. loadPolicy: loadPolicy,
  11171. timeout: loadPolicy.maxLoadTimeMs,
  11172. maxRetry: 0,
  11173. retryDelay: 0,
  11174. maxRetryDelay: 0
  11175. };
  11176. var loaderCallbacks = {
  11177. onSuccess: function onSuccess(response, stats, context, networkDetails) {
  11178. var frag = context.frag,
  11179. keyInfo = context.keyInfo,
  11180. uri = context.url;
  11181. if (!frag.decryptdata || keyInfo !== _this3.keyUriToKeyInfo[uri]) {
  11182. return reject(_this3.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error('after key load, decryptdata unset or changed'), networkDetails));
  11183. }
  11184. keyInfo.decryptdata.key = frag.decryptdata.key = new Uint8Array(response.data);
  11185. // detach fragment key loader on load success
  11186. frag.keyLoader = null;
  11187. keyInfo.loader = null;
  11188. resolve({
  11189. frag: frag,
  11190. keyInfo: keyInfo
  11191. });
  11192. },
  11193. onError: function onError(response, context, networkDetails, stats) {
  11194. _this3.resetLoader(context);
  11195. reject(_this3.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error("HTTP Error " + response.code + " loading key " + response.text), networkDetails, _objectSpread2({
  11196. url: loaderContext.url,
  11197. data: undefined
  11198. }, response)));
  11199. },
  11200. onTimeout: function onTimeout(stats, context, networkDetails) {
  11201. _this3.resetLoader(context);
  11202. reject(_this3.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_TIMEOUT, new Error('key loading timed out'), networkDetails));
  11203. },
  11204. onAbort: function onAbort(stats, context, networkDetails) {
  11205. _this3.resetLoader(context);
  11206. reject(_this3.createKeyLoadError(frag, ErrorDetails.INTERNAL_ABORTED, new Error('key loading aborted'), networkDetails));
  11207. }
  11208. };
  11209. keyLoader.load(loaderContext, loaderConfig, loaderCallbacks);
  11210. });
  11211. };
  11212. _proto.resetLoader = function resetLoader(context) {
  11213. var frag = context.frag,
  11214. keyInfo = context.keyInfo,
  11215. uri = context.url;
  11216. var loader = keyInfo.loader;
  11217. if (frag.keyLoader === loader) {
  11218. frag.keyLoader = null;
  11219. keyInfo.loader = null;
  11220. }
  11221. delete this.keyUriToKeyInfo[uri];
  11222. if (loader) {
  11223. loader.destroy();
  11224. }
  11225. };
  11226. return KeyLoader;
  11227. }();
  11228. /**
  11229. * @ignore
  11230. * Sub-class specialization of EventHandler base class.
  11231. *
  11232. * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,
  11233. * scheduled asynchroneously, avoiding recursive calls in the same tick.
  11234. *
  11235. * The task itself is implemented in `doTick`. It can be requested and called for single execution
  11236. * using the `tick` method.
  11237. *
  11238. * It will be assured that the task execution method (`tick`) only gets called once per main loop "tick",
  11239. * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.
  11240. *
  11241. * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,
  11242. * and cancelled with `clearNextTick`.
  11243. *
  11244. * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).
  11245. *
  11246. * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.
  11247. *
  11248. * Further explanations:
  11249. *
  11250. * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously
  11251. * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.
  11252. *
  11253. * When the task execution (`tick` method) is called in re-entrant way this is detected and
  11254. * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further
  11255. * task processing on the next main loop iteration (also known as "next tick" in the Node/JS runtime lingo).
  11256. */
  11257. var TaskLoop = /*#__PURE__*/function () {
  11258. function TaskLoop() {
  11259. this._boundTick = void 0;
  11260. this._tickTimer = null;
  11261. this._tickInterval = null;
  11262. this._tickCallCount = 0;
  11263. this._boundTick = this.tick.bind(this);
  11264. }
  11265. var _proto = TaskLoop.prototype;
  11266. _proto.destroy = function destroy() {
  11267. this.onHandlerDestroying();
  11268. this.onHandlerDestroyed();
  11269. };
  11270. _proto.onHandlerDestroying = function onHandlerDestroying() {
  11271. // clear all timers before unregistering from event bus
  11272. this.clearNextTick();
  11273. this.clearInterval();
  11274. };
  11275. _proto.onHandlerDestroyed = function onHandlerDestroyed() {};
  11276. _proto.hasInterval = function hasInterval() {
  11277. return !!this._tickInterval;
  11278. };
  11279. _proto.hasNextTick = function hasNextTick() {
  11280. return !!this._tickTimer;
  11281. }
  11282. /**
  11283. * @param millis - Interval time (ms)
  11284. * @eturns True when interval has been scheduled, false when already scheduled (no effect)
  11285. */;
  11286. _proto.setInterval = function setInterval(millis) {
  11287. if (!this._tickInterval) {
  11288. this._tickCallCount = 0;
  11289. this._tickInterval = self.setInterval(this._boundTick, millis);
  11290. return true;
  11291. }
  11292. return false;
  11293. }
  11294. /**
  11295. * @returns True when interval was cleared, false when none was set (no effect)
  11296. */;
  11297. _proto.clearInterval = function clearInterval() {
  11298. if (this._tickInterval) {
  11299. self.clearInterval(this._tickInterval);
  11300. this._tickInterval = null;
  11301. return true;
  11302. }
  11303. return false;
  11304. }
  11305. /**
  11306. * @returns True when timeout was cleared, false when none was set (no effect)
  11307. */;
  11308. _proto.clearNextTick = function clearNextTick() {
  11309. if (this._tickTimer) {
  11310. self.clearTimeout(this._tickTimer);
  11311. this._tickTimer = null;
  11312. return true;
  11313. }
  11314. return false;
  11315. }
  11316. /**
  11317. * Will call the subclass doTick implementation in this main loop tick
  11318. * or in the next one (via setTimeout(,0)) in case it has already been called
  11319. * in this tick (in case this is a re-entrant call).
  11320. */;
  11321. _proto.tick = function tick() {
  11322. this._tickCallCount++;
  11323. if (this._tickCallCount === 1) {
  11324. this.doTick();
  11325. // re-entrant call to tick from previous doTick call stack
  11326. // -> schedule a call on the next main loop iteration to process this task processing request
  11327. if (this._tickCallCount > 1) {
  11328. // make sure only one timer exists at any time at max
  11329. this.tickImmediate();
  11330. }
  11331. this._tickCallCount = 0;
  11332. }
  11333. };
  11334. _proto.tickImmediate = function tickImmediate() {
  11335. this.clearNextTick();
  11336. this._tickTimer = self.setTimeout(this._boundTick, 0);
  11337. }
  11338. /**
  11339. * For subclass to implement task logic
  11340. * @abstract
  11341. */;
  11342. _proto.doTick = function doTick() {};
  11343. return TaskLoop;
  11344. }();
  11345. var ChunkMetadata = function ChunkMetadata(level, sn, id, size, part, partial) {
  11346. if (size === void 0) {
  11347. size = 0;
  11348. }
  11349. if (part === void 0) {
  11350. part = -1;
  11351. }
  11352. if (partial === void 0) {
  11353. partial = false;
  11354. }
  11355. this.level = void 0;
  11356. this.sn = void 0;
  11357. this.part = void 0;
  11358. this.id = void 0;
  11359. this.size = void 0;
  11360. this.partial = void 0;
  11361. this.transmuxing = getNewPerformanceTiming();
  11362. this.buffering = {
  11363. audio: getNewPerformanceTiming(),
  11364. video: getNewPerformanceTiming(),
  11365. audiovideo: getNewPerformanceTiming()
  11366. };
  11367. this.level = level;
  11368. this.sn = sn;
  11369. this.id = id;
  11370. this.size = size;
  11371. this.part = part;
  11372. this.partial = partial;
  11373. };
  11374. function getNewPerformanceTiming() {
  11375. return {
  11376. start: 0,
  11377. executeStart: 0,
  11378. executeEnd: 0,
  11379. end: 0
  11380. };
  11381. }
  11382. function findFirstFragWithCC(fragments, cc) {
  11383. for (var i = 0, len = fragments.length; i < len; i++) {
  11384. var _fragments$i;
  11385. if (((_fragments$i = fragments[i]) == null ? void 0 : _fragments$i.cc) === cc) {
  11386. return fragments[i];
  11387. }
  11388. }
  11389. return null;
  11390. }
  11391. function shouldAlignOnDiscontinuities(lastFrag, switchDetails, details) {
  11392. if (switchDetails) {
  11393. if (details.endCC > details.startCC || lastFrag && lastFrag.cc < details.startCC) {
  11394. return true;
  11395. }
  11396. }
  11397. return false;
  11398. }
  11399. // Find the first frag in the previous level which matches the CC of the first frag of the new level
  11400. function findDiscontinuousReferenceFrag(prevDetails, curDetails) {
  11401. var prevFrags = prevDetails.fragments;
  11402. var curFrags = curDetails.fragments;
  11403. if (!curFrags.length || !prevFrags.length) {
  11404. logger.log('No fragments to align');
  11405. return;
  11406. }
  11407. var prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);
  11408. if (!prevStartFrag || prevStartFrag && !prevStartFrag.startPTS) {
  11409. logger.log('No frag in previous level to align on');
  11410. return;
  11411. }
  11412. return prevStartFrag;
  11413. }
  11414. function adjustFragmentStart(frag, sliding) {
  11415. if (frag) {
  11416. var start = frag.start + sliding;
  11417. frag.start = frag.startPTS = start;
  11418. frag.endPTS = start + frag.duration;
  11419. }
  11420. }
  11421. function adjustSlidingStart(sliding, details) {
  11422. // Update segments
  11423. var fragments = details.fragments;
  11424. for (var i = 0, len = fragments.length; i < len; i++) {
  11425. adjustFragmentStart(fragments[i], sliding);
  11426. }
  11427. // Update LL-HLS parts at the end of the playlist
  11428. if (details.fragmentHint) {
  11429. adjustFragmentStart(details.fragmentHint, sliding);
  11430. }
  11431. details.alignedSliding = true;
  11432. }
  11433. /**
  11434. * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a
  11435. * contiguous stream with the last fragments.
  11436. * The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to
  11437. * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time
  11438. * and an extra download.
  11439. * @param lastFrag
  11440. * @param lastLevel
  11441. * @param details
  11442. */
  11443. function alignStream(lastFrag, switchDetails, details) {
  11444. if (!switchDetails) {
  11445. return;
  11446. }
  11447. alignDiscontinuities(lastFrag, details, switchDetails);
  11448. if (!details.alignedSliding && switchDetails) {
  11449. // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.
  11450. // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same
  11451. // discontinuity sequence.
  11452. alignMediaPlaylistByPDT(details, switchDetails);
  11453. }
  11454. if (!details.alignedSliding && switchDetails && !details.skippedSegments) {
  11455. // Try to align on sn so that we pick a better start fragment.
  11456. // Do not perform this on playlists with delta updates as this is only to align levels on switch
  11457. // and adjustSliding only adjusts fragments after skippedSegments.
  11458. adjustSliding(switchDetails, details);
  11459. }
  11460. }
  11461. /**
  11462. * Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same
  11463. * discontinuity sequence.
  11464. * @param lastFrag - The last Fragment which shares the same discontinuity sequence
  11465. * @param lastLevel - The details of the last loaded level
  11466. * @param details - The details of the new level
  11467. */
  11468. function alignDiscontinuities(lastFrag, details, switchDetails) {
  11469. if (shouldAlignOnDiscontinuities(lastFrag, switchDetails, details)) {
  11470. var referenceFrag = findDiscontinuousReferenceFrag(switchDetails, details);
  11471. if (referenceFrag && isFiniteNumber(referenceFrag.start)) {
  11472. logger.log("Adjusting PTS using last level due to CC increase within current level " + details.url);
  11473. adjustSlidingStart(referenceFrag.start, details);
  11474. }
  11475. }
  11476. }
  11477. /**
  11478. * Ensures appropriate time-alignment between renditions based on PDT.
  11479. * This function assumes the timelines represented in `refDetails` are accurate, including the PDTs
  11480. * for the last discontinuity sequence number shared by both playlists when present,
  11481. * and uses the "wallclock"/PDT timeline as a cross-reference to `details`, adjusting the presentation
  11482. * times/timelines of `details` accordingly.
  11483. * Given the asynchronous nature of fetches and initial loads of live `main` and audio/subtitle tracks,
  11484. * the primary purpose of this function is to ensure the "local timelines" of audio/subtitle tracks
  11485. * are aligned to the main/video timeline, using PDT as the cross-reference/"anchor" that should
  11486. * be consistent across playlists, per the HLS spec.
  11487. * @param details - The details of the rendition you'd like to time-align (e.g. an audio rendition).
  11488. * @param refDetails - The details of the reference rendition with start and PDT times for alignment.
  11489. */
  11490. function alignMediaPlaylistByPDT(details, refDetails) {
  11491. if (!details.hasProgramDateTime || !refDetails.hasProgramDateTime) {
  11492. return;
  11493. }
  11494. var fragments = details.fragments;
  11495. var refFragments = refDetails.fragments;
  11496. if (!fragments.length || !refFragments.length) {
  11497. return;
  11498. }
  11499. // Calculate a delta to apply to all fragments according to the delta in PDT times and start times
  11500. // of a fragment in the reference details, and a fragment in the target details of the same discontinuity.
  11501. // If a fragment of the same discontinuity was not found use the middle fragment of both.
  11502. var refFrag;
  11503. var frag;
  11504. var targetCC = Math.min(refDetails.endCC, details.endCC);
  11505. if (refDetails.startCC < targetCC && details.startCC < targetCC) {
  11506. refFrag = findFirstFragWithCC(refFragments, targetCC);
  11507. frag = findFirstFragWithCC(fragments, targetCC);
  11508. }
  11509. if (!refFrag || !frag) {
  11510. refFrag = refFragments[Math.floor(refFragments.length / 2)];
  11511. frag = findFirstFragWithCC(fragments, refFrag.cc) || fragments[Math.floor(fragments.length / 2)];
  11512. }
  11513. var refPDT = refFrag.programDateTime;
  11514. var targetPDT = frag.programDateTime;
  11515. if (!refPDT || !targetPDT) {
  11516. return;
  11517. }
  11518. var delta = (targetPDT - refPDT) / 1000 - (frag.start - refFrag.start);
  11519. adjustSlidingStart(delta, details);
  11520. }
  11521. var AESCrypto = /*#__PURE__*/function () {
  11522. function AESCrypto(subtle, iv) {
  11523. this.subtle = void 0;
  11524. this.aesIV = void 0;
  11525. this.subtle = subtle;
  11526. this.aesIV = iv;
  11527. }
  11528. var _proto = AESCrypto.prototype;
  11529. _proto.decrypt = function decrypt(data, key) {
  11530. return this.subtle.decrypt({
  11531. name: 'AES-CBC',
  11532. iv: this.aesIV
  11533. }, key, data);
  11534. };
  11535. return AESCrypto;
  11536. }();
  11537. var FastAESKey = /*#__PURE__*/function () {
  11538. function FastAESKey(subtle, key) {
  11539. this.subtle = void 0;
  11540. this.key = void 0;
  11541. this.subtle = subtle;
  11542. this.key = key;
  11543. }
  11544. var _proto = FastAESKey.prototype;
  11545. _proto.expandKey = function expandKey() {
  11546. return this.subtle.importKey('raw', this.key, {
  11547. name: 'AES-CBC'
  11548. }, false, ['encrypt', 'decrypt']);
  11549. };
  11550. return FastAESKey;
  11551. }();
  11552. // PKCS7
  11553. function removePadding(array) {
  11554. var outputBytes = array.byteLength;
  11555. var paddingBytes = outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1);
  11556. if (paddingBytes) {
  11557. return sliceUint8(array, 0, outputBytes - paddingBytes);
  11558. }
  11559. return array;
  11560. }
  11561. var AESDecryptor = /*#__PURE__*/function () {
  11562. function AESDecryptor() {
  11563. this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
  11564. this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  11565. this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  11566. this.sBox = new Uint32Array(256);
  11567. this.invSBox = new Uint32Array(256);
  11568. this.key = new Uint32Array(0);
  11569. this.ksRows = 0;
  11570. this.keySize = 0;
  11571. this.keySchedule = void 0;
  11572. this.invKeySchedule = void 0;
  11573. this.initTable();
  11574. }
  11575. // Using view.getUint32() also swaps the byte order.
  11576. var _proto = AESDecryptor.prototype;
  11577. _proto.uint8ArrayToUint32Array_ = function uint8ArrayToUint32Array_(arrayBuffer) {
  11578. var view = new DataView(arrayBuffer);
  11579. var newArray = new Uint32Array(4);
  11580. for (var i = 0; i < 4; i++) {
  11581. newArray[i] = view.getUint32(i * 4);
  11582. }
  11583. return newArray;
  11584. };
  11585. _proto.initTable = function initTable() {
  11586. var sBox = this.sBox;
  11587. var invSBox = this.invSBox;
  11588. var subMix = this.subMix;
  11589. var subMix0 = subMix[0];
  11590. var subMix1 = subMix[1];
  11591. var subMix2 = subMix[2];
  11592. var subMix3 = subMix[3];
  11593. var invSubMix = this.invSubMix;
  11594. var invSubMix0 = invSubMix[0];
  11595. var invSubMix1 = invSubMix[1];
  11596. var invSubMix2 = invSubMix[2];
  11597. var invSubMix3 = invSubMix[3];
  11598. var d = new Uint32Array(256);
  11599. var x = 0;
  11600. var xi = 0;
  11601. var i = 0;
  11602. for (i = 0; i < 256; i++) {
  11603. if (i < 128) {
  11604. d[i] = i << 1;
  11605. } else {
  11606. d[i] = i << 1 ^ 0x11b;
  11607. }
  11608. }
  11609. for (i = 0; i < 256; i++) {
  11610. var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
  11611. sx = sx >>> 8 ^ sx & 0xff ^ 0x63;
  11612. sBox[x] = sx;
  11613. invSBox[sx] = x;
  11614. // Compute multiplication
  11615. var x2 = d[x];
  11616. var x4 = d[x2];
  11617. var x8 = d[x4];
  11618. // Compute sub/invSub bytes, mix columns tables
  11619. var t = d[sx] * 0x101 ^ sx * 0x1010100;
  11620. subMix0[x] = t << 24 | t >>> 8;
  11621. subMix1[x] = t << 16 | t >>> 16;
  11622. subMix2[x] = t << 8 | t >>> 24;
  11623. subMix3[x] = t;
  11624. // Compute inv sub bytes, inv mix columns tables
  11625. t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  11626. invSubMix0[sx] = t << 24 | t >>> 8;
  11627. invSubMix1[sx] = t << 16 | t >>> 16;
  11628. invSubMix2[sx] = t << 8 | t >>> 24;
  11629. invSubMix3[sx] = t;
  11630. // Compute next counter
  11631. if (!x) {
  11632. x = xi = 1;
  11633. } else {
  11634. x = x2 ^ d[d[d[x8 ^ x2]]];
  11635. xi ^= d[d[xi]];
  11636. }
  11637. }
  11638. };
  11639. _proto.expandKey = function expandKey(keyBuffer) {
  11640. // convert keyBuffer to Uint32Array
  11641. var key = this.uint8ArrayToUint32Array_(keyBuffer);
  11642. var sameKey = true;
  11643. var offset = 0;
  11644. while (offset < key.length && sameKey) {
  11645. sameKey = key[offset] === this.key[offset];
  11646. offset++;
  11647. }
  11648. if (sameKey) {
  11649. return;
  11650. }
  11651. this.key = key;
  11652. var keySize = this.keySize = key.length;
  11653. if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
  11654. throw new Error('Invalid aes key size=' + keySize);
  11655. }
  11656. var ksRows = this.ksRows = (keySize + 6 + 1) * 4;
  11657. var ksRow;
  11658. var invKsRow;
  11659. var keySchedule = this.keySchedule = new Uint32Array(ksRows);
  11660. var invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
  11661. var sbox = this.sBox;
  11662. var rcon = this.rcon;
  11663. var invSubMix = this.invSubMix;
  11664. var invSubMix0 = invSubMix[0];
  11665. var invSubMix1 = invSubMix[1];
  11666. var invSubMix2 = invSubMix[2];
  11667. var invSubMix3 = invSubMix[3];
  11668. var prev;
  11669. var t;
  11670. for (ksRow = 0; ksRow < ksRows; ksRow++) {
  11671. if (ksRow < keySize) {
  11672. prev = keySchedule[ksRow] = key[ksRow];
  11673. continue;
  11674. }
  11675. t = prev;
  11676. if (ksRow % keySize === 0) {
  11677. // Rot word
  11678. t = t << 8 | t >>> 24;
  11679. // Sub word
  11680. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  11681. // Mix Rcon
  11682. t ^= rcon[ksRow / keySize | 0] << 24;
  11683. } else if (keySize > 6 && ksRow % keySize === 4) {
  11684. // Sub word
  11685. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  11686. }
  11687. keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
  11688. }
  11689. for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
  11690. ksRow = ksRows - invKsRow;
  11691. if (invKsRow & 3) {
  11692. t = keySchedule[ksRow];
  11693. } else {
  11694. t = keySchedule[ksRow - 4];
  11695. }
  11696. if (invKsRow < 4 || ksRow <= 4) {
  11697. invKeySchedule[invKsRow] = t;
  11698. } else {
  11699. invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]];
  11700. }
  11701. invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
  11702. }
  11703. }
  11704. // Adding this as a method greatly improves performance.
  11705. ;
  11706. _proto.networkToHostOrderSwap = function networkToHostOrderSwap(word) {
  11707. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  11708. };
  11709. _proto.decrypt = function decrypt(inputArrayBuffer, offset, aesIV) {
  11710. var nRounds = this.keySize + 6;
  11711. var invKeySchedule = this.invKeySchedule;
  11712. var invSBOX = this.invSBox;
  11713. var invSubMix = this.invSubMix;
  11714. var invSubMix0 = invSubMix[0];
  11715. var invSubMix1 = invSubMix[1];
  11716. var invSubMix2 = invSubMix[2];
  11717. var invSubMix3 = invSubMix[3];
  11718. var initVector = this.uint8ArrayToUint32Array_(aesIV);
  11719. var initVector0 = initVector[0];
  11720. var initVector1 = initVector[1];
  11721. var initVector2 = initVector[2];
  11722. var initVector3 = initVector[3];
  11723. var inputInt32 = new Int32Array(inputArrayBuffer);
  11724. var outputInt32 = new Int32Array(inputInt32.length);
  11725. var t0, t1, t2, t3;
  11726. var s0, s1, s2, s3;
  11727. var inputWords0, inputWords1, inputWords2, inputWords3;
  11728. var ksRow, i;
  11729. var swapWord = this.networkToHostOrderSwap;
  11730. while (offset < inputInt32.length) {
  11731. inputWords0 = swapWord(inputInt32[offset]);
  11732. inputWords1 = swapWord(inputInt32[offset + 1]);
  11733. inputWords2 = swapWord(inputInt32[offset + 2]);
  11734. inputWords3 = swapWord(inputInt32[offset + 3]);
  11735. s0 = inputWords0 ^ invKeySchedule[0];
  11736. s1 = inputWords3 ^ invKeySchedule[1];
  11737. s2 = inputWords2 ^ invKeySchedule[2];
  11738. s3 = inputWords1 ^ invKeySchedule[3];
  11739. ksRow = 4;
  11740. // Iterate through the rounds of decryption
  11741. for (i = 1; i < nRounds; i++) {
  11742. t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];
  11743. t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  11744. t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  11745. t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  11746. // Update state
  11747. s0 = t0;
  11748. s1 = t1;
  11749. s2 = t2;
  11750. s3 = t3;
  11751. ksRow = ksRow + 4;
  11752. }
  11753. // Shift rows, sub bytes, add round key
  11754. t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow];
  11755. t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  11756. t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  11757. t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  11758. // Write
  11759. outputInt32[offset] = swapWord(t0 ^ initVector0);
  11760. outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
  11761. outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
  11762. outputInt32[offset + 3] = swapWord(t1 ^ initVector3);
  11763. // reset initVector to last 4 unsigned int
  11764. initVector0 = inputWords0;
  11765. initVector1 = inputWords1;
  11766. initVector2 = inputWords2;
  11767. initVector3 = inputWords3;
  11768. offset = offset + 4;
  11769. }
  11770. return outputInt32.buffer;
  11771. };
  11772. return AESDecryptor;
  11773. }();
  11774. var CHUNK_SIZE = 16; // 16 bytes, 128 bits
  11775. var Decrypter = /*#__PURE__*/function () {
  11776. function Decrypter(config, _temp) {
  11777. var _ref = _temp === void 0 ? {} : _temp,
  11778. _ref$removePKCS7Paddi = _ref.removePKCS7Padding,
  11779. removePKCS7Padding = _ref$removePKCS7Paddi === void 0 ? true : _ref$removePKCS7Paddi;
  11780. this.logEnabled = true;
  11781. this.removePKCS7Padding = void 0;
  11782. this.subtle = null;
  11783. this.softwareDecrypter = null;
  11784. this.key = null;
  11785. this.fastAesKey = null;
  11786. this.remainderData = null;
  11787. this.currentIV = null;
  11788. this.currentResult = null;
  11789. this.useSoftware = void 0;
  11790. this.useSoftware = config.enableSoftwareAES;
  11791. this.removePKCS7Padding = removePKCS7Padding;
  11792. // built in decryptor expects PKCS7 padding
  11793. if (removePKCS7Padding) {
  11794. try {
  11795. var browserCrypto = self.crypto;
  11796. if (browserCrypto) {
  11797. this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
  11798. }
  11799. } catch (e) {
  11800. /* no-op */
  11801. }
  11802. }
  11803. this.useSoftware = !this.subtle;
  11804. }
  11805. var _proto = Decrypter.prototype;
  11806. _proto.destroy = function destroy() {
  11807. this.subtle = null;
  11808. this.softwareDecrypter = null;
  11809. this.key = null;
  11810. this.fastAesKey = null;
  11811. this.remainderData = null;
  11812. this.currentIV = null;
  11813. this.currentResult = null;
  11814. };
  11815. _proto.isSync = function isSync() {
  11816. return this.useSoftware;
  11817. };
  11818. _proto.flush = function flush() {
  11819. var currentResult = this.currentResult,
  11820. remainderData = this.remainderData;
  11821. if (!currentResult || remainderData) {
  11822. this.reset();
  11823. return null;
  11824. }
  11825. var data = new Uint8Array(currentResult);
  11826. this.reset();
  11827. if (this.removePKCS7Padding) {
  11828. return removePadding(data);
  11829. }
  11830. return data;
  11831. };
  11832. _proto.reset = function reset() {
  11833. this.currentResult = null;
  11834. this.currentIV = null;
  11835. this.remainderData = null;
  11836. if (this.softwareDecrypter) {
  11837. this.softwareDecrypter = null;
  11838. }
  11839. };
  11840. _proto.decrypt = function decrypt(data, key, iv) {
  11841. var _this = this;
  11842. if (this.useSoftware) {
  11843. return new Promise(function (resolve, reject) {
  11844. _this.softwareDecrypt(new Uint8Array(data), key, iv);
  11845. var decryptResult = _this.flush();
  11846. if (decryptResult) {
  11847. resolve(decryptResult.buffer);
  11848. } else {
  11849. reject(new Error('[softwareDecrypt] Failed to decrypt data'));
  11850. }
  11851. });
  11852. }
  11853. return this.webCryptoDecrypt(new Uint8Array(data), key, iv);
  11854. }
  11855. // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
  11856. // data is handled in the flush() call
  11857. ;
  11858. _proto.softwareDecrypt = function softwareDecrypt(data, key, iv) {
  11859. var currentIV = this.currentIV,
  11860. currentResult = this.currentResult,
  11861. remainderData = this.remainderData;
  11862. this.logOnce('JS AES decrypt');
  11863. // The output is staggered during progressive parsing - the current result is cached, and emitted on the next call
  11864. // This is done in order to strip PKCS7 padding, which is found at the end of each segment. We only know we've reached
  11865. // the end on flush(), but by that time we have already received all bytes for the segment.
  11866. // Progressive decryption does not work with WebCrypto
  11867. if (remainderData) {
  11868. data = appendUint8Array(remainderData, data);
  11869. this.remainderData = null;
  11870. }
  11871. // Byte length must be a multiple of 16 (AES-128 = 128 bit blocks = 16 bytes)
  11872. var currentChunk = this.getValidChunk(data);
  11873. if (!currentChunk.length) {
  11874. return null;
  11875. }
  11876. if (currentIV) {
  11877. iv = currentIV;
  11878. }
  11879. var softwareDecrypter = this.softwareDecrypter;
  11880. if (!softwareDecrypter) {
  11881. softwareDecrypter = this.softwareDecrypter = new AESDecryptor();
  11882. }
  11883. softwareDecrypter.expandKey(key);
  11884. var result = currentResult;
  11885. this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv);
  11886. this.currentIV = sliceUint8(currentChunk, -16).buffer;
  11887. if (!result) {
  11888. return null;
  11889. }
  11890. return result;
  11891. };
  11892. _proto.webCryptoDecrypt = function webCryptoDecrypt(data, key, iv) {
  11893. var _this2 = this;
  11894. if (this.key !== key || !this.fastAesKey) {
  11895. if (!this.subtle) {
  11896. return Promise.resolve(this.onWebCryptoError(data, key, iv));
  11897. }
  11898. this.key = key;
  11899. this.fastAesKey = new FastAESKey(this.subtle, key);
  11900. }
  11901. return this.fastAesKey.expandKey().then(function (aesKey) {
  11902. // decrypt using web crypto
  11903. if (!_this2.subtle) {
  11904. return Promise.reject(new Error('web crypto not initialized'));
  11905. }
  11906. _this2.logOnce('WebCrypto AES decrypt');
  11907. var crypto = new AESCrypto(_this2.subtle, new Uint8Array(iv));
  11908. return crypto.decrypt(data.buffer, aesKey);
  11909. }).catch(function (err) {
  11910. logger.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, " + err.name + ": " + err.message);
  11911. return _this2.onWebCryptoError(data, key, iv);
  11912. });
  11913. };
  11914. _proto.onWebCryptoError = function onWebCryptoError(data, key, iv) {
  11915. this.useSoftware = true;
  11916. this.logEnabled = true;
  11917. this.softwareDecrypt(data, key, iv);
  11918. var decryptResult = this.flush();
  11919. if (decryptResult) {
  11920. return decryptResult.buffer;
  11921. }
  11922. throw new Error('WebCrypto and softwareDecrypt: failed to decrypt data');
  11923. };
  11924. _proto.getValidChunk = function getValidChunk(data) {
  11925. var currentChunk = data;
  11926. var splitPoint = data.length - data.length % CHUNK_SIZE;
  11927. if (splitPoint !== data.length) {
  11928. currentChunk = sliceUint8(data, 0, splitPoint);
  11929. this.remainderData = sliceUint8(data, splitPoint);
  11930. }
  11931. return currentChunk;
  11932. };
  11933. _proto.logOnce = function logOnce(msg) {
  11934. if (!this.logEnabled) {
  11935. return;
  11936. }
  11937. logger.log("[decrypter]: " + msg);
  11938. this.logEnabled = false;
  11939. };
  11940. return Decrypter;
  11941. }();
  11942. /**
  11943. * TimeRanges to string helper
  11944. */
  11945. var TimeRanges = {
  11946. toString: function toString(r) {
  11947. var log = '';
  11948. var len = r.length;
  11949. for (var i = 0; i < len; i++) {
  11950. log += "[" + r.start(i).toFixed(3) + "-" + r.end(i).toFixed(3) + "]";
  11951. }
  11952. return log;
  11953. }
  11954. };
  11955. var State = {
  11956. STOPPED: 'STOPPED',
  11957. IDLE: 'IDLE',
  11958. KEY_LOADING: 'KEY_LOADING',
  11959. FRAG_LOADING: 'FRAG_LOADING',
  11960. FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
  11961. WAITING_TRACK: 'WAITING_TRACK',
  11962. PARSING: 'PARSING',
  11963. PARSED: 'PARSED',
  11964. ENDED: 'ENDED',
  11965. ERROR: 'ERROR',
  11966. WAITING_INIT_PTS: 'WAITING_INIT_PTS',
  11967. WAITING_LEVEL: 'WAITING_LEVEL'
  11968. };
  11969. var BaseStreamController = /*#__PURE__*/function (_TaskLoop) {
  11970. _inheritsLoose(BaseStreamController, _TaskLoop);
  11971. function BaseStreamController(hls, fragmentTracker, keyLoader, logPrefix, playlistType) {
  11972. var _this;
  11973. _this = _TaskLoop.call(this) || this;
  11974. _this.hls = void 0;
  11975. _this.fragPrevious = null;
  11976. _this.fragCurrent = null;
  11977. _this.fragmentTracker = void 0;
  11978. _this.transmuxer = null;
  11979. _this._state = State.STOPPED;
  11980. _this.playlistType = void 0;
  11981. _this.media = null;
  11982. _this.mediaBuffer = null;
  11983. _this.config = void 0;
  11984. _this.bitrateTest = false;
  11985. _this.lastCurrentTime = 0;
  11986. _this.nextLoadPosition = 0;
  11987. _this.startPosition = 0;
  11988. _this.startTimeOffset = null;
  11989. _this.loadedmetadata = false;
  11990. _this.retryDate = 0;
  11991. _this.levels = null;
  11992. _this.fragmentLoader = void 0;
  11993. _this.keyLoader = void 0;
  11994. _this.levelLastLoaded = null;
  11995. _this.startFragRequested = false;
  11996. _this.decrypter = void 0;
  11997. _this.initPTS = [];
  11998. _this.onvseeking = null;
  11999. _this.onvended = null;
  12000. _this.logPrefix = '';
  12001. _this.log = void 0;
  12002. _this.warn = void 0;
  12003. _this.playlistType = playlistType;
  12004. _this.logPrefix = logPrefix;
  12005. _this.log = logger.log.bind(logger, logPrefix + ":");
  12006. _this.warn = logger.warn.bind(logger, logPrefix + ":");
  12007. _this.hls = hls;
  12008. _this.fragmentLoader = new FragmentLoader(hls.config);
  12009. _this.keyLoader = keyLoader;
  12010. _this.fragmentTracker = fragmentTracker;
  12011. _this.config = hls.config;
  12012. _this.decrypter = new Decrypter(hls.config);
  12013. hls.on(Events.MANIFEST_LOADED, _this.onManifestLoaded, _assertThisInitialized(_this));
  12014. return _this;
  12015. }
  12016. var _proto = BaseStreamController.prototype;
  12017. _proto.doTick = function doTick() {
  12018. this.onTickEnd();
  12019. };
  12020. _proto.onTickEnd = function onTickEnd() {}
  12021. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  12022. ;
  12023. _proto.startLoad = function startLoad(startPosition) {};
  12024. _proto.stopLoad = function stopLoad() {
  12025. this.fragmentLoader.abort();
  12026. this.keyLoader.abort(this.playlistType);
  12027. var frag = this.fragCurrent;
  12028. if (frag != null && frag.loader) {
  12029. frag.abortRequests();
  12030. this.fragmentTracker.removeFragment(frag);
  12031. }
  12032. this.resetTransmuxer();
  12033. this.fragCurrent = null;
  12034. this.fragPrevious = null;
  12035. this.clearInterval();
  12036. this.clearNextTick();
  12037. this.state = State.STOPPED;
  12038. };
  12039. _proto._streamEnded = function _streamEnded(bufferInfo, levelDetails) {
  12040. // If playlist is live, there is another buffered range after the current range, nothing buffered, media is detached,
  12041. // of nothing loading/loaded return false
  12042. if (levelDetails.live || bufferInfo.nextStart || !bufferInfo.end || !this.media) {
  12043. return false;
  12044. }
  12045. var partList = levelDetails.partList;
  12046. // Since the last part isn't guaranteed to correspond to the last playlist segment for Low-Latency HLS,
  12047. // check instead if the last part is buffered.
  12048. if (partList != null && partList.length) {
  12049. var lastPart = partList[partList.length - 1];
  12050. // Checking the midpoint of the part for potential margin of error and related issues.
  12051. // NOTE: Technically I believe parts could yield content that is < the computed duration (including potential a duration of 0)
  12052. // and still be spec-compliant, so there may still be edge cases here. Likewise, there could be issues in end of stream
  12053. // part mismatches for independent audio and video playlists/segments.
  12054. var lastPartBuffered = BufferHelper.isBuffered(this.media, lastPart.start + lastPart.duration / 2);
  12055. return lastPartBuffered;
  12056. }
  12057. var playlistType = levelDetails.fragments[levelDetails.fragments.length - 1].type;
  12058. return this.fragmentTracker.isEndListAppended(playlistType);
  12059. };
  12060. _proto.getLevelDetails = function getLevelDetails() {
  12061. if (this.levels && this.levelLastLoaded !== null) {
  12062. var _this$levelLastLoaded;
  12063. return (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details;
  12064. }
  12065. };
  12066. _proto.onMediaAttached = function onMediaAttached(event, data) {
  12067. var media = this.media = this.mediaBuffer = data.media;
  12068. this.onvseeking = this.onMediaSeeking.bind(this);
  12069. this.onvended = this.onMediaEnded.bind(this);
  12070. media.addEventListener('seeking', this.onvseeking);
  12071. media.addEventListener('ended', this.onvended);
  12072. var config = this.config;
  12073. if (this.levels && config.autoStartLoad && this.state === State.STOPPED) {
  12074. this.startLoad(config.startPosition);
  12075. }
  12076. };
  12077. _proto.onMediaDetaching = function onMediaDetaching() {
  12078. var media = this.media;
  12079. if (media != null && media.ended) {
  12080. this.log('MSE detaching and video ended, reset startPosition');
  12081. this.startPosition = this.lastCurrentTime = 0;
  12082. }
  12083. // remove video listeners
  12084. if (media && this.onvseeking && this.onvended) {
  12085. media.removeEventListener('seeking', this.onvseeking);
  12086. media.removeEventListener('ended', this.onvended);
  12087. this.onvseeking = this.onvended = null;
  12088. }
  12089. if (this.keyLoader) {
  12090. this.keyLoader.detach();
  12091. }
  12092. this.media = this.mediaBuffer = null;
  12093. this.loadedmetadata = false;
  12094. this.fragmentTracker.removeAllFragments();
  12095. this.stopLoad();
  12096. };
  12097. _proto.onMediaSeeking = function onMediaSeeking() {
  12098. var config = this.config,
  12099. fragCurrent = this.fragCurrent,
  12100. media = this.media,
  12101. mediaBuffer = this.mediaBuffer,
  12102. state = this.state;
  12103. var currentTime = media ? media.currentTime : 0;
  12104. var bufferInfo = BufferHelper.bufferInfo(mediaBuffer ? mediaBuffer : media, currentTime, config.maxBufferHole);
  12105. this.log("media seeking to " + (isFiniteNumber(currentTime) ? currentTime.toFixed(3) : currentTime) + ", state: " + state);
  12106. if (this.state === State.ENDED) {
  12107. this.resetLoadingState();
  12108. } else if (fragCurrent) {
  12109. // Seeking while frag load is in progress
  12110. var tolerance = config.maxFragLookUpTolerance;
  12111. var fragStartOffset = fragCurrent.start - tolerance;
  12112. var fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;
  12113. // if seeking out of buffered range or into new one
  12114. if (!bufferInfo.len || fragEndOffset < bufferInfo.start || fragStartOffset > bufferInfo.end) {
  12115. var pastFragment = currentTime > fragEndOffset;
  12116. // if the seek position is outside the current fragment range
  12117. if (currentTime < fragStartOffset || pastFragment) {
  12118. if (pastFragment && fragCurrent.loader) {
  12119. this.log('seeking outside of buffer while fragment load in progress, cancel fragment load');
  12120. fragCurrent.abortRequests();
  12121. this.resetLoadingState();
  12122. }
  12123. this.fragPrevious = null;
  12124. }
  12125. }
  12126. }
  12127. if (media) {
  12128. // Remove gap fragments
  12129. this.fragmentTracker.removeFragmentsInRange(currentTime, Infinity, this.playlistType, true);
  12130. this.lastCurrentTime = currentTime;
  12131. }
  12132. // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
  12133. if (!this.loadedmetadata && !bufferInfo.len) {
  12134. this.nextLoadPosition = this.startPosition = currentTime;
  12135. }
  12136. // Async tick to speed up processing
  12137. this.tickImmediate();
  12138. };
  12139. _proto.onMediaEnded = function onMediaEnded() {
  12140. // reset startPosition and lastCurrentTime to restart playback @ stream beginning
  12141. this.startPosition = this.lastCurrentTime = 0;
  12142. };
  12143. _proto.onManifestLoaded = function onManifestLoaded(event, data) {
  12144. this.startTimeOffset = data.startTimeOffset;
  12145. this.initPTS = [];
  12146. };
  12147. _proto.onHandlerDestroying = function onHandlerDestroying() {
  12148. this.hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  12149. this.stopLoad();
  12150. _TaskLoop.prototype.onHandlerDestroying.call(this);
  12151. // @ts-ignore
  12152. this.hls = null;
  12153. };
  12154. _proto.onHandlerDestroyed = function onHandlerDestroyed() {
  12155. this.state = State.STOPPED;
  12156. if (this.fragmentLoader) {
  12157. this.fragmentLoader.destroy();
  12158. }
  12159. if (this.keyLoader) {
  12160. this.keyLoader.destroy();
  12161. }
  12162. if (this.decrypter) {
  12163. this.decrypter.destroy();
  12164. }
  12165. this.hls = this.log = this.warn = this.decrypter = this.keyLoader = this.fragmentLoader = this.fragmentTracker = null;
  12166. _TaskLoop.prototype.onHandlerDestroyed.call(this);
  12167. };
  12168. _proto.loadFragment = function loadFragment(frag, level, targetBufferTime) {
  12169. this._loadFragForPlayback(frag, level, targetBufferTime);
  12170. };
  12171. _proto._loadFragForPlayback = function _loadFragForPlayback(frag, level, targetBufferTime) {
  12172. var _this2 = this;
  12173. var progressCallback = function progressCallback(data) {
  12174. if (_this2.fragContextChanged(frag)) {
  12175. _this2.warn("Fragment " + frag.sn + (data.part ? ' p: ' + data.part.index : '') + " of level " + frag.level + " was dropped during download.");
  12176. _this2.fragmentTracker.removeFragment(frag);
  12177. return;
  12178. }
  12179. frag.stats.chunkCount++;
  12180. _this2._handleFragmentLoadProgress(data);
  12181. };
  12182. this._doFragLoad(frag, level, targetBufferTime, progressCallback).then(function (data) {
  12183. if (!data) {
  12184. // if we're here we probably needed to backtrack or are waiting for more parts
  12185. return;
  12186. }
  12187. var state = _this2.state;
  12188. if (_this2.fragContextChanged(frag)) {
  12189. if (state === State.FRAG_LOADING || !_this2.fragCurrent && state === State.PARSING) {
  12190. _this2.fragmentTracker.removeFragment(frag);
  12191. _this2.state = State.IDLE;
  12192. }
  12193. return;
  12194. }
  12195. if ('payload' in data) {
  12196. _this2.log("Loaded fragment " + frag.sn + " of level " + frag.level);
  12197. _this2.hls.trigger(Events.FRAG_LOADED, data);
  12198. }
  12199. // Pass through the whole payload; controllers not implementing progressive loading receive data from this callback
  12200. _this2._handleFragmentLoadComplete(data);
  12201. }).catch(function (reason) {
  12202. if (_this2.state === State.STOPPED || _this2.state === State.ERROR) {
  12203. return;
  12204. }
  12205. _this2.warn("Frag error: " + ((reason == null ? void 0 : reason.message) || reason));
  12206. _this2.resetFragmentLoading(frag);
  12207. });
  12208. };
  12209. _proto.clearTrackerIfNeeded = function clearTrackerIfNeeded(frag) {
  12210. var _this$mediaBuffer;
  12211. var fragmentTracker = this.fragmentTracker;
  12212. var fragState = fragmentTracker.getState(frag);
  12213. if (fragState === FragmentState.APPENDING) {
  12214. // Lower the max buffer length and try again
  12215. var playlistType = frag.type;
  12216. var bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  12217. var minForwardBufferLength = Math.max(frag.duration, bufferedInfo ? bufferedInfo.len : this.config.maxBufferLength);
  12218. // If backtracking, always remove from the tracker without reducing max buffer length
  12219. var backtrackFragment = this.backtrackFragment;
  12220. var backtracked = backtrackFragment ? frag.sn - backtrackFragment.sn : 0;
  12221. if (backtracked === 1 || this.reduceMaxBufferLength(minForwardBufferLength)) {
  12222. fragmentTracker.removeFragment(frag);
  12223. }
  12224. } else if (((_this$mediaBuffer = this.mediaBuffer) == null ? void 0 : _this$mediaBuffer.buffered.length) === 0) {
  12225. // Stop gap for bad tracker / buffer flush behavior
  12226. fragmentTracker.removeAllFragments();
  12227. } else if (fragmentTracker.hasParts(frag.type)) {
  12228. // In low latency mode, remove fragments for which only some parts were buffered
  12229. fragmentTracker.detectPartialFragments({
  12230. frag: frag,
  12231. part: null,
  12232. stats: frag.stats,
  12233. id: frag.type
  12234. });
  12235. if (fragmentTracker.getState(frag) === FragmentState.PARTIAL) {
  12236. fragmentTracker.removeFragment(frag);
  12237. }
  12238. }
  12239. };
  12240. _proto.checkLiveUpdate = function checkLiveUpdate(details) {
  12241. if (details.updated && !details.live) {
  12242. // Live stream ended, update fragment tracker
  12243. var lastFragment = details.fragments[details.fragments.length - 1];
  12244. this.fragmentTracker.detectPartialFragments({
  12245. frag: lastFragment,
  12246. part: null,
  12247. stats: lastFragment.stats,
  12248. id: lastFragment.type
  12249. });
  12250. }
  12251. if (!details.fragments[0]) {
  12252. details.deltaUpdateFailed = true;
  12253. }
  12254. };
  12255. _proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset, type) {
  12256. if (type === void 0) {
  12257. type = null;
  12258. }
  12259. if (!(startOffset - endOffset)) {
  12260. return;
  12261. }
  12262. // When alternate audio is playing, the audio-stream-controller is responsible for the audio buffer. Otherwise,
  12263. // passing a null type flushes both buffers
  12264. var flushScope = {
  12265. startOffset: startOffset,
  12266. endOffset: endOffset,
  12267. type: type
  12268. };
  12269. this.hls.trigger(Events.BUFFER_FLUSHING, flushScope);
  12270. };
  12271. _proto._loadInitSegment = function _loadInitSegment(frag, level) {
  12272. var _this3 = this;
  12273. this._doFragLoad(frag, level).then(function (data) {
  12274. if (!data || _this3.fragContextChanged(frag) || !_this3.levels) {
  12275. throw new Error('init load aborted');
  12276. }
  12277. return data;
  12278. }).then(function (data) {
  12279. var hls = _this3.hls;
  12280. var payload = data.payload;
  12281. var decryptData = frag.decryptdata;
  12282. // check to see if the payload needs to be decrypted
  12283. if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && decryptData.method === 'AES-128') {
  12284. var startTime = self.performance.now();
  12285. // decrypt init segment data
  12286. return _this3.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer).catch(function (err) {
  12287. hls.trigger(Events.ERROR, {
  12288. type: ErrorTypes.MEDIA_ERROR,
  12289. details: ErrorDetails.FRAG_DECRYPT_ERROR,
  12290. fatal: false,
  12291. error: err,
  12292. reason: err.message,
  12293. frag: frag
  12294. });
  12295. throw err;
  12296. }).then(function (decryptedData) {
  12297. var endTime = self.performance.now();
  12298. hls.trigger(Events.FRAG_DECRYPTED, {
  12299. frag: frag,
  12300. payload: decryptedData,
  12301. stats: {
  12302. tstart: startTime,
  12303. tdecrypt: endTime
  12304. }
  12305. });
  12306. data.payload = decryptedData;
  12307. return _this3.completeInitSegmentLoad(data);
  12308. });
  12309. }
  12310. return _this3.completeInitSegmentLoad(data);
  12311. }).catch(function (reason) {
  12312. if (_this3.state === State.STOPPED || _this3.state === State.ERROR) {
  12313. return;
  12314. }
  12315. _this3.warn(reason);
  12316. _this3.resetFragmentLoading(frag);
  12317. });
  12318. };
  12319. _proto.completeInitSegmentLoad = function completeInitSegmentLoad(data) {
  12320. var levels = this.levels;
  12321. if (!levels) {
  12322. throw new Error('init load aborted, missing levels');
  12323. }
  12324. var stats = data.frag.stats;
  12325. this.state = State.IDLE;
  12326. data.frag.data = new Uint8Array(data.payload);
  12327. stats.parsing.start = stats.buffering.start = self.performance.now();
  12328. stats.parsing.end = stats.buffering.end = self.performance.now();
  12329. this.tick();
  12330. };
  12331. _proto.fragContextChanged = function fragContextChanged(frag) {
  12332. var fragCurrent = this.fragCurrent;
  12333. return !frag || !fragCurrent || frag.sn !== fragCurrent.sn || frag.level !== fragCurrent.level;
  12334. };
  12335. _proto.fragBufferedComplete = function fragBufferedComplete(frag, part) {
  12336. var _frag$startPTS, _frag$endPTS, _this$fragCurrent, _this$fragPrevious;
  12337. var media = this.mediaBuffer ? this.mediaBuffer : this.media;
  12338. 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)') + ")");
  12339. if (frag.sn !== 'initSegment') {
  12340. var _this$levels;
  12341. if (frag.type !== PlaylistLevelType.SUBTITLE) {
  12342. var el = frag.elementaryStreams;
  12343. if (!Object.keys(el).some(function (type) {
  12344. return !!el[type];
  12345. })) {
  12346. // empty segment
  12347. this.state = State.IDLE;
  12348. return;
  12349. }
  12350. }
  12351. var level = (_this$levels = this.levels) == null ? void 0 : _this$levels[frag.level];
  12352. if (level != null && level.fragmentError) {
  12353. this.log("Resetting level fragment error count of " + level.fragmentError + " on frag buffered");
  12354. level.fragmentError = 0;
  12355. }
  12356. }
  12357. this.state = State.IDLE;
  12358. if (!media) {
  12359. return;
  12360. }
  12361. 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)) {
  12362. this.loadedmetadata = true;
  12363. this.seekToStartPos();
  12364. }
  12365. this.tick();
  12366. };
  12367. _proto.seekToStartPos = function seekToStartPos() {};
  12368. _proto._handleFragmentLoadComplete = function _handleFragmentLoadComplete(fragLoadedEndData) {
  12369. var transmuxer = this.transmuxer;
  12370. if (!transmuxer) {
  12371. return;
  12372. }
  12373. var frag = fragLoadedEndData.frag,
  12374. part = fragLoadedEndData.part,
  12375. partsLoaded = fragLoadedEndData.partsLoaded;
  12376. // If we did not load parts, or loaded all parts, we have complete (not partial) fragment data
  12377. var complete = !partsLoaded || partsLoaded.length === 0 || partsLoaded.some(function (fragLoaded) {
  12378. return !fragLoaded;
  12379. });
  12380. var chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount + 1, 0, part ? part.index : -1, !complete);
  12381. transmuxer.flush(chunkMeta);
  12382. }
  12383. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  12384. ;
  12385. _proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(frag) {};
  12386. _proto._doFragLoad = function _doFragLoad(frag, level, targetBufferTime, progressCallback) {
  12387. var _frag$decryptdata,
  12388. _this4 = this;
  12389. if (targetBufferTime === void 0) {
  12390. targetBufferTime = null;
  12391. }
  12392. var details = level == null ? void 0 : level.details;
  12393. if (!this.levels || !details) {
  12394. throw new Error("frag load aborted, missing level" + (details ? '' : ' detail') + "s");
  12395. }
  12396. var keyLoadingPromise = null;
  12397. if (frag.encrypted && !((_frag$decryptdata = frag.decryptdata) != null && _frag$decryptdata.key)) {
  12398. this.log("Loading key for " + frag.sn + " of [" + details.startSN + "-" + details.endSN + "], " + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + " " + frag.level);
  12399. this.state = State.KEY_LOADING;
  12400. this.fragCurrent = frag;
  12401. keyLoadingPromise = this.keyLoader.load(frag).then(function (keyLoadedData) {
  12402. if (!_this4.fragContextChanged(keyLoadedData.frag)) {
  12403. _this4.hls.trigger(Events.KEY_LOADED, keyLoadedData);
  12404. if (_this4.state === State.KEY_LOADING) {
  12405. _this4.state = State.IDLE;
  12406. }
  12407. return keyLoadedData;
  12408. }
  12409. });
  12410. this.hls.trigger(Events.KEY_LOADING, {
  12411. frag: frag
  12412. });
  12413. if (this.fragCurrent === null) {
  12414. keyLoadingPromise = Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING"));
  12415. }
  12416. } else if (!frag.encrypted && details.encryptedFragments.length) {
  12417. this.keyLoader.loadClear(frag, details.encryptedFragments);
  12418. }
  12419. targetBufferTime = Math.max(frag.start, targetBufferTime || 0);
  12420. if (this.config.lowLatencyMode && frag.sn !== 'initSegment') {
  12421. var partList = details.partList;
  12422. if (partList && progressCallback) {
  12423. if (targetBufferTime > frag.end && details.fragmentHint) {
  12424. frag = details.fragmentHint;
  12425. }
  12426. var partIndex = this.getNextPart(partList, frag, targetBufferTime);
  12427. if (partIndex > -1) {
  12428. var part = partList[partIndex];
  12429. 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)));
  12430. this.nextLoadPosition = part.start + part.duration;
  12431. this.state = State.FRAG_LOADING;
  12432. var _result;
  12433. if (keyLoadingPromise) {
  12434. _result = keyLoadingPromise.then(function (keyLoadedData) {
  12435. if (!keyLoadedData || _this4.fragContextChanged(keyLoadedData.frag)) {
  12436. return null;
  12437. }
  12438. return _this4.doFragPartsLoad(frag, part, level, progressCallback);
  12439. }).catch(function (error) {
  12440. return _this4.handleFragLoadError(error);
  12441. });
  12442. } else {
  12443. _result = this.doFragPartsLoad(frag, part, level, progressCallback).catch(function (error) {
  12444. return _this4.handleFragLoadError(error);
  12445. });
  12446. }
  12447. this.hls.trigger(Events.FRAG_LOADING, {
  12448. frag: frag,
  12449. part: part,
  12450. targetBufferTime: targetBufferTime
  12451. });
  12452. if (this.fragCurrent === null) {
  12453. return Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts"));
  12454. }
  12455. return _result;
  12456. } else if (!frag.url || this.loadedEndOfParts(partList, targetBufferTime)) {
  12457. // Fragment hint has no parts
  12458. return Promise.resolve(null);
  12459. }
  12460. }
  12461. }
  12462. 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)));
  12463. // Don't update nextLoadPosition for fragments which are not buffered
  12464. if (isFiniteNumber(frag.sn) && !this.bitrateTest) {
  12465. this.nextLoadPosition = frag.start + frag.duration;
  12466. }
  12467. this.state = State.FRAG_LOADING;
  12468. // Load key before streaming fragment data
  12469. var dataOnProgress = this.config.progressive;
  12470. var result;
  12471. if (dataOnProgress && keyLoadingPromise) {
  12472. result = keyLoadingPromise.then(function (keyLoadedData) {
  12473. if (!keyLoadedData || _this4.fragContextChanged(keyLoadedData == null ? void 0 : keyLoadedData.frag)) {
  12474. return null;
  12475. }
  12476. return _this4.fragmentLoader.load(frag, progressCallback);
  12477. }).catch(function (error) {
  12478. return _this4.handleFragLoadError(error);
  12479. });
  12480. } else {
  12481. // load unencrypted fragment data with progress event,
  12482. // or handle fragment result after key and fragment are finished loading
  12483. result = Promise.all([this.fragmentLoader.load(frag, dataOnProgress ? progressCallback : undefined), keyLoadingPromise]).then(function (_ref) {
  12484. var fragLoadedData = _ref[0];
  12485. if (!dataOnProgress && fragLoadedData && progressCallback) {
  12486. progressCallback(fragLoadedData);
  12487. }
  12488. return fragLoadedData;
  12489. }).catch(function (error) {
  12490. return _this4.handleFragLoadError(error);
  12491. });
  12492. }
  12493. this.hls.trigger(Events.FRAG_LOADING, {
  12494. frag: frag,
  12495. targetBufferTime: targetBufferTime
  12496. });
  12497. if (this.fragCurrent === null) {
  12498. return Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING"));
  12499. }
  12500. return result;
  12501. };
  12502. _proto.doFragPartsLoad = function doFragPartsLoad(frag, fromPart, level, progressCallback) {
  12503. var _this5 = this;
  12504. return new Promise(function (resolve, reject) {
  12505. var _level$details;
  12506. var partsLoaded = [];
  12507. var initialPartList = (_level$details = level.details) == null ? void 0 : _level$details.partList;
  12508. var loadPart = function loadPart(part) {
  12509. _this5.fragmentLoader.loadPart(frag, part, progressCallback).then(function (partLoadedData) {
  12510. partsLoaded[part.index] = partLoadedData;
  12511. var loadedPart = partLoadedData.part;
  12512. _this5.hls.trigger(Events.FRAG_LOADED, partLoadedData);
  12513. var nextPart = getPartWith(level, frag.sn, part.index + 1) || findPart(initialPartList, frag.sn, part.index + 1);
  12514. if (nextPart) {
  12515. loadPart(nextPart);
  12516. } else {
  12517. return resolve({
  12518. frag: frag,
  12519. part: loadedPart,
  12520. partsLoaded: partsLoaded
  12521. });
  12522. }
  12523. }).catch(reject);
  12524. };
  12525. loadPart(fromPart);
  12526. });
  12527. };
  12528. _proto.handleFragLoadError = function handleFragLoadError(error) {
  12529. if ('data' in error) {
  12530. var data = error.data;
  12531. if (error.data && data.details === ErrorDetails.INTERNAL_ABORTED) {
  12532. this.handleFragLoadAborted(data.frag, data.part);
  12533. } else {
  12534. this.hls.trigger(Events.ERROR, data);
  12535. }
  12536. } else {
  12537. this.hls.trigger(Events.ERROR, {
  12538. type: ErrorTypes.OTHER_ERROR,
  12539. details: ErrorDetails.INTERNAL_EXCEPTION,
  12540. err: error,
  12541. error: error,
  12542. fatal: true
  12543. });
  12544. }
  12545. return null;
  12546. };
  12547. _proto._handleTransmuxerFlush = function _handleTransmuxerFlush(chunkMeta) {
  12548. var context = this.getCurrentContext(chunkMeta);
  12549. if (!context || this.state !== State.PARSING) {
  12550. if (!this.fragCurrent && this.state !== State.STOPPED && this.state !== State.ERROR) {
  12551. this.state = State.IDLE;
  12552. }
  12553. return;
  12554. }
  12555. var frag = context.frag,
  12556. part = context.part,
  12557. level = context.level;
  12558. var now = self.performance.now();
  12559. frag.stats.parsing.end = now;
  12560. if (part) {
  12561. part.stats.parsing.end = now;
  12562. }
  12563. this.updateLevelTiming(frag, part, level, chunkMeta.partial);
  12564. };
  12565. _proto.getCurrentContext = function getCurrentContext(chunkMeta) {
  12566. var levels = this.levels,
  12567. fragCurrent = this.fragCurrent;
  12568. var levelIndex = chunkMeta.level,
  12569. sn = chunkMeta.sn,
  12570. partIndex = chunkMeta.part;
  12571. if (!(levels != null && levels[levelIndex])) {
  12572. this.warn("Levels object was unset while buffering fragment " + sn + " of level " + levelIndex + ". The current chunk will not be buffered.");
  12573. return null;
  12574. }
  12575. var level = levels[levelIndex];
  12576. var part = partIndex > -1 ? getPartWith(level, sn, partIndex) : null;
  12577. var frag = part ? part.fragment : getFragmentWithSN(level, sn, fragCurrent);
  12578. if (!frag) {
  12579. return null;
  12580. }
  12581. if (fragCurrent && fragCurrent !== frag) {
  12582. frag.stats = fragCurrent.stats;
  12583. }
  12584. return {
  12585. frag: frag,
  12586. part: part,
  12587. level: level
  12588. };
  12589. };
  12590. _proto.bufferFragmentData = function bufferFragmentData(data, frag, part, chunkMeta, noBacktracking) {
  12591. var _buffer;
  12592. if (!data || this.state !== State.PARSING) {
  12593. return;
  12594. }
  12595. var data1 = data.data1,
  12596. data2 = data.data2;
  12597. var buffer = data1;
  12598. if (data1 && data2) {
  12599. // Combine the moof + mdat so that we buffer with a single append
  12600. buffer = appendUint8Array(data1, data2);
  12601. }
  12602. if (!((_buffer = buffer) != null && _buffer.length)) {
  12603. return;
  12604. }
  12605. var segment = {
  12606. type: data.type,
  12607. frag: frag,
  12608. part: part,
  12609. chunkMeta: chunkMeta,
  12610. parent: frag.type,
  12611. data: buffer
  12612. };
  12613. this.hls.trigger(Events.BUFFER_APPENDING, segment);
  12614. if (data.dropped && data.independent && !part) {
  12615. if (noBacktracking) {
  12616. return;
  12617. }
  12618. // Clear buffer so that we reload previous segments sequentially if required
  12619. this.flushBufferGap(frag);
  12620. }
  12621. };
  12622. _proto.flushBufferGap = function flushBufferGap(frag) {
  12623. var media = this.media;
  12624. if (!media) {
  12625. return;
  12626. }
  12627. // If currentTime is not buffered, clear the back buffer so that we can backtrack as much as needed
  12628. if (!BufferHelper.isBuffered(media, media.currentTime)) {
  12629. this.flushMainBuffer(0, frag.start);
  12630. return;
  12631. }
  12632. // Remove back-buffer without interrupting playback to allow back tracking
  12633. var currentTime = media.currentTime;
  12634. var bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  12635. var fragDuration = frag.duration;
  12636. var segmentFraction = Math.min(this.config.maxFragLookUpTolerance * 2, fragDuration * 0.25);
  12637. var start = Math.max(Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction), currentTime + segmentFraction);
  12638. if (frag.start - start > segmentFraction) {
  12639. this.flushMainBuffer(start, frag.start);
  12640. }
  12641. };
  12642. _proto.getFwdBufferInfo = function getFwdBufferInfo(bufferable, type) {
  12643. var pos = this.getLoadPosition();
  12644. if (!isFiniteNumber(pos)) {
  12645. return null;
  12646. }
  12647. return this.getFwdBufferInfoAtPos(bufferable, pos, type);
  12648. };
  12649. _proto.getFwdBufferInfoAtPos = function getFwdBufferInfoAtPos(bufferable, pos, type) {
  12650. var maxBufferHole = this.config.maxBufferHole;
  12651. var bufferInfo = BufferHelper.bufferInfo(bufferable, pos, maxBufferHole);
  12652. // Workaround flaw in getting forward buffer when maxBufferHole is smaller than gap at current pos
  12653. if (bufferInfo.len === 0 && bufferInfo.nextStart !== undefined) {
  12654. var bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type);
  12655. if (bufferedFragAtPos && bufferInfo.nextStart < bufferedFragAtPos.end) {
  12656. return BufferHelper.bufferInfo(bufferable, pos, Math.max(bufferInfo.nextStart, maxBufferHole));
  12657. }
  12658. }
  12659. return bufferInfo;
  12660. };
  12661. _proto.getMaxBufferLength = function getMaxBufferLength(levelBitrate) {
  12662. var config = this.config;
  12663. var maxBufLen;
  12664. if (levelBitrate) {
  12665. maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
  12666. } else {
  12667. maxBufLen = config.maxBufferLength;
  12668. }
  12669. return Math.min(maxBufLen, config.maxMaxBufferLength);
  12670. };
  12671. _proto.reduceMaxBufferLength = function reduceMaxBufferLength(threshold) {
  12672. var config = this.config;
  12673. var minLength = threshold || config.maxBufferLength;
  12674. var reducedLength = config.maxMaxBufferLength / 2;
  12675. if (reducedLength >= minLength) {
  12676. // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
  12677. config.maxMaxBufferLength = reducedLength;
  12678. this.warn("Reduce max buffer length to " + reducedLength + "s");
  12679. return true;
  12680. }
  12681. return false;
  12682. };
  12683. _proto.getAppendedFrag = function getAppendedFrag(position, playlistType) {
  12684. var fragOrPart = this.fragmentTracker.getAppendedFrag(position, PlaylistLevelType.MAIN);
  12685. if (fragOrPart && 'fragment' in fragOrPart) {
  12686. return fragOrPart.fragment;
  12687. }
  12688. return fragOrPart;
  12689. };
  12690. _proto.getNextFragment = function getNextFragment(pos, levelDetails) {
  12691. var fragments = levelDetails.fragments;
  12692. var fragLen = fragments.length;
  12693. if (!fragLen) {
  12694. return null;
  12695. }
  12696. // find fragment index, contiguous with end of buffer position
  12697. var config = this.config;
  12698. var start = fragments[0].start;
  12699. var frag;
  12700. if (levelDetails.live) {
  12701. var initialLiveManifestSize = config.initialLiveManifestSize;
  12702. if (fragLen < initialLiveManifestSize) {
  12703. this.warn("Not enough fragments to start playback (have: " + fragLen + ", need: " + initialLiveManifestSize + ")");
  12704. return null;
  12705. }
  12706. // The real fragment start times for a live stream are only known after the PTS range for that level is known.
  12707. // In order to discover the range, we load the best matching fragment for that level and demux it.
  12708. // Do not load using live logic if the starting frag is requested - we want to use getFragmentAtPosition() so that
  12709. // we get the fragment matching that start time
  12710. if (!levelDetails.PTSKnown && !this.startFragRequested && this.startPosition === -1 || pos < start) {
  12711. frag = this.getInitialLiveFragment(levelDetails, fragments);
  12712. this.startPosition = this.nextLoadPosition = frag ? this.hls.liveSyncPosition || frag.start : pos;
  12713. }
  12714. } else if (pos <= start) {
  12715. // VoD playlist: if loadPosition before start of playlist, load first fragment
  12716. frag = fragments[0];
  12717. }
  12718. // If we haven't run into any special cases already, just load the fragment most closely matching the requested position
  12719. if (!frag) {
  12720. var end = config.lowLatencyMode ? levelDetails.partEnd : levelDetails.fragmentEnd;
  12721. frag = this.getFragmentAtPosition(pos, end, levelDetails);
  12722. }
  12723. return this.mapToInitFragWhenRequired(frag);
  12724. };
  12725. _proto.isLoopLoading = function isLoopLoading(frag, targetBufferTime) {
  12726. var trackerState = this.fragmentTracker.getState(frag);
  12727. return (trackerState === FragmentState.OK || trackerState === FragmentState.PARTIAL && !!frag.gap) && this.nextLoadPosition > targetBufferTime;
  12728. };
  12729. _proto.getNextFragmentLoopLoading = function getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, playlistType, maxBufLen) {
  12730. var gapStart = frag.gap;
  12731. var nextFragment = this.getNextFragment(this.nextLoadPosition, levelDetails);
  12732. if (nextFragment === null) {
  12733. return nextFragment;
  12734. }
  12735. frag = nextFragment;
  12736. if (gapStart && frag && !frag.gap && bufferInfo.nextStart) {
  12737. // Media buffered after GAP tags should not make the next buffer timerange exceed forward buffer length
  12738. var nextbufferInfo = this.getFwdBufferInfoAtPos(this.mediaBuffer ? this.mediaBuffer : this.media, bufferInfo.nextStart, playlistType);
  12739. if (nextbufferInfo !== null && bufferInfo.len + nextbufferInfo.len >= maxBufLen) {
  12740. // Returning here might result in not finding an audio and video candiate to skip to
  12741. this.log("buffer full after gaps in \"" + playlistType + "\" playlist starting at sn: " + frag.sn);
  12742. return null;
  12743. }
  12744. }
  12745. return frag;
  12746. };
  12747. _proto.mapToInitFragWhenRequired = function mapToInitFragWhenRequired(frag) {
  12748. // If an initSegment is present, it must be buffered first
  12749. if (frag != null && frag.initSegment && !(frag != null && frag.initSegment.data) && !this.bitrateTest) {
  12750. return frag.initSegment;
  12751. }
  12752. return frag;
  12753. };
  12754. _proto.getNextPart = function getNextPart(partList, frag, targetBufferTime) {
  12755. var nextPart = -1;
  12756. var contiguous = false;
  12757. var independentAttrOmitted = true;
  12758. for (var i = 0, len = partList.length; i < len; i++) {
  12759. var part = partList[i];
  12760. independentAttrOmitted = independentAttrOmitted && !part.independent;
  12761. if (nextPart > -1 && targetBufferTime < part.start) {
  12762. break;
  12763. }
  12764. var loaded = part.loaded;
  12765. if (loaded) {
  12766. nextPart = -1;
  12767. } else if ((contiguous || part.independent || independentAttrOmitted) && part.fragment === frag) {
  12768. nextPart = i;
  12769. }
  12770. contiguous = loaded;
  12771. }
  12772. return nextPart;
  12773. };
  12774. _proto.loadedEndOfParts = function loadedEndOfParts(partList, targetBufferTime) {
  12775. var lastPart = partList[partList.length - 1];
  12776. return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;
  12777. }
  12778. /*
  12779. This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the
  12780. "sliding" of the playlist, which is its offset from the start of playback. After sliding we can compute the real
  12781. start and end times for each fragment in the playlist (after which this method will not need to be called).
  12782. */;
  12783. _proto.getInitialLiveFragment = function getInitialLiveFragment(levelDetails, fragments) {
  12784. var fragPrevious = this.fragPrevious;
  12785. var frag = null;
  12786. if (fragPrevious) {
  12787. if (levelDetails.hasProgramDateTime) {
  12788. // Prefer using PDT, because it can be accurate enough to choose the correct fragment without knowing the level sliding
  12789. this.log("Live playlist, switching playlist, load frag with same PDT: " + fragPrevious.programDateTime);
  12790. frag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, this.config.maxFragLookUpTolerance);
  12791. }
  12792. if (!frag) {
  12793. // SN does not need to be accurate between renditions, but depending on the packaging it may be so.
  12794. var targetSN = fragPrevious.sn + 1;
  12795. if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
  12796. var fragNext = fragments[targetSN - levelDetails.startSN];
  12797. // Ensure that we're staying within the continuity range, since PTS resets upon a new range
  12798. if (fragPrevious.cc === fragNext.cc) {
  12799. frag = fragNext;
  12800. this.log("Live playlist, switching playlist, load frag with next SN: " + frag.sn);
  12801. }
  12802. }
  12803. // It's important to stay within the continuity range if available; otherwise the fragments in the playlist
  12804. // will have the wrong start times
  12805. if (!frag) {
  12806. frag = findFragWithCC(fragments, fragPrevious.cc);
  12807. if (frag) {
  12808. this.log("Live playlist, switching playlist, load frag with same CC: " + frag.sn);
  12809. }
  12810. }
  12811. }
  12812. } else {
  12813. // Find a new start fragment when fragPrevious is null
  12814. var liveStart = this.hls.liveSyncPosition;
  12815. if (liveStart !== null) {
  12816. frag = this.getFragmentAtPosition(liveStart, this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge, levelDetails);
  12817. }
  12818. }
  12819. return frag;
  12820. }
  12821. /*
  12822. This method finds the best matching fragment given the provided position.
  12823. */;
  12824. _proto.getFragmentAtPosition = function getFragmentAtPosition(bufferEnd, end, levelDetails) {
  12825. var config = this.config;
  12826. var fragPrevious = this.fragPrevious;
  12827. var fragments = levelDetails.fragments,
  12828. endSN = levelDetails.endSN;
  12829. var fragmentHint = levelDetails.fragmentHint;
  12830. var maxFragLookUpTolerance = config.maxFragLookUpTolerance;
  12831. var partList = levelDetails.partList;
  12832. var loadingParts = !!(config.lowLatencyMode && partList != null && partList.length && fragmentHint);
  12833. if (loadingParts && fragmentHint && !this.bitrateTest) {
  12834. // Include incomplete fragment with parts at end
  12835. fragments = fragments.concat(fragmentHint);
  12836. endSN = fragmentHint.sn;
  12837. }
  12838. var frag;
  12839. if (bufferEnd < end) {
  12840. var lookupTolerance = bufferEnd > end - maxFragLookUpTolerance ? 0 : maxFragLookUpTolerance;
  12841. // Remove the tolerance if it would put the bufferEnd past the actual end of stream
  12842. // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
  12843. frag = findFragmentByPTS(fragPrevious, fragments, bufferEnd, lookupTolerance);
  12844. } else {
  12845. // reach end of playlist
  12846. frag = fragments[fragments.length - 1];
  12847. }
  12848. if (frag) {
  12849. var curSNIdx = frag.sn - levelDetails.startSN;
  12850. // Move fragPrevious forward to support forcing the next fragment to load
  12851. // when the buffer catches up to a previously buffered range.
  12852. var fragState = this.fragmentTracker.getState(frag);
  12853. if (fragState === FragmentState.OK || fragState === FragmentState.PARTIAL && frag.gap) {
  12854. fragPrevious = frag;
  12855. }
  12856. if (fragPrevious && frag.sn === fragPrevious.sn && (!loadingParts || partList[0].fragment.sn > frag.sn)) {
  12857. // Force the next fragment to load if the previous one was already selected. This can occasionally happen with
  12858. // non-uniform fragment durations
  12859. var sameLevel = fragPrevious && frag.level === fragPrevious.level;
  12860. if (sameLevel) {
  12861. var nextFrag = fragments[curSNIdx + 1];
  12862. if (frag.sn < endSN && this.fragmentTracker.getState(nextFrag) !== FragmentState.OK) {
  12863. frag = nextFrag;
  12864. } else {
  12865. frag = null;
  12866. }
  12867. }
  12868. }
  12869. }
  12870. return frag;
  12871. };
  12872. _proto.synchronizeToLiveEdge = function synchronizeToLiveEdge(levelDetails) {
  12873. var config = this.config,
  12874. media = this.media;
  12875. if (!media) {
  12876. return;
  12877. }
  12878. var liveSyncPosition = this.hls.liveSyncPosition;
  12879. var currentTime = media.currentTime;
  12880. var start = levelDetails.fragments[0].start;
  12881. var end = levelDetails.edge;
  12882. var withinSlidingWindow = currentTime >= start - config.maxFragLookUpTolerance && currentTime <= end;
  12883. // Continue if we can seek forward to sync position or if current time is outside of sliding window
  12884. if (liveSyncPosition !== null && media.duration > liveSyncPosition && (currentTime < liveSyncPosition || !withinSlidingWindow)) {
  12885. // Continue if buffer is starving or if current time is behind max latency
  12886. var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
  12887. if (!withinSlidingWindow && media.readyState < 4 || currentTime < end - maxLatency) {
  12888. if (!this.loadedmetadata) {
  12889. this.nextLoadPosition = liveSyncPosition;
  12890. }
  12891. // Only seek if ready and there is not a significant forward buffer available for playback
  12892. if (media.readyState) {
  12893. this.warn("Playback: " + currentTime.toFixed(3) + " is located too far from the end of live sliding playlist: " + end + ", reset currentTime to : " + liveSyncPosition.toFixed(3));
  12894. media.currentTime = liveSyncPosition;
  12895. }
  12896. }
  12897. }
  12898. };
  12899. _proto.alignPlaylists = function alignPlaylists(details, previousDetails, switchDetails) {
  12900. // FIXME: If not for `shouldAlignOnDiscontinuities` requiring fragPrevious.cc,
  12901. // this could all go in level-helper mergeDetails()
  12902. var length = details.fragments.length;
  12903. if (!length) {
  12904. this.warn("No fragments in live playlist");
  12905. return 0;
  12906. }
  12907. var slidingStart = details.fragments[0].start;
  12908. var firstLevelLoad = !previousDetails;
  12909. var aligned = details.alignedSliding && isFiniteNumber(slidingStart);
  12910. if (firstLevelLoad || !aligned && !slidingStart) {
  12911. var fragPrevious = this.fragPrevious;
  12912. alignStream(fragPrevious, switchDetails, details);
  12913. var alignedSlidingStart = details.fragments[0].start;
  12914. this.log("Live playlist sliding: " + alignedSlidingStart.toFixed(2) + " start-sn: " + (previousDetails ? previousDetails.startSN : 'na') + "->" + details.startSN + " prev-sn: " + (fragPrevious ? fragPrevious.sn : 'na') + " fragments: " + length);
  12915. return alignedSlidingStart;
  12916. }
  12917. return slidingStart;
  12918. };
  12919. _proto.waitForCdnTuneIn = function waitForCdnTuneIn(details) {
  12920. // Wait for Low-Latency CDN Tune-in to get an updated playlist
  12921. var advancePartLimit = 3;
  12922. return details.live && details.canBlockReload && details.partTarget && details.tuneInGoal > Math.max(details.partHoldBack, details.partTarget * advancePartLimit);
  12923. };
  12924. _proto.setStartPosition = function setStartPosition(details, sliding) {
  12925. // compute start position if set to -1. use it straight away if value is defined
  12926. var startPosition = this.startPosition;
  12927. if (startPosition < sliding) {
  12928. startPosition = -1;
  12929. }
  12930. if (startPosition === -1 || this.lastCurrentTime === -1) {
  12931. // Use Playlist EXT-X-START:TIME-OFFSET when set
  12932. // Prioritize Multivariant Playlist offset so that main, audio, and subtitle stream-controller start times match
  12933. var offsetInMultivariantPlaylist = this.startTimeOffset !== null;
  12934. var startTimeOffset = offsetInMultivariantPlaylist ? this.startTimeOffset : details.startTimeOffset;
  12935. if (startTimeOffset !== null && isFiniteNumber(startTimeOffset)) {
  12936. startPosition = sliding + startTimeOffset;
  12937. if (startTimeOffset < 0) {
  12938. startPosition += details.totalduration;
  12939. }
  12940. startPosition = Math.min(Math.max(sliding, startPosition), sliding + details.totalduration);
  12941. this.log("Start time offset " + startTimeOffset + " found in " + (offsetInMultivariantPlaylist ? 'multivariant' : 'media') + " playlist, adjust startPosition to " + startPosition);
  12942. this.startPosition = startPosition;
  12943. } else if (details.live) {
  12944. // Leave this.startPosition at -1, so that we can use `getInitialLiveFragment` logic when startPosition has
  12945. // not been specified via the config or an as an argument to startLoad (#3736).
  12946. startPosition = this.hls.liveSyncPosition || sliding;
  12947. } else {
  12948. this.startPosition = startPosition = 0;
  12949. }
  12950. this.lastCurrentTime = startPosition;
  12951. }
  12952. this.nextLoadPosition = startPosition;
  12953. };
  12954. _proto.getLoadPosition = function getLoadPosition() {
  12955. var media = this.media;
  12956. // if we have not yet loaded any fragment, start loading from start position
  12957. var pos = 0;
  12958. if (this.loadedmetadata && media) {
  12959. pos = media.currentTime;
  12960. } else if (this.nextLoadPosition) {
  12961. pos = this.nextLoadPosition;
  12962. }
  12963. return pos;
  12964. };
  12965. _proto.handleFragLoadAborted = function handleFragLoadAborted(frag, part) {
  12966. if (this.transmuxer && frag.sn !== 'initSegment' && frag.stats.aborted) {
  12967. this.warn("Fragment " + frag.sn + (part ? ' part ' + part.index : '') + " of level " + frag.level + " was aborted");
  12968. this.resetFragmentLoading(frag);
  12969. }
  12970. };
  12971. _proto.resetFragmentLoading = function resetFragmentLoading(frag) {
  12972. if (!this.fragCurrent || !this.fragContextChanged(frag) && this.state !== State.FRAG_LOADING_WAITING_RETRY) {
  12973. this.state = State.IDLE;
  12974. }
  12975. };
  12976. _proto.onFragmentOrKeyLoadError = function onFragmentOrKeyLoadError(filterType, data) {
  12977. if (data.chunkMeta && !data.frag) {
  12978. var context = this.getCurrentContext(data.chunkMeta);
  12979. if (context) {
  12980. data.frag = context.frag;
  12981. }
  12982. }
  12983. var frag = data.frag;
  12984. // Handle frag error related to caller's filterType
  12985. if (!frag || frag.type !== filterType || !this.levels) {
  12986. return;
  12987. }
  12988. if (this.fragContextChanged(frag)) {
  12989. var _this$fragCurrent2;
  12990. this.warn("Frag load error must match current frag to retry " + frag.url + " > " + ((_this$fragCurrent2 = this.fragCurrent) == null ? void 0 : _this$fragCurrent2.url));
  12991. return;
  12992. }
  12993. var gapTagEncountered = data.details === ErrorDetails.FRAG_GAP;
  12994. if (gapTagEncountered) {
  12995. this.fragmentTracker.fragBuffered(frag, true);
  12996. }
  12997. // keep retrying until the limit will be reached
  12998. var errorAction = data.errorAction;
  12999. var _ref2 = errorAction || {},
  13000. action = _ref2.action,
  13001. _ref2$retryCount = _ref2.retryCount,
  13002. retryCount = _ref2$retryCount === void 0 ? 0 : _ref2$retryCount,
  13003. retryConfig = _ref2.retryConfig;
  13004. if (errorAction && action === NetworkErrorAction.RetryRequest && retryConfig) {
  13005. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  13006. var delay = getRetryDelay(retryConfig, retryCount);
  13007. this.warn("Fragment " + frag.sn + " of " + filterType + " " + frag.level + " errored with " + data.details + ", retrying loading " + (retryCount + 1) + "/" + retryConfig.maxNumRetry + " in " + delay + "ms");
  13008. errorAction.resolved = true;
  13009. this.retryDate = self.performance.now() + delay;
  13010. this.state = State.FRAG_LOADING_WAITING_RETRY;
  13011. } else if (retryConfig && errorAction) {
  13012. this.resetFragmentErrors(filterType);
  13013. if (retryCount < retryConfig.maxNumRetry) {
  13014. // Network retry is skipped when level switch is preferred
  13015. if (!gapTagEncountered && action !== NetworkErrorAction.RemoveAlternatePermanently) {
  13016. errorAction.resolved = true;
  13017. }
  13018. } else {
  13019. logger.warn(data.details + " reached or exceeded max retry (" + retryCount + ")");
  13020. return;
  13021. }
  13022. } else if ((errorAction == null ? void 0 : errorAction.action) === NetworkErrorAction.SendAlternateToPenaltyBox) {
  13023. this.state = State.WAITING_LEVEL;
  13024. } else {
  13025. this.state = State.ERROR;
  13026. }
  13027. // Perform next async tick sooner to speed up error action resolution
  13028. this.tickImmediate();
  13029. };
  13030. _proto.reduceLengthAndFlushBuffer = function reduceLengthAndFlushBuffer(data) {
  13031. // if in appending state
  13032. if (this.state === State.PARSING || this.state === State.PARSED) {
  13033. var playlistType = data.parent;
  13034. var bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  13035. // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
  13036. // reduce max buf len if current position is buffered
  13037. var buffered = bufferedInfo && bufferedInfo.len > 0.5;
  13038. if (buffered) {
  13039. this.reduceMaxBufferLength(bufferedInfo.len);
  13040. }
  13041. var flushBuffer = !buffered;
  13042. if (flushBuffer) {
  13043. // current position is not buffered, but browser is still complaining about buffer full error
  13044. // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
  13045. // in that case flush the whole audio buffer to recover
  13046. this.warn("Buffer full error while media.currentTime is not buffered, flush " + playlistType + " buffer");
  13047. }
  13048. if (data.frag) {
  13049. this.fragmentTracker.removeFragment(data.frag);
  13050. this.nextLoadPosition = data.frag.start;
  13051. }
  13052. this.resetLoadingState();
  13053. return flushBuffer;
  13054. }
  13055. return false;
  13056. };
  13057. _proto.resetFragmentErrors = function resetFragmentErrors(filterType) {
  13058. if (filterType === PlaylistLevelType.AUDIO) {
  13059. // Reset current fragment since audio track audio is essential and may not have a fail-over track
  13060. this.fragCurrent = null;
  13061. }
  13062. // Fragment errors that result in a level switch or redundant fail-over
  13063. // should reset the stream controller state to idle
  13064. if (!this.loadedmetadata) {
  13065. this.startFragRequested = false;
  13066. }
  13067. if (this.state !== State.STOPPED) {
  13068. this.state = State.IDLE;
  13069. }
  13070. };
  13071. _proto.afterBufferFlushed = function afterBufferFlushed(media, bufferType, playlistType) {
  13072. if (!media) {
  13073. return;
  13074. }
  13075. // After successful buffer flushing, filter flushed fragments from bufferedFrags use mediaBuffered instead of media
  13076. // (so that we will check against video.buffered ranges in case of alt audio track)
  13077. var bufferedTimeRanges = BufferHelper.getBuffered(media);
  13078. this.fragmentTracker.detectEvictedFragments(bufferType, bufferedTimeRanges, playlistType);
  13079. if (this.state === State.ENDED) {
  13080. this.resetLoadingState();
  13081. }
  13082. };
  13083. _proto.resetLoadingState = function resetLoadingState() {
  13084. this.log('Reset loading state');
  13085. this.fragCurrent = null;
  13086. this.fragPrevious = null;
  13087. this.state = State.IDLE;
  13088. };
  13089. _proto.resetStartWhenNotLoaded = function resetStartWhenNotLoaded(level) {
  13090. // if loadedmetadata is not set, it means that first frag request failed
  13091. // in that case, reset startFragRequested flag
  13092. if (!this.loadedmetadata) {
  13093. this.startFragRequested = false;
  13094. var details = level ? level.details : null;
  13095. if (details != null && details.live) {
  13096. // Update the start position and return to IDLE to recover live start
  13097. this.startPosition = -1;
  13098. this.setStartPosition(details, 0);
  13099. this.resetLoadingState();
  13100. } else {
  13101. this.nextLoadPosition = this.startPosition;
  13102. }
  13103. }
  13104. };
  13105. _proto.resetWhenMissingContext = function resetWhenMissingContext(chunkMeta) {
  13106. this.warn("The loading context changed while buffering fragment " + chunkMeta.sn + " of level " + chunkMeta.level + ". This chunk will not be buffered.");
  13107. this.removeUnbufferedFrags();
  13108. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  13109. this.resetLoadingState();
  13110. };
  13111. _proto.removeUnbufferedFrags = function removeUnbufferedFrags(start) {
  13112. if (start === void 0) {
  13113. start = 0;
  13114. }
  13115. this.fragmentTracker.removeFragmentsInRange(start, Infinity, this.playlistType, false, true);
  13116. };
  13117. _proto.updateLevelTiming = function updateLevelTiming(frag, part, level, partial) {
  13118. var _this6 = this,
  13119. _this$transmuxer;
  13120. var details = level.details;
  13121. if (!details) {
  13122. this.warn('level.details undefined');
  13123. return;
  13124. }
  13125. var parsed = Object.keys(frag.elementaryStreams).reduce(function (result, type) {
  13126. var info = frag.elementaryStreams[type];
  13127. if (info) {
  13128. var parsedDuration = info.endPTS - info.startPTS;
  13129. if (parsedDuration <= 0) {
  13130. // Destroy the transmuxer after it's next time offset failed to advance because duration was <= 0.
  13131. // The new transmuxer will be configured with a time offset matching the next fragment start,
  13132. // preventing the timeline from shifting.
  13133. _this6.warn("Could not parse fragment " + frag.sn + " " + type + " duration reliably (" + parsedDuration + ")");
  13134. return result || false;
  13135. }
  13136. var drift = partial ? 0 : updateFragPTSDTS(details, frag, info.startPTS, info.endPTS, info.startDTS, info.endDTS);
  13137. _this6.hls.trigger(Events.LEVEL_PTS_UPDATED, {
  13138. details: details,
  13139. level: level,
  13140. drift: drift,
  13141. type: type,
  13142. frag: frag,
  13143. start: info.startPTS,
  13144. end: info.endPTS
  13145. });
  13146. return true;
  13147. }
  13148. return result;
  13149. }, false);
  13150. if (!parsed && ((_this$transmuxer = this.transmuxer) == null ? void 0 : _this$transmuxer.error) === null) {
  13151. var error = new Error("Found no media in fragment " + frag.sn + " of level " + frag.level + " resetting transmuxer to fallback to playlist timing");
  13152. if (level.fragmentError === 0) {
  13153. // Mark and track the odd empty segment as a gap to avoid reloading
  13154. level.fragmentError++;
  13155. frag.gap = true;
  13156. this.fragmentTracker.removeFragment(frag);
  13157. this.fragmentTracker.fragBuffered(frag, true);
  13158. }
  13159. this.warn(error.message);
  13160. this.hls.trigger(Events.ERROR, {
  13161. type: ErrorTypes.MEDIA_ERROR,
  13162. details: ErrorDetails.FRAG_PARSING_ERROR,
  13163. fatal: false,
  13164. error: error,
  13165. frag: frag,
  13166. reason: "Found no media in msn " + frag.sn + " of level \"" + level.url + "\""
  13167. });
  13168. if (!this.hls) {
  13169. return;
  13170. }
  13171. this.resetTransmuxer();
  13172. // For this error fallthrough. Marking parsed will allow advancing to next fragment.
  13173. }
  13174. this.state = State.PARSED;
  13175. this.hls.trigger(Events.FRAG_PARSED, {
  13176. frag: frag,
  13177. part: part
  13178. });
  13179. };
  13180. _proto.resetTransmuxer = function resetTransmuxer() {
  13181. if (this.transmuxer) {
  13182. this.transmuxer.destroy();
  13183. this.transmuxer = null;
  13184. }
  13185. };
  13186. _proto.recoverWorkerError = function recoverWorkerError(data) {
  13187. if (data.event === 'demuxerWorker') {
  13188. this.fragmentTracker.removeAllFragments();
  13189. this.resetTransmuxer();
  13190. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  13191. this.resetLoadingState();
  13192. }
  13193. };
  13194. _createClass(BaseStreamController, [{
  13195. key: "state",
  13196. get: function get() {
  13197. return this._state;
  13198. },
  13199. set: function set(nextState) {
  13200. var previousState = this._state;
  13201. if (previousState !== nextState) {
  13202. this._state = nextState;
  13203. this.log(previousState + "->" + nextState);
  13204. }
  13205. }
  13206. }]);
  13207. return BaseStreamController;
  13208. }(TaskLoop);
  13209. function getSourceBuffer() {
  13210. return self.SourceBuffer || self.WebKitSourceBuffer;
  13211. }
  13212. function isMSESupported() {
  13213. var mediaSource = getMediaSource();
  13214. if (!mediaSource) {
  13215. return false;
  13216. }
  13217. // if SourceBuffer is exposed ensure its API is valid
  13218. // Older browsers do not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible
  13219. var sourceBuffer = getSourceBuffer();
  13220. return !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function';
  13221. }
  13222. function isSupported() {
  13223. if (!isMSESupported()) {
  13224. return false;
  13225. }
  13226. var mediaSource = getMediaSource();
  13227. 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) {
  13228. return mediaSource.isTypeSupported(mimeTypeForCodec(codecsForVideoContainer, 'video'));
  13229. }) || ['mp4a.40.2', 'fLaC'].some(function (codecForAudioContainer) {
  13230. return mediaSource.isTypeSupported(mimeTypeForCodec(codecForAudioContainer, 'audio'));
  13231. }));
  13232. }
  13233. function changeTypeSupported() {
  13234. var _sourceBuffer$prototy;
  13235. var sourceBuffer = getSourceBuffer();
  13236. return typeof (sourceBuffer == null ? void 0 : (_sourceBuffer$prototy = sourceBuffer.prototype) == null ? void 0 : _sourceBuffer$prototy.changeType) === 'function';
  13237. }
  13238. function dummyTrack(type, inputTimeScale) {
  13239. if (type === void 0) {
  13240. type = '';
  13241. }
  13242. if (inputTimeScale === void 0) {
  13243. inputTimeScale = 90000;
  13244. }
  13245. return {
  13246. type: type,
  13247. id: -1,
  13248. pid: -1,
  13249. inputTimeScale: inputTimeScale,
  13250. sequenceNumber: -1,
  13251. samples: [],
  13252. dropped: 0
  13253. };
  13254. }
  13255. var BaseAudioDemuxer = /*#__PURE__*/function () {
  13256. function BaseAudioDemuxer() {
  13257. this._audioTrack = void 0;
  13258. this._id3Track = void 0;
  13259. this.frameIndex = 0;
  13260. this.cachedData = null;
  13261. this.basePTS = null;
  13262. this.initPTS = null;
  13263. this.lastPTS = null;
  13264. }
  13265. var _proto = BaseAudioDemuxer.prototype;
  13266. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  13267. this._id3Track = {
  13268. type: 'id3',
  13269. id: 3,
  13270. pid: -1,
  13271. inputTimeScale: 90000,
  13272. sequenceNumber: 0,
  13273. samples: [],
  13274. dropped: 0
  13275. };
  13276. };
  13277. _proto.resetTimeStamp = function resetTimeStamp(deaultTimestamp) {
  13278. this.initPTS = deaultTimestamp;
  13279. this.resetContiguity();
  13280. };
  13281. _proto.resetContiguity = function resetContiguity() {
  13282. this.basePTS = null;
  13283. this.lastPTS = null;
  13284. this.frameIndex = 0;
  13285. };
  13286. _proto.canParse = function canParse(data, offset) {
  13287. return false;
  13288. };
  13289. _proto.appendFrame = function appendFrame(track, data, offset) {}
  13290. // feed incoming data to the front of the parsing pipeline
  13291. ;
  13292. _proto.demux = function demux(data, timeOffset) {
  13293. if (this.cachedData) {
  13294. data = appendUint8Array(this.cachedData, data);
  13295. this.cachedData = null;
  13296. }
  13297. var id3Data = getID3Data(data, 0);
  13298. var offset = id3Data ? id3Data.length : 0;
  13299. var lastDataIndex;
  13300. var track = this._audioTrack;
  13301. var id3Track = this._id3Track;
  13302. var timestamp = id3Data ? getTimeStamp(id3Data) : undefined;
  13303. var length = data.length;
  13304. if (this.basePTS === null || this.frameIndex === 0 && isFiniteNumber(timestamp)) {
  13305. this.basePTS = initPTSFn(timestamp, timeOffset, this.initPTS);
  13306. this.lastPTS = this.basePTS;
  13307. }
  13308. if (this.lastPTS === null) {
  13309. this.lastPTS = this.basePTS;
  13310. }
  13311. // more expressive than alternative: id3Data?.length
  13312. if (id3Data && id3Data.length > 0) {
  13313. id3Track.samples.push({
  13314. pts: this.lastPTS,
  13315. dts: this.lastPTS,
  13316. data: id3Data,
  13317. type: MetadataSchema.audioId3,
  13318. duration: Number.POSITIVE_INFINITY
  13319. });
  13320. }
  13321. while (offset < length) {
  13322. if (this.canParse(data, offset)) {
  13323. var frame = this.appendFrame(track, data, offset);
  13324. if (frame) {
  13325. this.frameIndex++;
  13326. this.lastPTS = frame.sample.pts;
  13327. offset += frame.length;
  13328. lastDataIndex = offset;
  13329. } else {
  13330. offset = length;
  13331. }
  13332. } else if (canParse$2(data, offset)) {
  13333. // after a ID3.canParse, a call to ID3.getID3Data *should* always returns some data
  13334. id3Data = getID3Data(data, offset);
  13335. id3Track.samples.push({
  13336. pts: this.lastPTS,
  13337. dts: this.lastPTS,
  13338. data: id3Data,
  13339. type: MetadataSchema.audioId3,
  13340. duration: Number.POSITIVE_INFINITY
  13341. });
  13342. offset += id3Data.length;
  13343. lastDataIndex = offset;
  13344. } else {
  13345. offset++;
  13346. }
  13347. if (offset === length && lastDataIndex !== length) {
  13348. var partialData = sliceUint8(data, lastDataIndex);
  13349. if (this.cachedData) {
  13350. this.cachedData = appendUint8Array(this.cachedData, partialData);
  13351. } else {
  13352. this.cachedData = partialData;
  13353. }
  13354. }
  13355. }
  13356. return {
  13357. audioTrack: track,
  13358. videoTrack: dummyTrack(),
  13359. id3Track: id3Track,
  13360. textTrack: dummyTrack()
  13361. };
  13362. };
  13363. _proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
  13364. return Promise.reject(new Error("[" + this + "] This demuxer does not support Sample-AES decryption"));
  13365. };
  13366. _proto.flush = function flush(timeOffset) {
  13367. // Parse cache in case of remaining frames.
  13368. var cachedData = this.cachedData;
  13369. if (cachedData) {
  13370. this.cachedData = null;
  13371. this.demux(cachedData, 0);
  13372. }
  13373. return {
  13374. audioTrack: this._audioTrack,
  13375. videoTrack: dummyTrack(),
  13376. id3Track: this._id3Track,
  13377. textTrack: dummyTrack()
  13378. };
  13379. };
  13380. _proto.destroy = function destroy() {};
  13381. return BaseAudioDemuxer;
  13382. }();
  13383. /**
  13384. * Initialize PTS
  13385. * <p>
  13386. * use timestamp unless it is undefined, NaN or Infinity
  13387. * </p>
  13388. */
  13389. var initPTSFn = function initPTSFn(timestamp, timeOffset, initPTS) {
  13390. if (isFiniteNumber(timestamp)) {
  13391. return timestamp * 90;
  13392. }
  13393. var init90kHz = initPTS ? initPTS.baseTime * 90000 / initPTS.timescale : 0;
  13394. return timeOffset * 90000 + init90kHz;
  13395. };
  13396. /**
  13397. * ADTS parser helper
  13398. * @link https://wiki.multimedia.cx/index.php?title=ADTS
  13399. */
  13400. function getAudioConfig(observer, data, offset, audioCodec) {
  13401. var adtsObjectType;
  13402. var adtsExtensionSamplingIndex;
  13403. var adtsChannelConfig;
  13404. var config;
  13405. var userAgent = navigator.userAgent.toLowerCase();
  13406. var manifestCodec = audioCodec;
  13407. var adtsSamplingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  13408. // byte 2
  13409. adtsObjectType = ((data[offset + 2] & 0xc0) >>> 6) + 1;
  13410. var adtsSamplingIndex = (data[offset + 2] & 0x3c) >>> 2;
  13411. if (adtsSamplingIndex > adtsSamplingRates.length - 1) {
  13412. var error = new Error("invalid ADTS sampling index:" + adtsSamplingIndex);
  13413. observer.emit(Events.ERROR, Events.ERROR, {
  13414. type: ErrorTypes.MEDIA_ERROR,
  13415. details: ErrorDetails.FRAG_PARSING_ERROR,
  13416. fatal: true,
  13417. error: error,
  13418. reason: error.message
  13419. });
  13420. return;
  13421. }
  13422. adtsChannelConfig = (data[offset + 2] & 0x01) << 2;
  13423. // byte 3
  13424. adtsChannelConfig |= (data[offset + 3] & 0xc0) >>> 6;
  13425. logger.log("manifest codec:" + audioCodec + ", ADTS type:" + adtsObjectType + ", samplingIndex:" + adtsSamplingIndex);
  13426. // firefox: freq less than 24kHz = AAC SBR (HE-AAC)
  13427. if (/firefox/i.test(userAgent)) {
  13428. if (adtsSamplingIndex >= 6) {
  13429. adtsObjectType = 5;
  13430. config = new Array(4);
  13431. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  13432. // there is a factor 2 between frame sample rate and output sample rate
  13433. // multiply frequency by 2 (see table below, equivalent to substract 3)
  13434. adtsExtensionSamplingIndex = adtsSamplingIndex - 3;
  13435. } else {
  13436. adtsObjectType = 2;
  13437. config = new Array(2);
  13438. adtsExtensionSamplingIndex = adtsSamplingIndex;
  13439. }
  13440. // Android : always use AAC
  13441. } else if (userAgent.indexOf('android') !== -1) {
  13442. adtsObjectType = 2;
  13443. config = new Array(2);
  13444. adtsExtensionSamplingIndex = adtsSamplingIndex;
  13445. } else {
  13446. /* for other browsers (Chrome/Vivaldi/Opera ...)
  13447. always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)
  13448. */
  13449. adtsObjectType = 5;
  13450. config = new Array(4);
  13451. // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)
  13452. if (audioCodec && (audioCodec.indexOf('mp4a.40.29') !== -1 || audioCodec.indexOf('mp4a.40.5') !== -1) || !audioCodec && adtsSamplingIndex >= 6) {
  13453. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  13454. // there is a factor 2 between frame sample rate and output sample rate
  13455. // multiply frequency by 2 (see table below, equivalent to substract 3)
  13456. adtsExtensionSamplingIndex = adtsSamplingIndex - 3;
  13457. } else {
  13458. // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)
  13459. // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.
  13460. if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && (adtsSamplingIndex >= 6 && adtsChannelConfig === 1 || /vivaldi/i.test(userAgent)) || !audioCodec && adtsChannelConfig === 1) {
  13461. adtsObjectType = 2;
  13462. config = new Array(2);
  13463. }
  13464. adtsExtensionSamplingIndex = adtsSamplingIndex;
  13465. }
  13466. }
  13467. /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config
  13468. ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()
  13469. Audio Profile / Audio Object Type
  13470. 0: Null
  13471. 1: AAC Main
  13472. 2: AAC LC (Low Complexity)
  13473. 3: AAC SSR (Scalable Sample Rate)
  13474. 4: AAC LTP (Long Term Prediction)
  13475. 5: SBR (Spectral Band Replication)
  13476. 6: AAC Scalable
  13477. sampling freq
  13478. 0: 96000 Hz
  13479. 1: 88200 Hz
  13480. 2: 64000 Hz
  13481. 3: 48000 Hz
  13482. 4: 44100 Hz
  13483. 5: 32000 Hz
  13484. 6: 24000 Hz
  13485. 7: 22050 Hz
  13486. 8: 16000 Hz
  13487. 9: 12000 Hz
  13488. 10: 11025 Hz
  13489. 11: 8000 Hz
  13490. 12: 7350 Hz
  13491. 13: Reserved
  13492. 14: Reserved
  13493. 15: frequency is written explictly
  13494. Channel Configurations
  13495. These are the channel configurations:
  13496. 0: Defined in AOT Specifc Config
  13497. 1: 1 channel: front-center
  13498. 2: 2 channels: front-left, front-right
  13499. */
  13500. // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1
  13501. config[0] = adtsObjectType << 3;
  13502. // samplingFrequencyIndex
  13503. config[0] |= (adtsSamplingIndex & 0x0e) >> 1;
  13504. config[1] |= (adtsSamplingIndex & 0x01) << 7;
  13505. // channelConfiguration
  13506. config[1] |= adtsChannelConfig << 3;
  13507. if (adtsObjectType === 5) {
  13508. // adtsExtensionSamplingIndex
  13509. config[1] |= (adtsExtensionSamplingIndex & 0x0e) >> 1;
  13510. config[2] = (adtsExtensionSamplingIndex & 0x01) << 7;
  13511. // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???
  13512. // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc
  13513. config[2] |= 2 << 2;
  13514. config[3] = 0;
  13515. }
  13516. return {
  13517. config: config,
  13518. samplerate: adtsSamplingRates[adtsSamplingIndex],
  13519. channelCount: adtsChannelConfig,
  13520. codec: 'mp4a.40.' + adtsObjectType,
  13521. manifestCodec: manifestCodec
  13522. };
  13523. }
  13524. function isHeaderPattern$1(data, offset) {
  13525. return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;
  13526. }
  13527. function getHeaderLength(data, offset) {
  13528. return data[offset + 1] & 0x01 ? 7 : 9;
  13529. }
  13530. function getFullFrameLength(data, offset) {
  13531. return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xe0) >>> 5;
  13532. }
  13533. function canGetFrameLength(data, offset) {
  13534. return offset + 5 < data.length;
  13535. }
  13536. function isHeader$1(data, offset) {
  13537. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  13538. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  13539. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  13540. return offset + 1 < data.length && isHeaderPattern$1(data, offset);
  13541. }
  13542. function canParse$1(data, offset) {
  13543. return canGetFrameLength(data, offset) && isHeaderPattern$1(data, offset) && getFullFrameLength(data, offset) <= data.length - offset;
  13544. }
  13545. function probe$1(data, offset) {
  13546. // same as isHeader but we also check that ADTS frame follows last ADTS frame
  13547. // or end of data is reached
  13548. if (isHeader$1(data, offset)) {
  13549. // ADTS header Length
  13550. var headerLength = getHeaderLength(data, offset);
  13551. if (offset + headerLength >= data.length) {
  13552. return false;
  13553. }
  13554. // ADTS frame Length
  13555. var frameLength = getFullFrameLength(data, offset);
  13556. if (frameLength <= headerLength) {
  13557. return false;
  13558. }
  13559. var newOffset = offset + frameLength;
  13560. return newOffset === data.length || isHeader$1(data, newOffset);
  13561. }
  13562. return false;
  13563. }
  13564. function initTrackConfig(track, observer, data, offset, audioCodec) {
  13565. if (!track.samplerate) {
  13566. var config = getAudioConfig(observer, data, offset, audioCodec);
  13567. if (!config) {
  13568. return;
  13569. }
  13570. track.config = config.config;
  13571. track.samplerate = config.samplerate;
  13572. track.channelCount = config.channelCount;
  13573. track.codec = config.codec;
  13574. track.manifestCodec = config.manifestCodec;
  13575. logger.log("parsed codec:" + track.codec + ", rate:" + config.samplerate + ", channels:" + config.channelCount);
  13576. }
  13577. }
  13578. function getFrameDuration(samplerate) {
  13579. return 1024 * 90000 / samplerate;
  13580. }
  13581. function parseFrameHeader(data, offset) {
  13582. // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
  13583. var headerLength = getHeaderLength(data, offset);
  13584. if (offset + headerLength <= data.length) {
  13585. // retrieve frame size
  13586. var frameLength = getFullFrameLength(data, offset) - headerLength;
  13587. if (frameLength > 0) {
  13588. // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}`);
  13589. return {
  13590. headerLength: headerLength,
  13591. frameLength: frameLength
  13592. };
  13593. }
  13594. }
  13595. }
  13596. function appendFrame$1(track, data, offset, pts, frameIndex) {
  13597. var frameDuration = getFrameDuration(track.samplerate);
  13598. var stamp = pts + frameIndex * frameDuration;
  13599. var header = parseFrameHeader(data, offset);
  13600. var unit;
  13601. if (header) {
  13602. var frameLength = header.frameLength,
  13603. headerLength = header.headerLength;
  13604. var _length = headerLength + frameLength;
  13605. var missing = Math.max(0, offset + _length - data.length);
  13606. // logger.log(`AAC frame ${frameIndex}, pts:${stamp} length@offset/total: ${frameLength}@${offset+headerLength}/${data.byteLength} missing: ${missing}`);
  13607. if (missing) {
  13608. unit = new Uint8Array(_length - headerLength);
  13609. unit.set(data.subarray(offset + headerLength, data.length), 0);
  13610. } else {
  13611. unit = data.subarray(offset + headerLength, offset + _length);
  13612. }
  13613. var _sample = {
  13614. unit: unit,
  13615. pts: stamp
  13616. };
  13617. if (!missing) {
  13618. track.samples.push(_sample);
  13619. }
  13620. return {
  13621. sample: _sample,
  13622. length: _length,
  13623. missing: missing
  13624. };
  13625. }
  13626. // overflow incomplete header
  13627. var length = data.length - offset;
  13628. unit = new Uint8Array(length);
  13629. unit.set(data.subarray(offset, data.length), 0);
  13630. var sample = {
  13631. unit: unit,
  13632. pts: stamp
  13633. };
  13634. return {
  13635. sample: sample,
  13636. length: length,
  13637. missing: -1
  13638. };
  13639. }
  13640. /**
  13641. * MPEG parser helper
  13642. */
  13643. var chromeVersion$1 = null;
  13644. 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];
  13645. var SamplingRateMap = [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000];
  13646. var SamplesCoefficients = [
  13647. // MPEG 2.5
  13648. [0,
  13649. // Reserved
  13650. 72,
  13651. // Layer3
  13652. 144,
  13653. // Layer2
  13654. 12 // Layer1
  13655. ],
  13656. // Reserved
  13657. [0,
  13658. // Reserved
  13659. 0,
  13660. // Layer3
  13661. 0,
  13662. // Layer2
  13663. 0 // Layer1
  13664. ],
  13665. // MPEG 2
  13666. [0,
  13667. // Reserved
  13668. 72,
  13669. // Layer3
  13670. 144,
  13671. // Layer2
  13672. 12 // Layer1
  13673. ],
  13674. // MPEG 1
  13675. [0,
  13676. // Reserved
  13677. 144,
  13678. // Layer3
  13679. 144,
  13680. // Layer2
  13681. 12 // Layer1
  13682. ]];
  13683. var BytesInSlot = [0,
  13684. // Reserved
  13685. 1,
  13686. // Layer3
  13687. 1,
  13688. // Layer2
  13689. 4 // Layer1
  13690. ];
  13691. function appendFrame(track, data, offset, pts, frameIndex) {
  13692. // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference
  13693. if (offset + 24 > data.length) {
  13694. return;
  13695. }
  13696. var header = parseHeader(data, offset);
  13697. if (header && offset + header.frameLength <= data.length) {
  13698. var frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;
  13699. var stamp = pts + frameIndex * frameDuration;
  13700. var sample = {
  13701. unit: data.subarray(offset, offset + header.frameLength),
  13702. pts: stamp,
  13703. dts: stamp
  13704. };
  13705. track.config = [];
  13706. track.channelCount = header.channelCount;
  13707. track.samplerate = header.sampleRate;
  13708. track.samples.push(sample);
  13709. return {
  13710. sample: sample,
  13711. length: header.frameLength,
  13712. missing: 0
  13713. };
  13714. }
  13715. }
  13716. function parseHeader(data, offset) {
  13717. var mpegVersion = data[offset + 1] >> 3 & 3;
  13718. var mpegLayer = data[offset + 1] >> 1 & 3;
  13719. var bitRateIndex = data[offset + 2] >> 4 & 15;
  13720. var sampleRateIndex = data[offset + 2] >> 2 & 3;
  13721. if (mpegVersion !== 1 && bitRateIndex !== 0 && bitRateIndex !== 15 && sampleRateIndex !== 3) {
  13722. var paddingBit = data[offset + 2] >> 1 & 1;
  13723. var channelMode = data[offset + 3] >> 6;
  13724. var columnInBitrates = mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4;
  13725. var bitRate = BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1000;
  13726. var columnInSampleRates = mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2;
  13727. var sampleRate = SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex];
  13728. var channelCount = channelMode === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)
  13729. var sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer];
  13730. var bytesInSlot = BytesInSlot[mpegLayer];
  13731. var samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
  13732. var frameLength = Math.floor(sampleCoefficient * bitRate / sampleRate + paddingBit) * bytesInSlot;
  13733. if (chromeVersion$1 === null) {
  13734. var userAgent = navigator.userAgent || '';
  13735. var result = userAgent.match(/Chrome\/(\d+)/i);
  13736. chromeVersion$1 = result ? parseInt(result[1]) : 0;
  13737. }
  13738. var needChromeFix = !!chromeVersion$1 && chromeVersion$1 <= 87;
  13739. if (needChromeFix && mpegLayer === 2 && bitRate >= 224000 && channelMode === 0) {
  13740. // Work around bug in Chromium by setting channelMode to dual-channel (01) instead of stereo (00)
  13741. data[offset + 3] = data[offset + 3] | 0x80;
  13742. }
  13743. return {
  13744. sampleRate: sampleRate,
  13745. channelCount: channelCount,
  13746. frameLength: frameLength,
  13747. samplesPerFrame: samplesPerFrame
  13748. };
  13749. }
  13750. }
  13751. function isHeaderPattern(data, offset) {
  13752. return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;
  13753. }
  13754. function isHeader(data, offset) {
  13755. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  13756. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  13757. // More info http://www.mp3-tech.org/programmer/frame_header.html
  13758. return offset + 1 < data.length && isHeaderPattern(data, offset);
  13759. }
  13760. function canParse(data, offset) {
  13761. var headerSize = 4;
  13762. return isHeaderPattern(data, offset) && headerSize <= data.length - offset;
  13763. }
  13764. function probe(data, offset) {
  13765. // same as isHeader but we also check that MPEG frame follows last MPEG frame
  13766. // or end of data is reached
  13767. if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
  13768. // MPEG header Length
  13769. var headerLength = 4;
  13770. // MPEG frame Length
  13771. var header = parseHeader(data, offset);
  13772. var frameLength = headerLength;
  13773. if (header != null && header.frameLength) {
  13774. frameLength = header.frameLength;
  13775. }
  13776. var newOffset = offset + frameLength;
  13777. return newOffset === data.length || isHeader(data, newOffset);
  13778. }
  13779. return false;
  13780. }
  13781. var AACDemuxer = /*#__PURE__*/function (_BaseAudioDemuxer) {
  13782. _inheritsLoose(AACDemuxer, _BaseAudioDemuxer);
  13783. function AACDemuxer(observer, config) {
  13784. var _this;
  13785. _this = _BaseAudioDemuxer.call(this) || this;
  13786. _this.observer = void 0;
  13787. _this.config = void 0;
  13788. _this.observer = observer;
  13789. _this.config = config;
  13790. return _this;
  13791. }
  13792. var _proto = AACDemuxer.prototype;
  13793. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  13794. _BaseAudioDemuxer.prototype.resetInitSegment.call(this, initSegment, audioCodec, videoCodec, trackDuration);
  13795. this._audioTrack = {
  13796. container: 'audio/adts',
  13797. type: 'audio',
  13798. id: 2,
  13799. pid: -1,
  13800. sequenceNumber: 0,
  13801. segmentCodec: 'aac',
  13802. samples: [],
  13803. manifestCodec: audioCodec,
  13804. duration: trackDuration,
  13805. inputTimeScale: 90000,
  13806. dropped: 0
  13807. };
  13808. }
  13809. // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS
  13810. ;
  13811. AACDemuxer.probe = function probe$2(data) {
  13812. if (!data) {
  13813. return false;
  13814. }
  13815. // Check for the ADTS sync word
  13816. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  13817. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  13818. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  13819. var id3Data = getID3Data(data, 0);
  13820. var offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  13821. if (probe(data, offset)) {
  13822. return false;
  13823. }
  13824. for (var length = data.length; offset < length; offset++) {
  13825. if (probe$1(data, offset)) {
  13826. logger.log('ADTS sync word found !');
  13827. return true;
  13828. }
  13829. }
  13830. return false;
  13831. };
  13832. _proto.canParse = function canParse(data, offset) {
  13833. return canParse$1(data, offset);
  13834. };
  13835. _proto.appendFrame = function appendFrame(track, data, offset) {
  13836. initTrackConfig(track, this.observer, data, offset, track.manifestCodec);
  13837. var frame = appendFrame$1(track, data, offset, this.basePTS, this.frameIndex);
  13838. if (frame && frame.missing === 0) {
  13839. return frame;
  13840. }
  13841. };
  13842. return AACDemuxer;
  13843. }(BaseAudioDemuxer);
  13844. var emsgSchemePattern = /\/emsg[-/]ID3/i;
  13845. var MP4Demuxer = /*#__PURE__*/function () {
  13846. function MP4Demuxer(observer, config) {
  13847. this.remainderData = null;
  13848. this.timeOffset = 0;
  13849. this.config = void 0;
  13850. this.videoTrack = void 0;
  13851. this.audioTrack = void 0;
  13852. this.id3Track = void 0;
  13853. this.txtTrack = void 0;
  13854. this.config = config;
  13855. }
  13856. var _proto = MP4Demuxer.prototype;
  13857. _proto.resetTimeStamp = function resetTimeStamp() {};
  13858. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  13859. var videoTrack = this.videoTrack = dummyTrack('video', 1);
  13860. var audioTrack = this.audioTrack = dummyTrack('audio', 1);
  13861. var captionTrack = this.txtTrack = dummyTrack('text', 1);
  13862. this.id3Track = dummyTrack('id3', 1);
  13863. this.timeOffset = 0;
  13864. if (!(initSegment != null && initSegment.byteLength)) {
  13865. return;
  13866. }
  13867. var initData = parseInitSegment(initSegment);
  13868. if (initData.video) {
  13869. var _initData$video = initData.video,
  13870. id = _initData$video.id,
  13871. timescale = _initData$video.timescale,
  13872. codec = _initData$video.codec;
  13873. videoTrack.id = id;
  13874. videoTrack.timescale = captionTrack.timescale = timescale;
  13875. videoTrack.codec = codec;
  13876. }
  13877. if (initData.audio) {
  13878. var _initData$audio = initData.audio,
  13879. _id = _initData$audio.id,
  13880. _timescale = _initData$audio.timescale,
  13881. _codec = _initData$audio.codec;
  13882. audioTrack.id = _id;
  13883. audioTrack.timescale = _timescale;
  13884. audioTrack.codec = _codec;
  13885. }
  13886. captionTrack.id = RemuxerTrackIdConfig.text;
  13887. videoTrack.sampleDuration = 0;
  13888. videoTrack.duration = audioTrack.duration = trackDuration;
  13889. };
  13890. _proto.resetContiguity = function resetContiguity() {
  13891. this.remainderData = null;
  13892. };
  13893. MP4Demuxer.probe = function probe(data) {
  13894. return hasMoofData(data);
  13895. };
  13896. _proto.demux = function demux(data, timeOffset) {
  13897. this.timeOffset = timeOffset;
  13898. // 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
  13899. var videoSamples = data;
  13900. var videoTrack = this.videoTrack;
  13901. var textTrack = this.txtTrack;
  13902. if (this.config.progressive) {
  13903. // Split the bytestream into two ranges: one encompassing all data up until the start of the last moof, and everything else.
  13904. // This is done to guarantee that we're sending valid data to MSE - when demuxing progressively, we have no guarantee
  13905. // that the fetch loader gives us flush moof+mdat pairs. If we push jagged data to MSE, it will throw an exception.
  13906. if (this.remainderData) {
  13907. videoSamples = appendUint8Array(this.remainderData, data);
  13908. }
  13909. var segmentedData = segmentValidRange(videoSamples);
  13910. this.remainderData = segmentedData.remainder;
  13911. videoTrack.samples = segmentedData.valid || new Uint8Array();
  13912. } else {
  13913. videoTrack.samples = videoSamples;
  13914. }
  13915. var id3Track = this.extractID3Track(videoTrack, timeOffset);
  13916. textTrack.samples = parseSamples(timeOffset, videoTrack);
  13917. return {
  13918. videoTrack: videoTrack,
  13919. audioTrack: this.audioTrack,
  13920. id3Track: id3Track,
  13921. textTrack: this.txtTrack
  13922. };
  13923. };
  13924. _proto.flush = function flush() {
  13925. var timeOffset = this.timeOffset;
  13926. var videoTrack = this.videoTrack;
  13927. var textTrack = this.txtTrack;
  13928. videoTrack.samples = this.remainderData || new Uint8Array();
  13929. this.remainderData = null;
  13930. var id3Track = this.extractID3Track(videoTrack, this.timeOffset);
  13931. textTrack.samples = parseSamples(timeOffset, videoTrack);
  13932. return {
  13933. videoTrack: videoTrack,
  13934. audioTrack: dummyTrack(),
  13935. id3Track: id3Track,
  13936. textTrack: dummyTrack()
  13937. };
  13938. };
  13939. _proto.extractID3Track = function extractID3Track(videoTrack, timeOffset) {
  13940. var id3Track = this.id3Track;
  13941. if (videoTrack.samples.length) {
  13942. var emsgs = findBox(videoTrack.samples, ['emsg']);
  13943. if (emsgs) {
  13944. emsgs.forEach(function (data) {
  13945. var emsgInfo = parseEmsg(data);
  13946. if (emsgSchemePattern.test(emsgInfo.schemeIdUri)) {
  13947. var pts = isFiniteNumber(emsgInfo.presentationTime) ? emsgInfo.presentationTime / emsgInfo.timeScale : timeOffset + emsgInfo.presentationTimeDelta / emsgInfo.timeScale;
  13948. var duration = emsgInfo.eventDuration === 0xffffffff ? Number.POSITIVE_INFINITY : emsgInfo.eventDuration / emsgInfo.timeScale;
  13949. // Safari takes anything <= 0.001 seconds and maps it to Infinity
  13950. if (duration <= 0.001) {
  13951. duration = Number.POSITIVE_INFINITY;
  13952. }
  13953. var payload = emsgInfo.payload;
  13954. id3Track.samples.push({
  13955. data: payload,
  13956. len: payload.byteLength,
  13957. dts: pts,
  13958. pts: pts,
  13959. type: MetadataSchema.emsg,
  13960. duration: duration
  13961. });
  13962. }
  13963. });
  13964. }
  13965. }
  13966. return id3Track;
  13967. };
  13968. _proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
  13969. return Promise.reject(new Error('The MP4 demuxer does not support SAMPLE-AES decryption'));
  13970. };
  13971. _proto.destroy = function destroy() {};
  13972. return MP4Demuxer;
  13973. }();
  13974. var getAudioBSID = function getAudioBSID(data, offset) {
  13975. // check the bsid to confirm ac-3 | ec-3
  13976. var bsid = 0;
  13977. var numBits = 5;
  13978. offset += numBits;
  13979. var temp = new Uint32Array(1); // unsigned 32 bit for temporary storage
  13980. var mask = new Uint32Array(1); // unsigned 32 bit mask value
  13981. var _byte = new Uint8Array(1); // unsigned 8 bit for temporary storage
  13982. while (numBits > 0) {
  13983. _byte[0] = data[offset];
  13984. // read remaining bits, upto 8 bits at a time
  13985. var bits = Math.min(numBits, 8);
  13986. var shift = 8 - bits;
  13987. mask[0] = 0xff000000 >>> 24 + shift << shift;
  13988. temp[0] = (_byte[0] & mask[0]) >> shift;
  13989. bsid = !bsid ? temp[0] : bsid << bits | temp[0];
  13990. offset += 1;
  13991. numBits -= bits;
  13992. }
  13993. return bsid;
  13994. };
  13995. var BaseVideoParser = /*#__PURE__*/function () {
  13996. function BaseVideoParser() {
  13997. this.VideoSample = null;
  13998. }
  13999. var _proto = BaseVideoParser.prototype;
  14000. _proto.createVideoSample = function createVideoSample(key, pts, dts, debug) {
  14001. return {
  14002. key: key,
  14003. frame: false,
  14004. pts: pts,
  14005. dts: dts,
  14006. units: [],
  14007. debug: debug,
  14008. length: 0
  14009. };
  14010. };
  14011. _proto.getLastNalUnit = function getLastNalUnit(samples) {
  14012. var _VideoSample;
  14013. var VideoSample = this.VideoSample;
  14014. var lastUnit;
  14015. // try to fallback to previous sample if current one is empty
  14016. if (!VideoSample || VideoSample.units.length === 0) {
  14017. VideoSample = samples[samples.length - 1];
  14018. }
  14019. if ((_VideoSample = VideoSample) != null && _VideoSample.units) {
  14020. var units = VideoSample.units;
  14021. lastUnit = units[units.length - 1];
  14022. }
  14023. return lastUnit;
  14024. };
  14025. _proto.pushAccessUnit = function pushAccessUnit(VideoSample, videoTrack) {
  14026. if (VideoSample.units.length && VideoSample.frame) {
  14027. // if sample does not have PTS/DTS, patch with last sample PTS/DTS
  14028. if (VideoSample.pts === undefined) {
  14029. var samples = videoTrack.samples;
  14030. var nbSamples = samples.length;
  14031. if (nbSamples) {
  14032. var lastSample = samples[nbSamples - 1];
  14033. VideoSample.pts = lastSample.pts;
  14034. VideoSample.dts = lastSample.dts;
  14035. } else {
  14036. // dropping samples, no timestamp found
  14037. videoTrack.dropped++;
  14038. return;
  14039. }
  14040. }
  14041. videoTrack.samples.push(VideoSample);
  14042. }
  14043. if (VideoSample.debug.length) {
  14044. logger.log(VideoSample.pts + '/' + VideoSample.dts + ':' + VideoSample.debug);
  14045. }
  14046. };
  14047. return BaseVideoParser;
  14048. }();
  14049. /**
  14050. * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
  14051. */
  14052. var ExpGolomb = /*#__PURE__*/function () {
  14053. function ExpGolomb(data) {
  14054. this.data = void 0;
  14055. this.bytesAvailable = void 0;
  14056. this.word = void 0;
  14057. this.bitsAvailable = void 0;
  14058. this.data = data;
  14059. // the number of bytes left to examine in this.data
  14060. this.bytesAvailable = data.byteLength;
  14061. // the current word being examined
  14062. this.word = 0; // :uint
  14063. // the number of bits left to examine in the current word
  14064. this.bitsAvailable = 0; // :uint
  14065. }
  14066. // ():void
  14067. var _proto = ExpGolomb.prototype;
  14068. _proto.loadWord = function loadWord() {
  14069. var data = this.data;
  14070. var bytesAvailable = this.bytesAvailable;
  14071. var position = data.byteLength - bytesAvailable;
  14072. var workingBytes = new Uint8Array(4);
  14073. var availableBytes = Math.min(4, bytesAvailable);
  14074. if (availableBytes === 0) {
  14075. throw new Error('no bytes available');
  14076. }
  14077. workingBytes.set(data.subarray(position, position + availableBytes));
  14078. this.word = new DataView(workingBytes.buffer).getUint32(0);
  14079. // track the amount of this.data that has been processed
  14080. this.bitsAvailable = availableBytes * 8;
  14081. this.bytesAvailable -= availableBytes;
  14082. }
  14083. // (count:int):void
  14084. ;
  14085. _proto.skipBits = function skipBits(count) {
  14086. var skipBytes; // :int
  14087. count = Math.min(count, this.bytesAvailable * 8 + this.bitsAvailable);
  14088. if (this.bitsAvailable > count) {
  14089. this.word <<= count;
  14090. this.bitsAvailable -= count;
  14091. } else {
  14092. count -= this.bitsAvailable;
  14093. skipBytes = count >> 3;
  14094. count -= skipBytes << 3;
  14095. this.bytesAvailable -= skipBytes;
  14096. this.loadWord();
  14097. this.word <<= count;
  14098. this.bitsAvailable -= count;
  14099. }
  14100. }
  14101. // (size:int):uint
  14102. ;
  14103. _proto.readBits = function readBits(size) {
  14104. var bits = Math.min(this.bitsAvailable, size); // :uint
  14105. var valu = this.word >>> 32 - bits; // :uint
  14106. if (size > 32) {
  14107. logger.error('Cannot read more than 32 bits at a time');
  14108. }
  14109. this.bitsAvailable -= bits;
  14110. if (this.bitsAvailable > 0) {
  14111. this.word <<= bits;
  14112. } else if (this.bytesAvailable > 0) {
  14113. this.loadWord();
  14114. } else {
  14115. throw new Error('no bits available');
  14116. }
  14117. bits = size - bits;
  14118. if (bits > 0 && this.bitsAvailable) {
  14119. return valu << bits | this.readBits(bits);
  14120. } else {
  14121. return valu;
  14122. }
  14123. }
  14124. // ():uint
  14125. ;
  14126. _proto.skipLZ = function skipLZ() {
  14127. var leadingZeroCount; // :uint
  14128. for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
  14129. if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) {
  14130. // the first bit of working word is 1
  14131. this.word <<= leadingZeroCount;
  14132. this.bitsAvailable -= leadingZeroCount;
  14133. return leadingZeroCount;
  14134. }
  14135. }
  14136. // we exhausted word and still have not found a 1
  14137. this.loadWord();
  14138. return leadingZeroCount + this.skipLZ();
  14139. }
  14140. // ():void
  14141. ;
  14142. _proto.skipUEG = function skipUEG() {
  14143. this.skipBits(1 + this.skipLZ());
  14144. }
  14145. // ():void
  14146. ;
  14147. _proto.skipEG = function skipEG() {
  14148. this.skipBits(1 + this.skipLZ());
  14149. }
  14150. // ():uint
  14151. ;
  14152. _proto.readUEG = function readUEG() {
  14153. var clz = this.skipLZ(); // :uint
  14154. return this.readBits(clz + 1) - 1;
  14155. }
  14156. // ():int
  14157. ;
  14158. _proto.readEG = function readEG() {
  14159. var valu = this.readUEG(); // :int
  14160. if (0x01 & valu) {
  14161. // the number is odd if the low order bit is set
  14162. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  14163. } else {
  14164. return -1 * (valu >>> 1); // divide by two then make it negative
  14165. }
  14166. }
  14167. // Some convenience functions
  14168. // :Boolean
  14169. ;
  14170. _proto.readBoolean = function readBoolean() {
  14171. return this.readBits(1) === 1;
  14172. }
  14173. // ():int
  14174. ;
  14175. _proto.readUByte = function readUByte() {
  14176. return this.readBits(8);
  14177. }
  14178. // ():int
  14179. ;
  14180. _proto.readUShort = function readUShort() {
  14181. return this.readBits(16);
  14182. }
  14183. // ():int
  14184. ;
  14185. _proto.readUInt = function readUInt() {
  14186. return this.readBits(32);
  14187. }
  14188. /**
  14189. * Advance the ExpGolomb decoder past a scaling list. The scaling
  14190. * list is optionally transmitted as part of a sequence parameter
  14191. * set and is not relevant to transmuxing.
  14192. * @param count the number of entries in this scaling list
  14193. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  14194. */;
  14195. _proto.skipScalingList = function skipScalingList(count) {
  14196. var lastScale = 8;
  14197. var nextScale = 8;
  14198. var deltaScale;
  14199. for (var j = 0; j < count; j++) {
  14200. if (nextScale !== 0) {
  14201. deltaScale = this.readEG();
  14202. nextScale = (lastScale + deltaScale + 256) % 256;
  14203. }
  14204. lastScale = nextScale === 0 ? lastScale : nextScale;
  14205. }
  14206. }
  14207. /**
  14208. * Read a sequence parameter set and return some interesting video
  14209. * properties. A sequence parameter set is the H264 metadata that
  14210. * describes the properties of upcoming video frames.
  14211. * @returns an object with configuration parsed from the
  14212. * sequence parameter set, including the dimensions of the
  14213. * associated video frames.
  14214. */;
  14215. _proto.readSPS = function readSPS() {
  14216. var frameCropLeftOffset = 0;
  14217. var frameCropRightOffset = 0;
  14218. var frameCropTopOffset = 0;
  14219. var frameCropBottomOffset = 0;
  14220. var numRefFramesInPicOrderCntCycle;
  14221. var scalingListCount;
  14222. var i;
  14223. var readUByte = this.readUByte.bind(this);
  14224. var readBits = this.readBits.bind(this);
  14225. var readUEG = this.readUEG.bind(this);
  14226. var readBoolean = this.readBoolean.bind(this);
  14227. var skipBits = this.skipBits.bind(this);
  14228. var skipEG = this.skipEG.bind(this);
  14229. var skipUEG = this.skipUEG.bind(this);
  14230. var skipScalingList = this.skipScalingList.bind(this);
  14231. readUByte();
  14232. var profileIdc = readUByte(); // profile_idc
  14233. readBits(5); // profileCompat constraint_set[0-4]_flag, u(5)
  14234. skipBits(3); // reserved_zero_3bits u(3),
  14235. readUByte(); // level_idc u(8)
  14236. skipUEG(); // seq_parameter_set_id
  14237. // some profiles have more optional data we don't need
  14238. if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
  14239. var chromaFormatIdc = readUEG();
  14240. if (chromaFormatIdc === 3) {
  14241. skipBits(1);
  14242. } // separate_colour_plane_flag
  14243. skipUEG(); // bit_depth_luma_minus8
  14244. skipUEG(); // bit_depth_chroma_minus8
  14245. skipBits(1); // qpprime_y_zero_transform_bypass_flag
  14246. if (readBoolean()) {
  14247. // seq_scaling_matrix_present_flag
  14248. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  14249. for (i = 0; i < scalingListCount; i++) {
  14250. if (readBoolean()) {
  14251. // seq_scaling_list_present_flag[ i ]
  14252. if (i < 6) {
  14253. skipScalingList(16);
  14254. } else {
  14255. skipScalingList(64);
  14256. }
  14257. }
  14258. }
  14259. }
  14260. }
  14261. skipUEG(); // log2_max_frame_num_minus4
  14262. var picOrderCntType = readUEG();
  14263. if (picOrderCntType === 0) {
  14264. readUEG(); // log2_max_pic_order_cnt_lsb_minus4
  14265. } else if (picOrderCntType === 1) {
  14266. skipBits(1); // delta_pic_order_always_zero_flag
  14267. skipEG(); // offset_for_non_ref_pic
  14268. skipEG(); // offset_for_top_to_bottom_field
  14269. numRefFramesInPicOrderCntCycle = readUEG();
  14270. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  14271. skipEG();
  14272. } // offset_for_ref_frame[ i ]
  14273. }
  14274. skipUEG(); // max_num_ref_frames
  14275. skipBits(1); // gaps_in_frame_num_value_allowed_flag
  14276. var picWidthInMbsMinus1 = readUEG();
  14277. var picHeightInMapUnitsMinus1 = readUEG();
  14278. var frameMbsOnlyFlag = readBits(1);
  14279. if (frameMbsOnlyFlag === 0) {
  14280. skipBits(1);
  14281. } // mb_adaptive_frame_field_flag
  14282. skipBits(1); // direct_8x8_inference_flag
  14283. if (readBoolean()) {
  14284. // frame_cropping_flag
  14285. frameCropLeftOffset = readUEG();
  14286. frameCropRightOffset = readUEG();
  14287. frameCropTopOffset = readUEG();
  14288. frameCropBottomOffset = readUEG();
  14289. }
  14290. var pixelRatio = [1, 1];
  14291. if (readBoolean()) {
  14292. // vui_parameters_present_flag
  14293. if (readBoolean()) {
  14294. // aspect_ratio_info_present_flag
  14295. var aspectRatioIdc = readUByte();
  14296. switch (aspectRatioIdc) {
  14297. case 1:
  14298. pixelRatio = [1, 1];
  14299. break;
  14300. case 2:
  14301. pixelRatio = [12, 11];
  14302. break;
  14303. case 3:
  14304. pixelRatio = [10, 11];
  14305. break;
  14306. case 4:
  14307. pixelRatio = [16, 11];
  14308. break;
  14309. case 5:
  14310. pixelRatio = [40, 33];
  14311. break;
  14312. case 6:
  14313. pixelRatio = [24, 11];
  14314. break;
  14315. case 7:
  14316. pixelRatio = [20, 11];
  14317. break;
  14318. case 8:
  14319. pixelRatio = [32, 11];
  14320. break;
  14321. case 9:
  14322. pixelRatio = [80, 33];
  14323. break;
  14324. case 10:
  14325. pixelRatio = [18, 11];
  14326. break;
  14327. case 11:
  14328. pixelRatio = [15, 11];
  14329. break;
  14330. case 12:
  14331. pixelRatio = [64, 33];
  14332. break;
  14333. case 13:
  14334. pixelRatio = [160, 99];
  14335. break;
  14336. case 14:
  14337. pixelRatio = [4, 3];
  14338. break;
  14339. case 15:
  14340. pixelRatio = [3, 2];
  14341. break;
  14342. case 16:
  14343. pixelRatio = [2, 1];
  14344. break;
  14345. case 255:
  14346. {
  14347. pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
  14348. break;
  14349. }
  14350. }
  14351. }
  14352. }
  14353. return {
  14354. width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
  14355. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
  14356. pixelRatio: pixelRatio
  14357. };
  14358. };
  14359. _proto.readSliceType = function readSliceType() {
  14360. // skip NALu type
  14361. this.readUByte();
  14362. // discard first_mb_in_slice
  14363. this.readUEG();
  14364. // return slice_type
  14365. return this.readUEG();
  14366. };
  14367. return ExpGolomb;
  14368. }();
  14369. var AvcVideoParser = /*#__PURE__*/function (_BaseVideoParser) {
  14370. _inheritsLoose(AvcVideoParser, _BaseVideoParser);
  14371. function AvcVideoParser() {
  14372. return _BaseVideoParser.apply(this, arguments) || this;
  14373. }
  14374. var _proto = AvcVideoParser.prototype;
  14375. _proto.parseAVCPES = function parseAVCPES(track, textTrack, pes, last, duration) {
  14376. var _this = this;
  14377. var units = this.parseAVCNALu(track, pes.data);
  14378. var VideoSample = this.VideoSample;
  14379. var push;
  14380. var spsfound = false;
  14381. // free pes.data to save up some memory
  14382. pes.data = null;
  14383. // if new NAL units found and last sample still there, let's push ...
  14384. // this helps parsing streams with missing AUD (only do this if AUD never found)
  14385. if (VideoSample && units.length && !track.audFound) {
  14386. this.pushAccessUnit(VideoSample, track);
  14387. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts, '');
  14388. }
  14389. units.forEach(function (unit) {
  14390. var _VideoSample2;
  14391. switch (unit.type) {
  14392. // NDR
  14393. case 1:
  14394. {
  14395. var iskey = false;
  14396. push = true;
  14397. var data = unit.data;
  14398. // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)
  14399. if (spsfound && data.length > 4) {
  14400. // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR
  14401. var sliceType = new ExpGolomb(data).readSliceType();
  14402. // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice
  14403. // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.
  14404. // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.
  14405. // I slice: A slice that is not an SI slice that is decoded using intra prediction only.
  14406. // if (sliceType === 2 || sliceType === 7) {
  14407. if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
  14408. iskey = true;
  14409. }
  14410. }
  14411. if (iskey) {
  14412. var _VideoSample;
  14413. // if we have non-keyframe data already, that cannot belong to the same frame as a keyframe, so force a push
  14414. if ((_VideoSample = VideoSample) != null && _VideoSample.frame && !VideoSample.key) {
  14415. _this.pushAccessUnit(VideoSample, track);
  14416. VideoSample = _this.VideoSample = null;
  14417. }
  14418. }
  14419. if (!VideoSample) {
  14420. VideoSample = _this.VideoSample = _this.createVideoSample(true, pes.pts, pes.dts, '');
  14421. }
  14422. VideoSample.frame = true;
  14423. VideoSample.key = iskey;
  14424. break;
  14425. // IDR
  14426. }
  14427. case 5:
  14428. push = true;
  14429. // handle PES not starting with AUD
  14430. // if we have frame data already, that cannot belong to the same frame, so force a push
  14431. if ((_VideoSample2 = VideoSample) != null && _VideoSample2.frame && !VideoSample.key) {
  14432. _this.pushAccessUnit(VideoSample, track);
  14433. VideoSample = _this.VideoSample = null;
  14434. }
  14435. if (!VideoSample) {
  14436. VideoSample = _this.VideoSample = _this.createVideoSample(true, pes.pts, pes.dts, '');
  14437. }
  14438. VideoSample.key = true;
  14439. VideoSample.frame = true;
  14440. break;
  14441. // SEI
  14442. case 6:
  14443. {
  14444. push = true;
  14445. parseSEIMessageFromNALu(unit.data, 1, pes.pts, textTrack.samples);
  14446. break;
  14447. // SPS
  14448. }
  14449. case 7:
  14450. {
  14451. var _track$pixelRatio, _track$pixelRatio2;
  14452. push = true;
  14453. spsfound = true;
  14454. var sps = unit.data;
  14455. var expGolombDecoder = new ExpGolomb(sps);
  14456. var config = expGolombDecoder.readSPS();
  14457. 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]) {
  14458. track.width = config.width;
  14459. track.height = config.height;
  14460. track.pixelRatio = config.pixelRatio;
  14461. track.sps = [sps];
  14462. track.duration = duration;
  14463. var codecarray = sps.subarray(1, 4);
  14464. var codecstring = 'avc1.';
  14465. for (var i = 0; i < 3; i++) {
  14466. var h = codecarray[i].toString(16);
  14467. if (h.length < 2) {
  14468. h = '0' + h;
  14469. }
  14470. codecstring += h;
  14471. }
  14472. track.codec = codecstring;
  14473. }
  14474. break;
  14475. }
  14476. // PPS
  14477. case 8:
  14478. push = true;
  14479. track.pps = [unit.data];
  14480. break;
  14481. // AUD
  14482. case 9:
  14483. push = true;
  14484. track.audFound = true;
  14485. if (VideoSample) {
  14486. _this.pushAccessUnit(VideoSample, track);
  14487. }
  14488. VideoSample = _this.VideoSample = _this.createVideoSample(false, pes.pts, pes.dts, '');
  14489. break;
  14490. // Filler Data
  14491. case 12:
  14492. push = true;
  14493. break;
  14494. default:
  14495. push = false;
  14496. if (VideoSample) {
  14497. VideoSample.debug += 'unknown NAL ' + unit.type + ' ';
  14498. }
  14499. break;
  14500. }
  14501. if (VideoSample && push) {
  14502. var _units = VideoSample.units;
  14503. _units.push(unit);
  14504. }
  14505. });
  14506. // if last PES packet, push samples
  14507. if (last && VideoSample) {
  14508. this.pushAccessUnit(VideoSample, track);
  14509. this.VideoSample = null;
  14510. }
  14511. };
  14512. _proto.parseAVCNALu = function parseAVCNALu(track, array) {
  14513. var len = array.byteLength;
  14514. var state = track.naluState || 0;
  14515. var lastState = state;
  14516. var units = [];
  14517. var i = 0;
  14518. var value;
  14519. var overflow;
  14520. var unitType;
  14521. var lastUnitStart = -1;
  14522. var lastUnitType = 0;
  14523. // logger.log('PES:' + Hex.hexDump(array));
  14524. if (state === -1) {
  14525. // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet
  14526. lastUnitStart = 0;
  14527. // NALu type is value read from offset 0
  14528. lastUnitType = array[0] & 0x1f;
  14529. state = 0;
  14530. i = 1;
  14531. }
  14532. while (i < len) {
  14533. value = array[i++];
  14534. // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case
  14535. if (!state) {
  14536. state = value ? 0 : 1;
  14537. continue;
  14538. }
  14539. if (state === 1) {
  14540. state = value ? 0 : 2;
  14541. continue;
  14542. }
  14543. // here we have state either equal to 2 or 3
  14544. if (!value) {
  14545. state = 3;
  14546. } else if (value === 1) {
  14547. overflow = i - state - 1;
  14548. if (lastUnitStart >= 0) {
  14549. var unit = {
  14550. data: array.subarray(lastUnitStart, overflow),
  14551. type: lastUnitType
  14552. };
  14553. // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
  14554. units.push(unit);
  14555. } else {
  14556. // lastUnitStart is undefined => this is the first start code found in this PES packet
  14557. // first check if start code delimiter is overlapping between 2 PES packets,
  14558. // ie it started in last packet (lastState not zero)
  14559. // and ended at the beginning of this PES packet (i <= 4 - lastState)
  14560. var lastUnit = this.getLastNalUnit(track.samples);
  14561. if (lastUnit) {
  14562. if (lastState && i <= 4 - lastState) {
  14563. // start delimiter overlapping between PES packets
  14564. // strip start delimiter bytes from the end of last NAL unit
  14565. // check if lastUnit had a state different from zero
  14566. if (lastUnit.state) {
  14567. // strip last bytes
  14568. lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
  14569. }
  14570. }
  14571. // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.
  14572. if (overflow > 0) {
  14573. // logger.log('first NALU found with overflow:' + overflow);
  14574. lastUnit.data = appendUint8Array(lastUnit.data, array.subarray(0, overflow));
  14575. lastUnit.state = 0;
  14576. }
  14577. }
  14578. }
  14579. // check if we can read unit type
  14580. if (i < len) {
  14581. unitType = array[i] & 0x1f;
  14582. // logger.log('find NALU @ offset:' + i + ',type:' + unitType);
  14583. lastUnitStart = i;
  14584. lastUnitType = unitType;
  14585. state = 0;
  14586. } else {
  14587. // not enough byte to read unit type. let's read it on next PES parsing
  14588. state = -1;
  14589. }
  14590. } else {
  14591. state = 0;
  14592. }
  14593. }
  14594. if (lastUnitStart >= 0 && state >= 0) {
  14595. var _unit = {
  14596. data: array.subarray(lastUnitStart, len),
  14597. type: lastUnitType,
  14598. state: state
  14599. };
  14600. units.push(_unit);
  14601. // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);
  14602. }
  14603. // no NALu found
  14604. if (units.length === 0) {
  14605. // append pes.data to previous NAL unit
  14606. var _lastUnit = this.getLastNalUnit(track.samples);
  14607. if (_lastUnit) {
  14608. _lastUnit.data = appendUint8Array(_lastUnit.data, array);
  14609. }
  14610. }
  14611. track.naluState = state;
  14612. return units;
  14613. };
  14614. return AvcVideoParser;
  14615. }(BaseVideoParser);
  14616. /**
  14617. * SAMPLE-AES decrypter
  14618. */
  14619. var SampleAesDecrypter = /*#__PURE__*/function () {
  14620. function SampleAesDecrypter(observer, config, keyData) {
  14621. this.keyData = void 0;
  14622. this.decrypter = void 0;
  14623. this.keyData = keyData;
  14624. this.decrypter = new Decrypter(config, {
  14625. removePKCS7Padding: false
  14626. });
  14627. }
  14628. var _proto = SampleAesDecrypter.prototype;
  14629. _proto.decryptBuffer = function decryptBuffer(encryptedData) {
  14630. return this.decrypter.decrypt(encryptedData, this.keyData.key.buffer, this.keyData.iv.buffer);
  14631. }
  14632. // AAC - encrypt all full 16 bytes blocks starting from offset 16
  14633. ;
  14634. _proto.decryptAacSample = function decryptAacSample(samples, sampleIndex, callback) {
  14635. var _this = this;
  14636. var curUnit = samples[sampleIndex].unit;
  14637. if (curUnit.length <= 16) {
  14638. // No encrypted portion in this sample (first 16 bytes is not
  14639. // encrypted, see https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/HLS_Sample_Encryption/Encryption/Encryption.html),
  14640. return;
  14641. }
  14642. var encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
  14643. var encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
  14644. this.decryptBuffer(encryptedBuffer).then(function (decryptedBuffer) {
  14645. var decryptedData = new Uint8Array(decryptedBuffer);
  14646. curUnit.set(decryptedData, 16);
  14647. if (!_this.decrypter.isSync()) {
  14648. _this.decryptAacSamples(samples, sampleIndex + 1, callback);
  14649. }
  14650. });
  14651. };
  14652. _proto.decryptAacSamples = function decryptAacSamples(samples, sampleIndex, callback) {
  14653. for (;; sampleIndex++) {
  14654. if (sampleIndex >= samples.length) {
  14655. callback();
  14656. return;
  14657. }
  14658. if (samples[sampleIndex].unit.length < 32) {
  14659. continue;
  14660. }
  14661. this.decryptAacSample(samples, sampleIndex, callback);
  14662. if (!this.decrypter.isSync()) {
  14663. return;
  14664. }
  14665. }
  14666. }
  14667. // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
  14668. ;
  14669. _proto.getAvcEncryptedData = function getAvcEncryptedData(decodedData) {
  14670. var encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
  14671. var encryptedData = new Int8Array(encryptedDataLen);
  14672. var outputPos = 0;
  14673. for (var inputPos = 32; inputPos < decodedData.length - 16; inputPos += 160, outputPos += 16) {
  14674. encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
  14675. }
  14676. return encryptedData;
  14677. };
  14678. _proto.getAvcDecryptedUnit = function getAvcDecryptedUnit(decodedData, decryptedData) {
  14679. var uint8DecryptedData = new Uint8Array(decryptedData);
  14680. var inputPos = 0;
  14681. for (var outputPos = 32; outputPos < decodedData.length - 16; outputPos += 160, inputPos += 16) {
  14682. decodedData.set(uint8DecryptedData.subarray(inputPos, inputPos + 16), outputPos);
  14683. }
  14684. return decodedData;
  14685. };
  14686. _proto.decryptAvcSample = function decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit) {
  14687. var _this2 = this;
  14688. var decodedData = discardEPB(curUnit.data);
  14689. var encryptedData = this.getAvcEncryptedData(decodedData);
  14690. this.decryptBuffer(encryptedData.buffer).then(function (decryptedBuffer) {
  14691. curUnit.data = _this2.getAvcDecryptedUnit(decodedData, decryptedBuffer);
  14692. if (!_this2.decrypter.isSync()) {
  14693. _this2.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
  14694. }
  14695. });
  14696. };
  14697. _proto.decryptAvcSamples = function decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
  14698. if (samples instanceof Uint8Array) {
  14699. throw new Error('Cannot decrypt samples of type Uint8Array');
  14700. }
  14701. for (;; sampleIndex++, unitIndex = 0) {
  14702. if (sampleIndex >= samples.length) {
  14703. callback();
  14704. return;
  14705. }
  14706. var curUnits = samples[sampleIndex].units;
  14707. for (;; unitIndex++) {
  14708. if (unitIndex >= curUnits.length) {
  14709. break;
  14710. }
  14711. var curUnit = curUnits[unitIndex];
  14712. if (curUnit.data.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
  14713. continue;
  14714. }
  14715. this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit);
  14716. if (!this.decrypter.isSync()) {
  14717. return;
  14718. }
  14719. }
  14720. }
  14721. };
  14722. return SampleAesDecrypter;
  14723. }();
  14724. var PACKET_LENGTH = 188;
  14725. var TSDemuxer = /*#__PURE__*/function () {
  14726. function TSDemuxer(observer, config, typeSupported) {
  14727. this.observer = void 0;
  14728. this.config = void 0;
  14729. this.typeSupported = void 0;
  14730. this.sampleAes = null;
  14731. this.pmtParsed = false;
  14732. this.audioCodec = void 0;
  14733. this.videoCodec = void 0;
  14734. this._duration = 0;
  14735. this._pmtId = -1;
  14736. this._videoTrack = void 0;
  14737. this._audioTrack = void 0;
  14738. this._id3Track = void 0;
  14739. this._txtTrack = void 0;
  14740. this.aacOverFlow = null;
  14741. this.remainderData = null;
  14742. this.videoParser = void 0;
  14743. this.observer = observer;
  14744. this.config = config;
  14745. this.typeSupported = typeSupported;
  14746. this.videoParser = new AvcVideoParser();
  14747. }
  14748. TSDemuxer.probe = function probe(data) {
  14749. var syncOffset = TSDemuxer.syncOffset(data);
  14750. if (syncOffset > 0) {
  14751. logger.warn("MPEG2-TS detected but first sync word found @ offset " + syncOffset);
  14752. }
  14753. return syncOffset !== -1;
  14754. };
  14755. TSDemuxer.syncOffset = function syncOffset(data) {
  14756. var length = data.length;
  14757. var scanwindow = Math.min(PACKET_LENGTH * 5, length - PACKET_LENGTH) + 1;
  14758. var i = 0;
  14759. while (i < scanwindow) {
  14760. // a TS init segment should contain at least 2 TS packets: PAT and PMT, each starting with 0x47
  14761. var foundPat = false;
  14762. var packetStart = -1;
  14763. var tsPackets = 0;
  14764. for (var j = i; j < length; j += PACKET_LENGTH) {
  14765. if (data[j] === 0x47 && (length - j === PACKET_LENGTH || data[j + PACKET_LENGTH] === 0x47)) {
  14766. tsPackets++;
  14767. if (packetStart === -1) {
  14768. packetStart = j;
  14769. // First sync word found at offset, increase scan length (#5251)
  14770. if (packetStart !== 0) {
  14771. scanwindow = Math.min(packetStart + PACKET_LENGTH * 99, data.length - PACKET_LENGTH) + 1;
  14772. }
  14773. }
  14774. if (!foundPat) {
  14775. foundPat = parsePID(data, j) === 0;
  14776. }
  14777. // Sync word found at 0 with 3 packets, or found at offset least 2 packets up to scanwindow (#5501)
  14778. if (foundPat && tsPackets > 1 && (packetStart === 0 && tsPackets > 2 || j + PACKET_LENGTH > scanwindow)) {
  14779. return packetStart;
  14780. }
  14781. } else if (tsPackets) {
  14782. // Exit if sync word found, but does not contain contiguous packets
  14783. return -1;
  14784. } else {
  14785. break;
  14786. }
  14787. }
  14788. i++;
  14789. }
  14790. return -1;
  14791. }
  14792. /**
  14793. * Creates a track model internal to demuxer used to drive remuxing input
  14794. */;
  14795. TSDemuxer.createTrack = function createTrack(type, duration) {
  14796. return {
  14797. container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,
  14798. type: type,
  14799. id: RemuxerTrackIdConfig[type],
  14800. pid: -1,
  14801. inputTimeScale: 90000,
  14802. sequenceNumber: 0,
  14803. samples: [],
  14804. dropped: 0,
  14805. duration: type === 'audio' ? duration : undefined
  14806. };
  14807. }
  14808. /**
  14809. * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
  14810. * Resets all internal track instances of the demuxer.
  14811. */;
  14812. var _proto = TSDemuxer.prototype;
  14813. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  14814. this.pmtParsed = false;
  14815. this._pmtId = -1;
  14816. this._videoTrack = TSDemuxer.createTrack('video');
  14817. this._audioTrack = TSDemuxer.createTrack('audio', trackDuration);
  14818. this._id3Track = TSDemuxer.createTrack('id3');
  14819. this._txtTrack = TSDemuxer.createTrack('text');
  14820. this._audioTrack.segmentCodec = 'aac';
  14821. // flush any partial content
  14822. this.aacOverFlow = null;
  14823. this.remainderData = null;
  14824. this.audioCodec = audioCodec;
  14825. this.videoCodec = videoCodec;
  14826. this._duration = trackDuration;
  14827. };
  14828. _proto.resetTimeStamp = function resetTimeStamp() {};
  14829. _proto.resetContiguity = function resetContiguity() {
  14830. var _audioTrack = this._audioTrack,
  14831. _videoTrack = this._videoTrack,
  14832. _id3Track = this._id3Track;
  14833. if (_audioTrack) {
  14834. _audioTrack.pesData = null;
  14835. }
  14836. if (_videoTrack) {
  14837. _videoTrack.pesData = null;
  14838. }
  14839. if (_id3Track) {
  14840. _id3Track.pesData = null;
  14841. }
  14842. this.aacOverFlow = null;
  14843. this.remainderData = null;
  14844. };
  14845. _proto.demux = function demux(data, timeOffset, isSampleAes, flush) {
  14846. if (isSampleAes === void 0) {
  14847. isSampleAes = false;
  14848. }
  14849. if (flush === void 0) {
  14850. flush = false;
  14851. }
  14852. if (!isSampleAes) {
  14853. this.sampleAes = null;
  14854. }
  14855. var pes;
  14856. var videoTrack = this._videoTrack;
  14857. var audioTrack = this._audioTrack;
  14858. var id3Track = this._id3Track;
  14859. var textTrack = this._txtTrack;
  14860. var videoPid = videoTrack.pid;
  14861. var videoData = videoTrack.pesData;
  14862. var audioPid = audioTrack.pid;
  14863. var id3Pid = id3Track.pid;
  14864. var audioData = audioTrack.pesData;
  14865. var id3Data = id3Track.pesData;
  14866. var unknownPID = null;
  14867. var pmtParsed = this.pmtParsed;
  14868. var pmtId = this._pmtId;
  14869. var len = data.length;
  14870. if (this.remainderData) {
  14871. data = appendUint8Array(this.remainderData, data);
  14872. len = data.length;
  14873. this.remainderData = null;
  14874. }
  14875. if (len < PACKET_LENGTH && !flush) {
  14876. this.remainderData = data;
  14877. return {
  14878. audioTrack: audioTrack,
  14879. videoTrack: videoTrack,
  14880. id3Track: id3Track,
  14881. textTrack: textTrack
  14882. };
  14883. }
  14884. var syncOffset = Math.max(0, TSDemuxer.syncOffset(data));
  14885. len -= (len - syncOffset) % PACKET_LENGTH;
  14886. if (len < data.byteLength && !flush) {
  14887. this.remainderData = new Uint8Array(data.buffer, len, data.buffer.byteLength - len);
  14888. }
  14889. // loop through TS packets
  14890. var tsPacketErrors = 0;
  14891. for (var start = syncOffset; start < len; start += PACKET_LENGTH) {
  14892. if (data[start] === 0x47) {
  14893. var stt = !!(data[start + 1] & 0x40);
  14894. var pid = parsePID(data, start);
  14895. var atf = (data[start + 3] & 0x30) >> 4;
  14896. // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.
  14897. var offset = void 0;
  14898. if (atf > 1) {
  14899. offset = start + 5 + data[start + 4];
  14900. // continue if there is only adaptation field
  14901. if (offset === start + PACKET_LENGTH) {
  14902. continue;
  14903. }
  14904. } else {
  14905. offset = start + 4;
  14906. }
  14907. switch (pid) {
  14908. case videoPid:
  14909. if (stt) {
  14910. if (videoData && (pes = parsePES(videoData))) {
  14911. this.videoParser.parseAVCPES(videoTrack, textTrack, pes, false, this._duration);
  14912. }
  14913. videoData = {
  14914. data: [],
  14915. size: 0
  14916. };
  14917. }
  14918. if (videoData) {
  14919. videoData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  14920. videoData.size += start + PACKET_LENGTH - offset;
  14921. }
  14922. break;
  14923. case audioPid:
  14924. if (stt) {
  14925. if (audioData && (pes = parsePES(audioData))) {
  14926. switch (audioTrack.segmentCodec) {
  14927. case 'aac':
  14928. this.parseAACPES(audioTrack, pes);
  14929. break;
  14930. case 'mp3':
  14931. this.parseMPEGPES(audioTrack, pes);
  14932. break;
  14933. }
  14934. }
  14935. audioData = {
  14936. data: [],
  14937. size: 0
  14938. };
  14939. }
  14940. if (audioData) {
  14941. audioData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  14942. audioData.size += start + PACKET_LENGTH - offset;
  14943. }
  14944. break;
  14945. case id3Pid:
  14946. if (stt) {
  14947. if (id3Data && (pes = parsePES(id3Data))) {
  14948. this.parseID3PES(id3Track, pes);
  14949. }
  14950. id3Data = {
  14951. data: [],
  14952. size: 0
  14953. };
  14954. }
  14955. if (id3Data) {
  14956. id3Data.data.push(data.subarray(offset, start + PACKET_LENGTH));
  14957. id3Data.size += start + PACKET_LENGTH - offset;
  14958. }
  14959. break;
  14960. case 0:
  14961. if (stt) {
  14962. offset += data[offset] + 1;
  14963. }
  14964. pmtId = this._pmtId = parsePAT(data, offset);
  14965. // logger.log('PMT PID:' + this._pmtId);
  14966. break;
  14967. case pmtId:
  14968. {
  14969. if (stt) {
  14970. offset += data[offset] + 1;
  14971. }
  14972. var parsedPIDs = parsePMT(data, offset, this.typeSupported, isSampleAes, this.observer);
  14973. // only update track id if track PID found while parsing PMT
  14974. // this is to avoid resetting the PID to -1 in case
  14975. // track PID transiently disappears from the stream
  14976. // this could happen in case of transient missing audio samples for example
  14977. // NOTE this is only the PID of the track as found in TS,
  14978. // but we are not using this for MP4 track IDs.
  14979. videoPid = parsedPIDs.videoPid;
  14980. if (videoPid > 0) {
  14981. videoTrack.pid = videoPid;
  14982. videoTrack.segmentCodec = parsedPIDs.segmentVideoCodec;
  14983. }
  14984. audioPid = parsedPIDs.audioPid;
  14985. if (audioPid > 0) {
  14986. audioTrack.pid = audioPid;
  14987. audioTrack.segmentCodec = parsedPIDs.segmentAudioCodec;
  14988. }
  14989. id3Pid = parsedPIDs.id3Pid;
  14990. if (id3Pid > 0) {
  14991. id3Track.pid = id3Pid;
  14992. }
  14993. if (unknownPID !== null && !pmtParsed) {
  14994. logger.warn("MPEG-TS PMT found at " + start + " after unknown PID '" + unknownPID + "'. Backtracking to sync byte @" + syncOffset + " to parse all TS packets.");
  14995. unknownPID = null;
  14996. // we set it to -188, the += 188 in the for loop will reset start to 0
  14997. start = syncOffset - 188;
  14998. }
  14999. pmtParsed = this.pmtParsed = true;
  15000. break;
  15001. }
  15002. case 0x11:
  15003. case 0x1fff:
  15004. break;
  15005. default:
  15006. unknownPID = pid;
  15007. break;
  15008. }
  15009. } else {
  15010. tsPacketErrors++;
  15011. }
  15012. }
  15013. if (tsPacketErrors > 0) {
  15014. emitParsingError(this.observer, new Error("Found " + tsPacketErrors + " TS packet/s that do not start with 0x47"));
  15015. }
  15016. videoTrack.pesData = videoData;
  15017. audioTrack.pesData = audioData;
  15018. id3Track.pesData = id3Data;
  15019. var demuxResult = {
  15020. audioTrack: audioTrack,
  15021. videoTrack: videoTrack,
  15022. id3Track: id3Track,
  15023. textTrack: textTrack
  15024. };
  15025. if (flush) {
  15026. this.extractRemainingSamples(demuxResult);
  15027. }
  15028. return demuxResult;
  15029. };
  15030. _proto.flush = function flush() {
  15031. var remainderData = this.remainderData;
  15032. this.remainderData = null;
  15033. var result;
  15034. if (remainderData) {
  15035. result = this.demux(remainderData, -1, false, true);
  15036. } else {
  15037. result = {
  15038. videoTrack: this._videoTrack,
  15039. audioTrack: this._audioTrack,
  15040. id3Track: this._id3Track,
  15041. textTrack: this._txtTrack
  15042. };
  15043. }
  15044. this.extractRemainingSamples(result);
  15045. if (this.sampleAes) {
  15046. return this.decrypt(result, this.sampleAes);
  15047. }
  15048. return result;
  15049. };
  15050. _proto.extractRemainingSamples = function extractRemainingSamples(demuxResult) {
  15051. var audioTrack = demuxResult.audioTrack,
  15052. videoTrack = demuxResult.videoTrack,
  15053. id3Track = demuxResult.id3Track,
  15054. textTrack = demuxResult.textTrack;
  15055. var videoData = videoTrack.pesData;
  15056. var audioData = audioTrack.pesData;
  15057. var id3Data = id3Track.pesData;
  15058. // try to parse last PES packets
  15059. var pes;
  15060. if (videoData && (pes = parsePES(videoData))) {
  15061. this.videoParser.parseAVCPES(videoTrack, textTrack, pes, true, this._duration);
  15062. videoTrack.pesData = null;
  15063. } else {
  15064. // either avcData null or PES truncated, keep it for next frag parsing
  15065. videoTrack.pesData = videoData;
  15066. }
  15067. if (audioData && (pes = parsePES(audioData))) {
  15068. switch (audioTrack.segmentCodec) {
  15069. case 'aac':
  15070. this.parseAACPES(audioTrack, pes);
  15071. break;
  15072. case 'mp3':
  15073. this.parseMPEGPES(audioTrack, pes);
  15074. break;
  15075. }
  15076. audioTrack.pesData = null;
  15077. } else {
  15078. if (audioData != null && audioData.size) {
  15079. logger.log('last AAC PES packet truncated,might overlap between fragments');
  15080. }
  15081. // either audioData null or PES truncated, keep it for next frag parsing
  15082. audioTrack.pesData = audioData;
  15083. }
  15084. if (id3Data && (pes = parsePES(id3Data))) {
  15085. this.parseID3PES(id3Track, pes);
  15086. id3Track.pesData = null;
  15087. } else {
  15088. // either id3Data null or PES truncated, keep it for next frag parsing
  15089. id3Track.pesData = id3Data;
  15090. }
  15091. };
  15092. _proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
  15093. var demuxResult = this.demux(data, timeOffset, true, !this.config.progressive);
  15094. var sampleAes = this.sampleAes = new SampleAesDecrypter(this.observer, this.config, keyData);
  15095. return this.decrypt(demuxResult, sampleAes);
  15096. };
  15097. _proto.decrypt = function decrypt(demuxResult, sampleAes) {
  15098. return new Promise(function (resolve) {
  15099. var audioTrack = demuxResult.audioTrack,
  15100. videoTrack = demuxResult.videoTrack;
  15101. if (audioTrack.samples && audioTrack.segmentCodec === 'aac') {
  15102. sampleAes.decryptAacSamples(audioTrack.samples, 0, function () {
  15103. if (videoTrack.samples) {
  15104. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, function () {
  15105. resolve(demuxResult);
  15106. });
  15107. } else {
  15108. resolve(demuxResult);
  15109. }
  15110. });
  15111. } else if (videoTrack.samples) {
  15112. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, function () {
  15113. resolve(demuxResult);
  15114. });
  15115. }
  15116. });
  15117. };
  15118. _proto.destroy = function destroy() {
  15119. this._duration = 0;
  15120. };
  15121. _proto.parseAACPES = function parseAACPES(track, pes) {
  15122. var startOffset = 0;
  15123. var aacOverFlow = this.aacOverFlow;
  15124. var data = pes.data;
  15125. if (aacOverFlow) {
  15126. this.aacOverFlow = null;
  15127. var frameMissingBytes = aacOverFlow.missing;
  15128. var sampleLength = aacOverFlow.sample.unit.byteLength;
  15129. // logger.log(`AAC: append overflowing ${sampleLength} bytes to beginning of new PES`);
  15130. if (frameMissingBytes === -1) {
  15131. data = appendUint8Array(aacOverFlow.sample.unit, data);
  15132. } else {
  15133. var frameOverflowBytes = sampleLength - frameMissingBytes;
  15134. aacOverFlow.sample.unit.set(data.subarray(0, frameMissingBytes), frameOverflowBytes);
  15135. track.samples.push(aacOverFlow.sample);
  15136. startOffset = aacOverFlow.missing;
  15137. }
  15138. }
  15139. // look for ADTS header (0xFFFx)
  15140. var offset;
  15141. var len;
  15142. for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
  15143. if (isHeader$1(data, offset)) {
  15144. break;
  15145. }
  15146. }
  15147. // if ADTS header does not start straight from the beginning of the PES payload, raise an error
  15148. if (offset !== startOffset) {
  15149. var reason;
  15150. var recoverable = offset < len - 1;
  15151. if (recoverable) {
  15152. reason = "AAC PES did not start with ADTS header,offset:" + offset;
  15153. } else {
  15154. reason = 'No ADTS header found in AAC PES';
  15155. }
  15156. emitParsingError(this.observer, new Error(reason), recoverable);
  15157. if (!recoverable) {
  15158. return;
  15159. }
  15160. }
  15161. initTrackConfig(track, this.observer, data, offset, this.audioCodec);
  15162. var pts;
  15163. if (pes.pts !== undefined) {
  15164. pts = pes.pts;
  15165. } else if (aacOverFlow) {
  15166. // if last AAC frame is overflowing, we should ensure timestamps are contiguous:
  15167. // first sample PTS should be equal to last sample PTS + frameDuration
  15168. var frameDuration = getFrameDuration(track.samplerate);
  15169. pts = aacOverFlow.sample.pts + frameDuration;
  15170. } else {
  15171. logger.warn('[tsdemuxer]: AAC PES unknown PTS');
  15172. return;
  15173. }
  15174. // scan for aac samples
  15175. var frameIndex = 0;
  15176. var frame;
  15177. while (offset < len) {
  15178. frame = appendFrame$1(track, data, offset, pts, frameIndex);
  15179. offset += frame.length;
  15180. if (!frame.missing) {
  15181. frameIndex++;
  15182. for (; offset < len - 1; offset++) {
  15183. if (isHeader$1(data, offset)) {
  15184. break;
  15185. }
  15186. }
  15187. } else {
  15188. this.aacOverFlow = frame;
  15189. break;
  15190. }
  15191. }
  15192. };
  15193. _proto.parseMPEGPES = function parseMPEGPES(track, pes) {
  15194. var data = pes.data;
  15195. var length = data.length;
  15196. var frameIndex = 0;
  15197. var offset = 0;
  15198. var pts = pes.pts;
  15199. if (pts === undefined) {
  15200. logger.warn('[tsdemuxer]: MPEG PES unknown PTS');
  15201. return;
  15202. }
  15203. while (offset < length) {
  15204. if (isHeader(data, offset)) {
  15205. var frame = appendFrame(track, data, offset, pts, frameIndex);
  15206. if (frame) {
  15207. offset += frame.length;
  15208. frameIndex++;
  15209. } else {
  15210. // logger.log('Unable to parse Mpeg audio frame');
  15211. break;
  15212. }
  15213. } else {
  15214. // nothing found, keep looking
  15215. offset++;
  15216. }
  15217. }
  15218. };
  15219. _proto.parseAC3PES = function parseAC3PES(track, pes) {
  15220. };
  15221. _proto.parseID3PES = function parseID3PES(id3Track, pes) {
  15222. if (pes.pts === undefined) {
  15223. logger.warn('[tsdemuxer]: ID3 PES unknown PTS');
  15224. return;
  15225. }
  15226. var id3Sample = _extends({}, pes, {
  15227. type: this._videoTrack ? MetadataSchema.emsg : MetadataSchema.audioId3,
  15228. duration: Number.POSITIVE_INFINITY
  15229. });
  15230. id3Track.samples.push(id3Sample);
  15231. };
  15232. return TSDemuxer;
  15233. }();
  15234. function parsePID(data, offset) {
  15235. // pid is a 13-bit field starting at the last bit of TS[1]
  15236. return ((data[offset + 1] & 0x1f) << 8) + data[offset + 2];
  15237. }
  15238. function parsePAT(data, offset) {
  15239. // skip the PSI header and parse the first PMT entry
  15240. return (data[offset + 10] & 0x1f) << 8 | data[offset + 11];
  15241. }
  15242. function parsePMT(data, offset, typeSupported, isSampleAes, observer) {
  15243. var result = {
  15244. audioPid: -1,
  15245. videoPid: -1,
  15246. id3Pid: -1,
  15247. segmentVideoCodec: 'avc',
  15248. segmentAudioCodec: 'aac'
  15249. };
  15250. var sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
  15251. var tableEnd = offset + 3 + sectionLength - 4;
  15252. // to determine where the table is, we have to figure out how
  15253. // long the program info descriptors are
  15254. var programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11];
  15255. // advance the offset to the first entry in the mapping table
  15256. offset += 12 + programInfoLength;
  15257. while (offset < tableEnd) {
  15258. var pid = parsePID(data, offset);
  15259. var esInfoLength = (data[offset + 3] & 0x0f) << 8 | data[offset + 4];
  15260. switch (data[offset]) {
  15261. case 0xcf:
  15262. // SAMPLE-AES AAC
  15263. if (!isSampleAes) {
  15264. logEncryptedSamplesFoundInUnencryptedStream('ADTS AAC');
  15265. break;
  15266. }
  15267. /* falls through */
  15268. case 0x0f:
  15269. // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
  15270. // logger.log('AAC PID:' + pid);
  15271. if (result.audioPid === -1) {
  15272. result.audioPid = pid;
  15273. }
  15274. break;
  15275. // Packetized metadata (ID3)
  15276. case 0x15:
  15277. // logger.log('ID3 PID:' + pid);
  15278. if (result.id3Pid === -1) {
  15279. result.id3Pid = pid;
  15280. }
  15281. break;
  15282. case 0xdb:
  15283. // SAMPLE-AES AVC
  15284. if (!isSampleAes) {
  15285. logEncryptedSamplesFoundInUnencryptedStream('H.264');
  15286. break;
  15287. }
  15288. /* falls through */
  15289. case 0x1b:
  15290. // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
  15291. // logger.log('AVC PID:' + pid);
  15292. if (result.videoPid === -1) {
  15293. result.videoPid = pid;
  15294. result.segmentVideoCodec = 'avc';
  15295. }
  15296. break;
  15297. // ISO/IEC 11172-3 (MPEG-1 audio)
  15298. // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)
  15299. case 0x03:
  15300. case 0x04:
  15301. // logger.log('MPEG PID:' + pid);
  15302. if (!typeSupported.mpeg && !typeSupported.mp3) {
  15303. logger.log('MPEG audio found, not supported in this browser');
  15304. } else if (result.audioPid === -1) {
  15305. result.audioPid = pid;
  15306. result.segmentAudioCodec = 'mp3';
  15307. }
  15308. break;
  15309. case 0xc1:
  15310. // SAMPLE-AES AC3
  15311. if (!isSampleAes) {
  15312. logEncryptedSamplesFoundInUnencryptedStream('AC-3');
  15313. break;
  15314. }
  15315. /* falls through */
  15316. case 0x81:
  15317. {
  15318. logger.warn('AC-3 in M2TS support not included in build');
  15319. }
  15320. break;
  15321. case 0x06:
  15322. // stream_type 6 can mean a lot of different things in case of DVB.
  15323. // We need to look at the descriptors. Right now, we're only interested
  15324. // in AC-3 audio, so we do the descriptor parsing only when we don't have
  15325. // an audio PID yet.
  15326. if (result.audioPid === -1 && esInfoLength > 0) {
  15327. var parsePos = offset + 5;
  15328. var remaining = esInfoLength;
  15329. while (remaining > 2) {
  15330. var descriptorId = data[parsePos];
  15331. switch (descriptorId) {
  15332. case 0x6a:
  15333. // DVB Descriptor for AC-3
  15334. {
  15335. logger.warn('AC-3 in M2TS support not included in build');
  15336. }
  15337. break;
  15338. }
  15339. var descriptorLen = data[parsePos + 1] + 2;
  15340. parsePos += descriptorLen;
  15341. remaining -= descriptorLen;
  15342. }
  15343. }
  15344. break;
  15345. case 0xc2: // SAMPLE-AES EC3
  15346. /* falls through */
  15347. case 0x87:
  15348. emitParsingError(observer, new Error('Unsupported EC-3 in M2TS found'));
  15349. return result;
  15350. case 0x24:
  15351. emitParsingError(observer, new Error('Unsupported HEVC in M2TS found'));
  15352. return result;
  15353. }
  15354. // move to the next table entry
  15355. // skip past the elementary stream descriptors, if present
  15356. offset += esInfoLength + 5;
  15357. }
  15358. return result;
  15359. }
  15360. function emitParsingError(observer, error, levelRetry) {
  15361. logger.warn("parsing error: " + error.message);
  15362. observer.emit(Events.ERROR, Events.ERROR, {
  15363. type: ErrorTypes.MEDIA_ERROR,
  15364. details: ErrorDetails.FRAG_PARSING_ERROR,
  15365. fatal: false,
  15366. levelRetry: levelRetry,
  15367. error: error,
  15368. reason: error.message
  15369. });
  15370. }
  15371. function logEncryptedSamplesFoundInUnencryptedStream(type) {
  15372. logger.log(type + " with AES-128-CBC encryption found in unencrypted stream");
  15373. }
  15374. function parsePES(stream) {
  15375. var i = 0;
  15376. var frag;
  15377. var pesLen;
  15378. var pesHdrLen;
  15379. var pesPts;
  15380. var pesDts;
  15381. var data = stream.data;
  15382. // safety check
  15383. if (!stream || stream.size === 0) {
  15384. return null;
  15385. }
  15386. // we might need up to 19 bytes to read PES header
  15387. // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes
  15388. // usually only one merge is needed (and this is rare ...)
  15389. while (data[0].length < 19 && data.length > 1) {
  15390. data[0] = appendUint8Array(data[0], data[1]);
  15391. data.splice(1, 1);
  15392. }
  15393. // retrieve PTS/DTS from first fragment
  15394. frag = data[0];
  15395. var pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
  15396. if (pesPrefix === 1) {
  15397. pesLen = (frag[4] << 8) + frag[5];
  15398. // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated
  15399. // minus 6 : PES header size
  15400. if (pesLen && pesLen > stream.size - 6) {
  15401. return null;
  15402. }
  15403. var pesFlags = frag[7];
  15404. if (pesFlags & 0xc0) {
  15405. /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  15406. as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
  15407. as Bitwise operators treat their operands as a sequence of 32 bits */
  15408. pesPts = (frag[9] & 0x0e) * 536870912 +
  15409. // 1 << 29
  15410. (frag[10] & 0xff) * 4194304 +
  15411. // 1 << 22
  15412. (frag[11] & 0xfe) * 16384 +
  15413. // 1 << 14
  15414. (frag[12] & 0xff) * 128 +
  15415. // 1 << 7
  15416. (frag[13] & 0xfe) / 2;
  15417. if (pesFlags & 0x40) {
  15418. pesDts = (frag[14] & 0x0e) * 536870912 +
  15419. // 1 << 29
  15420. (frag[15] & 0xff) * 4194304 +
  15421. // 1 << 22
  15422. (frag[16] & 0xfe) * 16384 +
  15423. // 1 << 14
  15424. (frag[17] & 0xff) * 128 +
  15425. // 1 << 7
  15426. (frag[18] & 0xfe) / 2;
  15427. if (pesPts - pesDts > 60 * 90000) {
  15428. logger.warn(Math.round((pesPts - pesDts) / 90000) + "s delta between PTS and DTS, align them");
  15429. pesPts = pesDts;
  15430. }
  15431. } else {
  15432. pesDts = pesPts;
  15433. }
  15434. }
  15435. pesHdrLen = frag[8];
  15436. // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension
  15437. var payloadStartOffset = pesHdrLen + 9;
  15438. if (stream.size <= payloadStartOffset) {
  15439. return null;
  15440. }
  15441. stream.size -= payloadStartOffset;
  15442. // reassemble PES packet
  15443. var pesData = new Uint8Array(stream.size);
  15444. for (var j = 0, dataLen = data.length; j < dataLen; j++) {
  15445. frag = data[j];
  15446. var len = frag.byteLength;
  15447. if (payloadStartOffset) {
  15448. if (payloadStartOffset > len) {
  15449. // trim full frag if PES header bigger than frag
  15450. payloadStartOffset -= len;
  15451. continue;
  15452. } else {
  15453. // trim partial frag if PES header smaller than frag
  15454. frag = frag.subarray(payloadStartOffset);
  15455. len -= payloadStartOffset;
  15456. payloadStartOffset = 0;
  15457. }
  15458. }
  15459. pesData.set(frag, i);
  15460. i += len;
  15461. }
  15462. if (pesLen) {
  15463. // payload size : remove PES header + PES extension
  15464. pesLen -= pesHdrLen + 3;
  15465. }
  15466. return {
  15467. data: pesData,
  15468. pts: pesPts,
  15469. dts: pesDts,
  15470. len: pesLen
  15471. };
  15472. }
  15473. return null;
  15474. }
  15475. var MP3Demuxer = /*#__PURE__*/function (_BaseAudioDemuxer) {
  15476. _inheritsLoose(MP3Demuxer, _BaseAudioDemuxer);
  15477. function MP3Demuxer() {
  15478. return _BaseAudioDemuxer.apply(this, arguments) || this;
  15479. }
  15480. var _proto = MP3Demuxer.prototype;
  15481. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  15482. _BaseAudioDemuxer.prototype.resetInitSegment.call(this, initSegment, audioCodec, videoCodec, trackDuration);
  15483. this._audioTrack = {
  15484. container: 'audio/mpeg',
  15485. type: 'audio',
  15486. id: 2,
  15487. pid: -1,
  15488. sequenceNumber: 0,
  15489. segmentCodec: 'mp3',
  15490. samples: [],
  15491. manifestCodec: audioCodec,
  15492. duration: trackDuration,
  15493. inputTimeScale: 90000,
  15494. dropped: 0
  15495. };
  15496. };
  15497. MP3Demuxer.probe = function probe$1(data) {
  15498. if (!data) {
  15499. return false;
  15500. }
  15501. // check if data contains ID3 timestamp and MPEG sync word
  15502. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  15503. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  15504. // More info http://www.mp3-tech.org/programmer/frame_header.html
  15505. var id3Data = getID3Data(data, 0);
  15506. var offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  15507. // Check for ac-3|ec-3 sync bytes and return false if present
  15508. if (id3Data && data[offset] === 0x0b && data[offset + 1] === 0x77 && getTimeStamp(id3Data) !== undefined &&
  15509. // check the bsid to confirm ac-3 or ec-3 (not mp3)
  15510. getAudioBSID(data, offset) <= 16) {
  15511. return false;
  15512. }
  15513. for (var length = data.length; offset < length; offset++) {
  15514. if (probe(data, offset)) {
  15515. logger.log('MPEG Audio sync word found !');
  15516. return true;
  15517. }
  15518. }
  15519. return false;
  15520. };
  15521. _proto.canParse = function canParse$1(data, offset) {
  15522. return canParse(data, offset);
  15523. };
  15524. _proto.appendFrame = function appendFrame$1(track, data, offset) {
  15525. if (this.basePTS === null) {
  15526. return;
  15527. }
  15528. return appendFrame(track, data, offset, this.basePTS, this.frameIndex);
  15529. };
  15530. return MP3Demuxer;
  15531. }(BaseAudioDemuxer);
  15532. /**
  15533. * AAC helper
  15534. */
  15535. var AAC = /*#__PURE__*/function () {
  15536. function AAC() {}
  15537. AAC.getSilentFrame = function getSilentFrame(codec, channelCount) {
  15538. switch (codec) {
  15539. case 'mp4a.40.2':
  15540. if (channelCount === 1) {
  15541. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
  15542. } else if (channelCount === 2) {
  15543. return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
  15544. } else if (channelCount === 3) {
  15545. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
  15546. } else if (channelCount === 4) {
  15547. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
  15548. } else if (channelCount === 5) {
  15549. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
  15550. } else if (channelCount === 6) {
  15551. 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]);
  15552. }
  15553. break;
  15554. // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)
  15555. default:
  15556. if (channelCount === 1) {
  15557. // 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
  15558. 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]);
  15559. } else if (channelCount === 2) {
  15560. // 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
  15561. 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]);
  15562. } else if (channelCount === 3) {
  15563. // 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
  15564. 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]);
  15565. }
  15566. break;
  15567. }
  15568. return undefined;
  15569. };
  15570. return AAC;
  15571. }();
  15572. /**
  15573. * Generate MP4 Box
  15574. */
  15575. var UINT32_MAX = Math.pow(2, 32) - 1;
  15576. var MP4 = /*#__PURE__*/function () {
  15577. function MP4() {}
  15578. MP4.init = function init() {
  15579. MP4.types = {
  15580. avc1: [],
  15581. // codingname
  15582. avcC: [],
  15583. btrt: [],
  15584. dinf: [],
  15585. dref: [],
  15586. esds: [],
  15587. ftyp: [],
  15588. hdlr: [],
  15589. mdat: [],
  15590. mdhd: [],
  15591. mdia: [],
  15592. mfhd: [],
  15593. minf: [],
  15594. moof: [],
  15595. moov: [],
  15596. mp4a: [],
  15597. '.mp3': [],
  15598. dac3: [],
  15599. 'ac-3': [],
  15600. mvex: [],
  15601. mvhd: [],
  15602. pasp: [],
  15603. sdtp: [],
  15604. stbl: [],
  15605. stco: [],
  15606. stsc: [],
  15607. stsd: [],
  15608. stsz: [],
  15609. stts: [],
  15610. tfdt: [],
  15611. tfhd: [],
  15612. traf: [],
  15613. trak: [],
  15614. trun: [],
  15615. trex: [],
  15616. tkhd: [],
  15617. vmhd: [],
  15618. smhd: []
  15619. };
  15620. var i;
  15621. for (i in MP4.types) {
  15622. if (MP4.types.hasOwnProperty(i)) {
  15623. MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  15624. }
  15625. }
  15626. var videoHdlr = new Uint8Array([0x00,
  15627. // version 0
  15628. 0x00, 0x00, 0x00,
  15629. // flags
  15630. 0x00, 0x00, 0x00, 0x00,
  15631. // pre_defined
  15632. 0x76, 0x69, 0x64, 0x65,
  15633. // handler_type: 'vide'
  15634. 0x00, 0x00, 0x00, 0x00,
  15635. // reserved
  15636. 0x00, 0x00, 0x00, 0x00,
  15637. // reserved
  15638. 0x00, 0x00, 0x00, 0x00,
  15639. // reserved
  15640. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  15641. ]);
  15642. var audioHdlr = new Uint8Array([0x00,
  15643. // version 0
  15644. 0x00, 0x00, 0x00,
  15645. // flags
  15646. 0x00, 0x00, 0x00, 0x00,
  15647. // pre_defined
  15648. 0x73, 0x6f, 0x75, 0x6e,
  15649. // handler_type: 'soun'
  15650. 0x00, 0x00, 0x00, 0x00,
  15651. // reserved
  15652. 0x00, 0x00, 0x00, 0x00,
  15653. // reserved
  15654. 0x00, 0x00, 0x00, 0x00,
  15655. // reserved
  15656. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  15657. ]);
  15658. MP4.HDLR_TYPES = {
  15659. video: videoHdlr,
  15660. audio: audioHdlr
  15661. };
  15662. var dref = new Uint8Array([0x00,
  15663. // version 0
  15664. 0x00, 0x00, 0x00,
  15665. // flags
  15666. 0x00, 0x00, 0x00, 0x01,
  15667. // entry_count
  15668. 0x00, 0x00, 0x00, 0x0c,
  15669. // entry_size
  15670. 0x75, 0x72, 0x6c, 0x20,
  15671. // 'url' type
  15672. 0x00,
  15673. // version 0
  15674. 0x00, 0x00, 0x01 // entry_flags
  15675. ]);
  15676. var stco = new Uint8Array([0x00,
  15677. // version
  15678. 0x00, 0x00, 0x00,
  15679. // flags
  15680. 0x00, 0x00, 0x00, 0x00 // entry_count
  15681. ]);
  15682. MP4.STTS = MP4.STSC = MP4.STCO = stco;
  15683. MP4.STSZ = new Uint8Array([0x00,
  15684. // version
  15685. 0x00, 0x00, 0x00,
  15686. // flags
  15687. 0x00, 0x00, 0x00, 0x00,
  15688. // sample_size
  15689. 0x00, 0x00, 0x00, 0x00 // sample_count
  15690. ]);
  15691. MP4.VMHD = new Uint8Array([0x00,
  15692. // version
  15693. 0x00, 0x00, 0x01,
  15694. // flags
  15695. 0x00, 0x00,
  15696. // graphicsmode
  15697. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  15698. ]);
  15699. MP4.SMHD = new Uint8Array([0x00,
  15700. // version
  15701. 0x00, 0x00, 0x00,
  15702. // flags
  15703. 0x00, 0x00,
  15704. // balance
  15705. 0x00, 0x00 // reserved
  15706. ]);
  15707. MP4.STSD = new Uint8Array([0x00,
  15708. // version 0
  15709. 0x00, 0x00, 0x00,
  15710. // flags
  15711. 0x00, 0x00, 0x00, 0x01]); // entry_count
  15712. var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom
  15713. var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1
  15714. var minorVersion = new Uint8Array([0, 0, 0, 1]);
  15715. MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
  15716. MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
  15717. };
  15718. MP4.box = function box(type) {
  15719. var size = 8;
  15720. for (var _len = arguments.length, payload = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  15721. payload[_key - 1] = arguments[_key];
  15722. }
  15723. var i = payload.length;
  15724. var len = i;
  15725. // calculate the total size we need to allocate
  15726. while (i--) {
  15727. size += payload[i].byteLength;
  15728. }
  15729. var result = new Uint8Array(size);
  15730. result[0] = size >> 24 & 0xff;
  15731. result[1] = size >> 16 & 0xff;
  15732. result[2] = size >> 8 & 0xff;
  15733. result[3] = size & 0xff;
  15734. result.set(type, 4);
  15735. // copy the payload into the result
  15736. for (i = 0, size = 8; i < len; i++) {
  15737. // copy payload[i] array @ offset size
  15738. result.set(payload[i], size);
  15739. size += payload[i].byteLength;
  15740. }
  15741. return result;
  15742. };
  15743. MP4.hdlr = function hdlr(type) {
  15744. return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
  15745. };
  15746. MP4.mdat = function mdat(data) {
  15747. return MP4.box(MP4.types.mdat, data);
  15748. };
  15749. MP4.mdhd = function mdhd(timescale, duration) {
  15750. duration *= timescale;
  15751. var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  15752. var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  15753. return MP4.box(MP4.types.mdhd, new Uint8Array([0x01,
  15754. // version 1
  15755. 0x00, 0x00, 0x00,
  15756. // flags
  15757. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  15758. // creation_time
  15759. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  15760. // modification_time
  15761. timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff,
  15762. // timescale
  15763. upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x55, 0xc4,
  15764. // 'und' language (undetermined)
  15765. 0x00, 0x00]));
  15766. };
  15767. MP4.mdia = function mdia(track) {
  15768. return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));
  15769. };
  15770. MP4.mfhd = function mfhd(sequenceNumber) {
  15771. return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00,
  15772. // flags
  15773. sequenceNumber >> 24, sequenceNumber >> 16 & 0xff, sequenceNumber >> 8 & 0xff, sequenceNumber & 0xff // sequence_number
  15774. ]));
  15775. };
  15776. MP4.minf = function minf(track) {
  15777. if (track.type === 'audio') {
  15778. return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
  15779. } else {
  15780. return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
  15781. }
  15782. };
  15783. MP4.moof = function moof(sn, baseMediaDecodeTime, track) {
  15784. return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
  15785. };
  15786. MP4.moov = function moov(tracks) {
  15787. var i = tracks.length;
  15788. var boxes = [];
  15789. while (i--) {
  15790. boxes[i] = MP4.trak(tracks[i]);
  15791. }
  15792. return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));
  15793. };
  15794. MP4.mvex = function mvex(tracks) {
  15795. var i = tracks.length;
  15796. var boxes = [];
  15797. while (i--) {
  15798. boxes[i] = MP4.trex(tracks[i]);
  15799. }
  15800. return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));
  15801. };
  15802. MP4.mvhd = function mvhd(timescale, duration) {
  15803. duration *= timescale;
  15804. var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  15805. var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  15806. var bytes = new Uint8Array([0x01,
  15807. // version 1
  15808. 0x00, 0x00, 0x00,
  15809. // flags
  15810. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  15811. // creation_time
  15812. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  15813. // modification_time
  15814. timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff,
  15815. // timescale
  15816. upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x00, 0x01, 0x00, 0x00,
  15817. // 1.0 rate
  15818. 0x01, 0x00,
  15819. // 1.0 volume
  15820. 0x00, 0x00,
  15821. // reserved
  15822. 0x00, 0x00, 0x00, 0x00,
  15823. // reserved
  15824. 0x00, 0x00, 0x00, 0x00,
  15825. // reserved
  15826. 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,
  15827. // transformation: unity matrix
  15828. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  15829. // pre_defined
  15830. 0xff, 0xff, 0xff, 0xff // next_track_ID
  15831. ]);
  15832. return MP4.box(MP4.types.mvhd, bytes);
  15833. };
  15834. MP4.sdtp = function sdtp(track) {
  15835. var samples = track.samples || [];
  15836. var bytes = new Uint8Array(4 + samples.length);
  15837. var i;
  15838. var flags;
  15839. // leave the full box header (4 bytes) all zero
  15840. // write the sample table
  15841. for (i = 0; i < samples.length; i++) {
  15842. flags = samples[i].flags;
  15843. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  15844. }
  15845. return MP4.box(MP4.types.sdtp, bytes);
  15846. };
  15847. MP4.stbl = function stbl(track) {
  15848. 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));
  15849. };
  15850. MP4.avc1 = function avc1(track) {
  15851. var sps = [];
  15852. var pps = [];
  15853. var i;
  15854. var data;
  15855. var len;
  15856. // assemble the SPSs
  15857. for (i = 0; i < track.sps.length; i++) {
  15858. data = track.sps[i];
  15859. len = data.byteLength;
  15860. sps.push(len >>> 8 & 0xff);
  15861. sps.push(len & 0xff);
  15862. // SPS
  15863. sps = sps.concat(Array.prototype.slice.call(data));
  15864. }
  15865. // assemble the PPSs
  15866. for (i = 0; i < track.pps.length; i++) {
  15867. data = track.pps[i];
  15868. len = data.byteLength;
  15869. pps.push(len >>> 8 & 0xff);
  15870. pps.push(len & 0xff);
  15871. pps = pps.concat(Array.prototype.slice.call(data));
  15872. }
  15873. var avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01,
  15874. // version
  15875. sps[3],
  15876. // profile
  15877. sps[4],
  15878. // profile compat
  15879. sps[5],
  15880. // level
  15881. 0xfc | 3,
  15882. // lengthSizeMinusOne, hard-coded to 4 bytes
  15883. 0xe0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets
  15884. ].concat(sps).concat([track.pps.length // numOfPictureParameterSets
  15885. ]).concat(pps))); // "PPS"
  15886. var width = track.width;
  15887. var height = track.height;
  15888. var hSpacing = track.pixelRatio[0];
  15889. var vSpacing = track.pixelRatio[1];
  15890. return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00,
  15891. // reserved
  15892. 0x00, 0x00, 0x00,
  15893. // reserved
  15894. 0x00, 0x01,
  15895. // data_reference_index
  15896. 0x00, 0x00,
  15897. // pre_defined
  15898. 0x00, 0x00,
  15899. // reserved
  15900. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  15901. // pre_defined
  15902. width >> 8 & 0xff, width & 0xff,
  15903. // width
  15904. height >> 8 & 0xff, height & 0xff,
  15905. // height
  15906. 0x00, 0x48, 0x00, 0x00,
  15907. // horizresolution
  15908. 0x00, 0x48, 0x00, 0x00,
  15909. // vertresolution
  15910. 0x00, 0x00, 0x00, 0x00,
  15911. // reserved
  15912. 0x00, 0x01,
  15913. // frame_count
  15914. 0x12, 0x64, 0x61, 0x69, 0x6c,
  15915. // dailymotion/hls.js
  15916. 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,
  15917. // compressorname
  15918. 0x00, 0x18,
  15919. // depth = 24
  15920. 0x11, 0x11]),
  15921. // pre_defined = -1
  15922. avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80,
  15923. // bufferSizeDB
  15924. 0x00, 0x2d, 0xc6, 0xc0,
  15925. // maxBitrate
  15926. 0x00, 0x2d, 0xc6, 0xc0])),
  15927. // avgBitrate
  15928. MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24,
  15929. // hSpacing
  15930. hSpacing >> 16 & 0xff, hSpacing >> 8 & 0xff, hSpacing & 0xff, vSpacing >> 24,
  15931. // vSpacing
  15932. vSpacing >> 16 & 0xff, vSpacing >> 8 & 0xff, vSpacing & 0xff])));
  15933. };
  15934. MP4.esds = function esds(track) {
  15935. var configlen = track.config.length;
  15936. return new Uint8Array([0x00,
  15937. // version 0
  15938. 0x00, 0x00, 0x00,
  15939. // flags
  15940. 0x03,
  15941. // descriptor_type
  15942. 0x17 + configlen,
  15943. // length
  15944. 0x00, 0x01,
  15945. // es_id
  15946. 0x00,
  15947. // stream_priority
  15948. 0x04,
  15949. // descriptor_type
  15950. 0x0f + configlen,
  15951. // length
  15952. 0x40,
  15953. // codec : mpeg4_audio
  15954. 0x15,
  15955. // stream_type
  15956. 0x00, 0x00, 0x00,
  15957. // buffer_size
  15958. 0x00, 0x00, 0x00, 0x00,
  15959. // maxBitrate
  15960. 0x00, 0x00, 0x00, 0x00,
  15961. // avgBitrate
  15962. 0x05 // descriptor_type
  15963. ].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor
  15964. };
  15965. MP4.audioStsd = function audioStsd(track) {
  15966. var samplerate = track.samplerate;
  15967. return new Uint8Array([0x00, 0x00, 0x00,
  15968. // reserved
  15969. 0x00, 0x00, 0x00,
  15970. // reserved
  15971. 0x00, 0x01,
  15972. // data_reference_index
  15973. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  15974. // reserved
  15975. 0x00, track.channelCount,
  15976. // channelcount
  15977. 0x00, 0x10,
  15978. // sampleSize:16bits
  15979. 0x00, 0x00, 0x00, 0x00,
  15980. // reserved2
  15981. samplerate >> 8 & 0xff, samplerate & 0xff,
  15982. //
  15983. 0x00, 0x00]);
  15984. };
  15985. MP4.mp4a = function mp4a(track) {
  15986. return MP4.box(MP4.types.mp4a, MP4.audioStsd(track), MP4.box(MP4.types.esds, MP4.esds(track)));
  15987. };
  15988. MP4.mp3 = function mp3(track) {
  15989. return MP4.box(MP4.types['.mp3'], MP4.audioStsd(track));
  15990. };
  15991. MP4.ac3 = function ac3(track) {
  15992. return MP4.box(MP4.types['ac-3'], MP4.audioStsd(track), MP4.box(MP4.types.dac3, track.config));
  15993. };
  15994. MP4.stsd = function stsd(track) {
  15995. if (track.type === 'audio') {
  15996. if (track.segmentCodec === 'mp3' && track.codec === 'mp3') {
  15997. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));
  15998. }
  15999. if (track.segmentCodec === 'ac3') {
  16000. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.ac3(track));
  16001. }
  16002. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
  16003. } else {
  16004. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
  16005. }
  16006. };
  16007. MP4.tkhd = function tkhd(track) {
  16008. var id = track.id;
  16009. var duration = track.duration * track.timescale;
  16010. var width = track.width;
  16011. var height = track.height;
  16012. var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  16013. var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  16014. return MP4.box(MP4.types.tkhd, new Uint8Array([0x01,
  16015. // version 1
  16016. 0x00, 0x00, 0x07,
  16017. // flags
  16018. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  16019. // creation_time
  16020. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  16021. // modification_time
  16022. id >> 24 & 0xff, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff,
  16023. // track_ID
  16024. 0x00, 0x00, 0x00, 0x00,
  16025. // reserved
  16026. 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,
  16027. // reserved
  16028. 0x00, 0x00,
  16029. // layer
  16030. 0x00, 0x00,
  16031. // alternate_group
  16032. 0x00, 0x00,
  16033. // non-audio track volume
  16034. 0x00, 0x00,
  16035. // reserved
  16036. 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,
  16037. // transformation: unity matrix
  16038. width >> 8 & 0xff, width & 0xff, 0x00, 0x00,
  16039. // width
  16040. height >> 8 & 0xff, height & 0xff, 0x00, 0x00 // height
  16041. ]));
  16042. };
  16043. MP4.traf = function traf(track, baseMediaDecodeTime) {
  16044. var sampleDependencyTable = MP4.sdtp(track);
  16045. var id = track.id;
  16046. var upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
  16047. var lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
  16048. return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00,
  16049. // version 0
  16050. 0x00, 0x00, 0x00,
  16051. // flags
  16052. id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff // track_ID
  16053. ])), MP4.box(MP4.types.tfdt, new Uint8Array([0x01,
  16054. // version 1
  16055. 0x00, 0x00, 0x00,
  16056. // flags
  16057. 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 +
  16058. // tfhd
  16059. 20 +
  16060. // tfdt
  16061. 8 +
  16062. // traf header
  16063. 16 +
  16064. // mfhd
  16065. 8 +
  16066. // moof header
  16067. 8),
  16068. // mdat header
  16069. sampleDependencyTable);
  16070. }
  16071. /**
  16072. * Generate a track box.
  16073. * @param track a track definition
  16074. */;
  16075. MP4.trak = function trak(track) {
  16076. track.duration = track.duration || 0xffffffff;
  16077. return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
  16078. };
  16079. MP4.trex = function trex(track) {
  16080. var id = track.id;
  16081. return MP4.box(MP4.types.trex, new Uint8Array([0x00,
  16082. // version 0
  16083. 0x00, 0x00, 0x00,
  16084. // flags
  16085. id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff,
  16086. // track_ID
  16087. 0x00, 0x00, 0x00, 0x01,
  16088. // default_sample_description_index
  16089. 0x00, 0x00, 0x00, 0x00,
  16090. // default_sample_duration
  16091. 0x00, 0x00, 0x00, 0x00,
  16092. // default_sample_size
  16093. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  16094. ]));
  16095. };
  16096. MP4.trun = function trun(track, offset) {
  16097. var samples = track.samples || [];
  16098. var len = samples.length;
  16099. var arraylen = 12 + 16 * len;
  16100. var array = new Uint8Array(arraylen);
  16101. var i;
  16102. var sample;
  16103. var duration;
  16104. var size;
  16105. var flags;
  16106. var cts;
  16107. offset += 8 + arraylen;
  16108. array.set([track.type === 'video' ? 0x01 : 0x00,
  16109. // version 1 for video with signed-int sample_composition_time_offset
  16110. 0x00, 0x0f, 0x01,
  16111. // flags
  16112. len >>> 24 & 0xff, len >>> 16 & 0xff, len >>> 8 & 0xff, len & 0xff,
  16113. // sample_count
  16114. offset >>> 24 & 0xff, offset >>> 16 & 0xff, offset >>> 8 & 0xff, offset & 0xff // data_offset
  16115. ], 0);
  16116. for (i = 0; i < len; i++) {
  16117. sample = samples[i];
  16118. duration = sample.duration;
  16119. size = sample.size;
  16120. flags = sample.flags;
  16121. cts = sample.cts;
  16122. array.set([duration >>> 24 & 0xff, duration >>> 16 & 0xff, duration >>> 8 & 0xff, duration & 0xff,
  16123. // sample_duration
  16124. size >>> 24 & 0xff, size >>> 16 & 0xff, size >>> 8 & 0xff, size & 0xff,
  16125. // sample_size
  16126. flags.isLeading << 2 | flags.dependsOn, flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync, flags.degradPrio & 0xf0 << 8, flags.degradPrio & 0x0f,
  16127. // sample_flags
  16128. cts >>> 24 & 0xff, cts >>> 16 & 0xff, cts >>> 8 & 0xff, cts & 0xff // sample_composition_time_offset
  16129. ], 12 + 16 * i);
  16130. }
  16131. return MP4.box(MP4.types.trun, array);
  16132. };
  16133. MP4.initSegment = function initSegment(tracks) {
  16134. if (!MP4.types) {
  16135. MP4.init();
  16136. }
  16137. var movie = MP4.moov(tracks);
  16138. var result = appendUint8Array(MP4.FTYP, movie);
  16139. return result;
  16140. };
  16141. return MP4;
  16142. }();
  16143. MP4.types = void 0;
  16144. MP4.HDLR_TYPES = void 0;
  16145. MP4.STTS = void 0;
  16146. MP4.STSC = void 0;
  16147. MP4.STCO = void 0;
  16148. MP4.STSZ = void 0;
  16149. MP4.VMHD = void 0;
  16150. MP4.SMHD = void 0;
  16151. MP4.STSD = void 0;
  16152. MP4.FTYP = void 0;
  16153. MP4.DINF = void 0;
  16154. var MPEG_TS_CLOCK_FREQ_HZ = 90000;
  16155. function toTimescaleFromBase(baseTime, destScale, srcBase, round) {
  16156. if (srcBase === void 0) {
  16157. srcBase = 1;
  16158. }
  16159. if (round === void 0) {
  16160. round = false;
  16161. }
  16162. var result = baseTime * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)`
  16163. return round ? Math.round(result) : result;
  16164. }
  16165. function toMsFromMpegTsClock(baseTime, round) {
  16166. if (round === void 0) {
  16167. round = false;
  16168. }
  16169. return toTimescaleFromBase(baseTime, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);
  16170. }
  16171. var MAX_SILENT_FRAME_DURATION = 10 * 1000; // 10 seconds
  16172. var AAC_SAMPLES_PER_FRAME = 1024;
  16173. var MPEG_AUDIO_SAMPLE_PER_FRAME = 1152;
  16174. var AC3_SAMPLES_PER_FRAME = 1536;
  16175. var chromeVersion = null;
  16176. var safariWebkitVersion = null;
  16177. var MP4Remuxer = /*#__PURE__*/function () {
  16178. function MP4Remuxer(observer, config, typeSupported, vendor) {
  16179. this.observer = void 0;
  16180. this.config = void 0;
  16181. this.typeSupported = void 0;
  16182. this.ISGenerated = false;
  16183. this._initPTS = null;
  16184. this._initDTS = null;
  16185. this.nextAvcDts = null;
  16186. this.nextAudioPts = null;
  16187. this.videoSampleDuration = null;
  16188. this.isAudioContiguous = false;
  16189. this.isVideoContiguous = false;
  16190. this.videoTrackConfig = void 0;
  16191. this.observer = observer;
  16192. this.config = config;
  16193. this.typeSupported = typeSupported;
  16194. this.ISGenerated = false;
  16195. if (chromeVersion === null) {
  16196. var userAgent = navigator.userAgent || '';
  16197. var result = userAgent.match(/Chrome\/(\d+)/i);
  16198. chromeVersion = result ? parseInt(result[1]) : 0;
  16199. }
  16200. if (safariWebkitVersion === null) {
  16201. var _result = navigator.userAgent.match(/Safari\/(\d+)/i);
  16202. safariWebkitVersion = _result ? parseInt(_result[1]) : 0;
  16203. }
  16204. }
  16205. var _proto = MP4Remuxer.prototype;
  16206. _proto.destroy = function destroy() {
  16207. // @ts-ignore
  16208. this.config = this.videoTrackConfig = this._initPTS = this._initDTS = null;
  16209. };
  16210. _proto.resetTimeStamp = function resetTimeStamp(defaultTimeStamp) {
  16211. logger.log('[mp4-remuxer]: initPTS & initDTS reset');
  16212. this._initPTS = this._initDTS = defaultTimeStamp;
  16213. };
  16214. _proto.resetNextTimestamp = function resetNextTimestamp() {
  16215. logger.log('[mp4-remuxer]: reset next timestamp');
  16216. this.isVideoContiguous = false;
  16217. this.isAudioContiguous = false;
  16218. };
  16219. _proto.resetInitSegment = function resetInitSegment() {
  16220. logger.log('[mp4-remuxer]: ISGenerated flag reset');
  16221. this.ISGenerated = false;
  16222. this.videoTrackConfig = undefined;
  16223. };
  16224. _proto.getVideoStartPts = function getVideoStartPts(videoSamples) {
  16225. var rolloverDetected = false;
  16226. var startPTS = videoSamples.reduce(function (minPTS, sample) {
  16227. var delta = sample.pts - minPTS;
  16228. if (delta < -4294967296) {
  16229. // 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation
  16230. rolloverDetected = true;
  16231. return normalizePts(minPTS, sample.pts);
  16232. } else if (delta > 0) {
  16233. return minPTS;
  16234. } else {
  16235. return sample.pts;
  16236. }
  16237. }, videoSamples[0].pts);
  16238. if (rolloverDetected) {
  16239. logger.debug('PTS rollover detected');
  16240. }
  16241. return startPTS;
  16242. };
  16243. _proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, flush, playlistType) {
  16244. var video;
  16245. var audio;
  16246. var initSegment;
  16247. var text;
  16248. var id3;
  16249. var independent;
  16250. var audioTimeOffset = timeOffset;
  16251. var videoTimeOffset = timeOffset;
  16252. // If we're remuxing audio and video progressively, wait until we've received enough samples for each track before proceeding.
  16253. // This is done to synchronize the audio and video streams. We know if the current segment will have samples if the "pid"
  16254. // parameter is greater than -1. The pid is set when the PMT is parsed, which contains the tracks list.
  16255. // However, if the initSegment has already been generated, or we've reached the end of a segment (flush),
  16256. // then we can remux one track without waiting for the other.
  16257. var hasAudio = audioTrack.pid > -1;
  16258. var hasVideo = videoTrack.pid > -1;
  16259. var length = videoTrack.samples.length;
  16260. var enoughAudioSamples = audioTrack.samples.length > 0;
  16261. var enoughVideoSamples = flush && length > 0 || length > 1;
  16262. var canRemuxAvc = (!hasAudio || enoughAudioSamples) && (!hasVideo || enoughVideoSamples) || this.ISGenerated || flush;
  16263. if (canRemuxAvc) {
  16264. if (this.ISGenerated) {
  16265. var _videoTrack$pixelRati, _config$pixelRatio, _videoTrack$pixelRati2, _config$pixelRatio2;
  16266. var config = this.videoTrackConfig;
  16267. 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]))) {
  16268. this.resetInitSegment();
  16269. }
  16270. } else {
  16271. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  16272. }
  16273. var isVideoContiguous = this.isVideoContiguous;
  16274. var firstKeyFrameIndex = -1;
  16275. var firstKeyFramePTS;
  16276. if (enoughVideoSamples) {
  16277. firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples);
  16278. if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) {
  16279. independent = true;
  16280. if (firstKeyFrameIndex > 0) {
  16281. logger.warn("[mp4-remuxer]: Dropped " + firstKeyFrameIndex + " out of " + length + " video samples due to a missing keyframe");
  16282. var startPTS = this.getVideoStartPts(videoTrack.samples);
  16283. videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex);
  16284. videoTrack.dropped += firstKeyFrameIndex;
  16285. videoTimeOffset += (videoTrack.samples[0].pts - startPTS) / videoTrack.inputTimeScale;
  16286. firstKeyFramePTS = videoTimeOffset;
  16287. } else if (firstKeyFrameIndex === -1) {
  16288. logger.warn("[mp4-remuxer]: No keyframe found out of " + length + " video samples");
  16289. independent = false;
  16290. }
  16291. }
  16292. }
  16293. if (this.ISGenerated) {
  16294. if (enoughAudioSamples && enoughVideoSamples) {
  16295. // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)
  16296. // if first audio DTS is not aligned with first video DTS then we need to take that into account
  16297. // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small
  16298. // drift between audio and video streams
  16299. var _startPTS = this.getVideoStartPts(videoTrack.samples);
  16300. var tsDelta = normalizePts(audioTrack.samples[0].pts, _startPTS) - _startPTS;
  16301. var audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;
  16302. audioTimeOffset += Math.max(0, audiovideoTimestampDelta);
  16303. videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);
  16304. }
  16305. // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is calculated in remuxAudio.
  16306. if (enoughAudioSamples) {
  16307. // if initSegment was generated without audio samples, regenerate it again
  16308. if (!audioTrack.samplerate) {
  16309. logger.warn('[mp4-remuxer]: regenerate InitSegment as audio detected');
  16310. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  16311. }
  16312. audio = this.remuxAudio(audioTrack, audioTimeOffset, this.isAudioContiguous, accurateTimeOffset, hasVideo || enoughVideoSamples || playlistType === PlaylistLevelType.AUDIO ? videoTimeOffset : undefined);
  16313. if (enoughVideoSamples) {
  16314. var audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0;
  16315. // if initSegment was generated without video samples, regenerate it again
  16316. if (!videoTrack.inputTimeScale) {
  16317. logger.warn('[mp4-remuxer]: regenerate InitSegment as video detected');
  16318. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  16319. }
  16320. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, audioTrackLength);
  16321. }
  16322. } else if (enoughVideoSamples) {
  16323. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, 0);
  16324. }
  16325. if (video) {
  16326. video.firstKeyFrame = firstKeyFrameIndex;
  16327. video.independent = firstKeyFrameIndex !== -1;
  16328. video.firstKeyFramePTS = firstKeyFramePTS;
  16329. }
  16330. }
  16331. }
  16332. // Allow ID3 and text to remux, even if more audio/video samples are required
  16333. if (this.ISGenerated && this._initPTS && this._initDTS) {
  16334. if (id3Track.samples.length) {
  16335. id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, this._initPTS, this._initDTS);
  16336. }
  16337. if (textTrack.samples.length) {
  16338. text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, this._initPTS);
  16339. }
  16340. }
  16341. return {
  16342. audio: audio,
  16343. video: video,
  16344. initSegment: initSegment,
  16345. independent: independent,
  16346. text: text,
  16347. id3: id3
  16348. };
  16349. };
  16350. _proto.generateIS = function generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset) {
  16351. var audioSamples = audioTrack.samples;
  16352. var videoSamples = videoTrack.samples;
  16353. var typeSupported = this.typeSupported;
  16354. var tracks = {};
  16355. var _initPTS = this._initPTS;
  16356. var computePTSDTS = !_initPTS || accurateTimeOffset;
  16357. var container = 'audio/mp4';
  16358. var initPTS;
  16359. var initDTS;
  16360. var timescale;
  16361. if (computePTSDTS) {
  16362. initPTS = initDTS = Infinity;
  16363. }
  16364. if (audioTrack.config && audioSamples.length) {
  16365. // let's use audio sampling rate as MP4 time scale.
  16366. // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)
  16367. // using audio sampling rate here helps having an integer MP4 frame duration
  16368. // this avoids potential rounding issue and AV sync issue
  16369. audioTrack.timescale = audioTrack.samplerate;
  16370. switch (audioTrack.segmentCodec) {
  16371. case 'mp3':
  16372. if (typeSupported.mpeg) {
  16373. // Chrome and Safari
  16374. container = 'audio/mpeg';
  16375. audioTrack.codec = '';
  16376. } else if (typeSupported.mp3) {
  16377. // Firefox
  16378. audioTrack.codec = 'mp3';
  16379. }
  16380. break;
  16381. case 'ac3':
  16382. audioTrack.codec = 'ac-3';
  16383. break;
  16384. }
  16385. tracks.audio = {
  16386. id: 'audio',
  16387. container: container,
  16388. codec: audioTrack.codec,
  16389. initSegment: audioTrack.segmentCodec === 'mp3' && typeSupported.mpeg ? new Uint8Array(0) : MP4.initSegment([audioTrack]),
  16390. metadata: {
  16391. channelCount: audioTrack.channelCount
  16392. }
  16393. };
  16394. if (computePTSDTS) {
  16395. timescale = audioTrack.inputTimeScale;
  16396. if (!_initPTS || timescale !== _initPTS.timescale) {
  16397. // remember first PTS of this demuxing context. for audio, PTS = DTS
  16398. initPTS = initDTS = audioSamples[0].pts - Math.round(timescale * timeOffset);
  16399. } else {
  16400. computePTSDTS = false;
  16401. }
  16402. }
  16403. }
  16404. if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
  16405. // let's use input time scale as MP4 video timescale
  16406. // we use input time scale straight away to avoid rounding issues on frame duration / cts computation
  16407. videoTrack.timescale = videoTrack.inputTimeScale;
  16408. tracks.video = {
  16409. id: 'main',
  16410. container: 'video/mp4',
  16411. codec: videoTrack.codec,
  16412. initSegment: MP4.initSegment([videoTrack]),
  16413. metadata: {
  16414. width: videoTrack.width,
  16415. height: videoTrack.height
  16416. }
  16417. };
  16418. if (computePTSDTS) {
  16419. timescale = videoTrack.inputTimeScale;
  16420. if (!_initPTS || timescale !== _initPTS.timescale) {
  16421. var startPTS = this.getVideoStartPts(videoSamples);
  16422. var startOffset = Math.round(timescale * timeOffset);
  16423. initDTS = Math.min(initDTS, normalizePts(videoSamples[0].dts, startPTS) - startOffset);
  16424. initPTS = Math.min(initPTS, startPTS - startOffset);
  16425. } else {
  16426. computePTSDTS = false;
  16427. }
  16428. }
  16429. this.videoTrackConfig = {
  16430. width: videoTrack.width,
  16431. height: videoTrack.height,
  16432. pixelRatio: videoTrack.pixelRatio
  16433. };
  16434. }
  16435. if (Object.keys(tracks).length) {
  16436. this.ISGenerated = true;
  16437. if (computePTSDTS) {
  16438. this._initPTS = {
  16439. baseTime: initPTS,
  16440. timescale: timescale
  16441. };
  16442. this._initDTS = {
  16443. baseTime: initDTS,
  16444. timescale: timescale
  16445. };
  16446. } else {
  16447. initPTS = timescale = undefined;
  16448. }
  16449. return {
  16450. tracks: tracks,
  16451. initPTS: initPTS,
  16452. timescale: timescale
  16453. };
  16454. }
  16455. };
  16456. _proto.remuxVideo = function remuxVideo(track, timeOffset, contiguous, audioTrackLength) {
  16457. var timeScale = track.inputTimeScale;
  16458. var inputSamples = track.samples;
  16459. var outputSamples = [];
  16460. var nbSamples = inputSamples.length;
  16461. var initPTS = this._initPTS;
  16462. var nextAvcDts = this.nextAvcDts;
  16463. var offset = 8;
  16464. var mp4SampleDuration = this.videoSampleDuration;
  16465. var firstDTS;
  16466. var lastDTS;
  16467. var minPTS = Number.POSITIVE_INFINITY;
  16468. var maxPTS = Number.NEGATIVE_INFINITY;
  16469. var sortSamples = false;
  16470. // if parsed fragment is contiguous with last one, let's use last DTS value as reference
  16471. if (!contiguous || nextAvcDts === null) {
  16472. var pts = timeOffset * timeScale;
  16473. var cts = inputSamples[0].pts - normalizePts(inputSamples[0].dts, inputSamples[0].pts);
  16474. if (chromeVersion && nextAvcDts !== null && Math.abs(pts - cts - nextAvcDts) < 15000) {
  16475. // treat as contigous to adjust samples that would otherwise produce video buffer gaps in Chrome
  16476. contiguous = true;
  16477. } else {
  16478. // if not contiguous, let's use target timeOffset
  16479. nextAvcDts = pts - cts;
  16480. }
  16481. }
  16482. // PTS is coded on 33bits, and can loop from -2^32 to 2^32
  16483. // PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value
  16484. var initTime = initPTS.baseTime * timeScale / initPTS.timescale;
  16485. for (var i = 0; i < nbSamples; i++) {
  16486. var sample = inputSamples[i];
  16487. sample.pts = normalizePts(sample.pts - initTime, nextAvcDts);
  16488. sample.dts = normalizePts(sample.dts - initTime, nextAvcDts);
  16489. if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {
  16490. sortSamples = true;
  16491. }
  16492. }
  16493. // sort video samples by DTS then PTS then demux id order
  16494. if (sortSamples) {
  16495. inputSamples.sort(function (a, b) {
  16496. var deltadts = a.dts - b.dts;
  16497. var deltapts = a.pts - b.pts;
  16498. return deltadts || deltapts;
  16499. });
  16500. }
  16501. // Get first/last DTS
  16502. firstDTS = inputSamples[0].dts;
  16503. lastDTS = inputSamples[inputSamples.length - 1].dts;
  16504. // Sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS
  16505. // set this constant duration as being the avg delta between consecutive DTS.
  16506. var inputDuration = lastDTS - firstDTS;
  16507. var averageSampleDuration = inputDuration ? Math.round(inputDuration / (nbSamples - 1)) : mp4SampleDuration || track.inputTimeScale / 30;
  16508. // if fragment are contiguous, detect hole/overlapping between fragments
  16509. if (contiguous) {
  16510. // check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)
  16511. var delta = firstDTS - nextAvcDts;
  16512. var foundHole = delta > averageSampleDuration;
  16513. var foundOverlap = delta < -1;
  16514. if (foundHole || foundOverlap) {
  16515. if (foundHole) {
  16516. logger.warn("AVC: " + toMsFromMpegTsClock(delta, true) + " ms (" + delta + "dts) hole between fragments detected at " + timeOffset.toFixed(3));
  16517. } else {
  16518. logger.warn("AVC: " + toMsFromMpegTsClock(-delta, true) + " ms (" + delta + "dts) overlapping between fragments detected at " + timeOffset.toFixed(3));
  16519. }
  16520. if (!foundOverlap || nextAvcDts >= inputSamples[0].pts || chromeVersion) {
  16521. firstDTS = nextAvcDts;
  16522. var firstPTS = inputSamples[0].pts - delta;
  16523. if (foundHole) {
  16524. inputSamples[0].dts = firstDTS;
  16525. inputSamples[0].pts = firstPTS;
  16526. } else {
  16527. for (var _i = 0; _i < inputSamples.length; _i++) {
  16528. if (inputSamples[_i].dts > firstPTS) {
  16529. break;
  16530. }
  16531. inputSamples[_i].dts -= delta;
  16532. inputSamples[_i].pts -= delta;
  16533. }
  16534. }
  16535. logger.log("Video: Initial PTS/DTS adjusted: " + toMsFromMpegTsClock(firstPTS, true) + "/" + toMsFromMpegTsClock(firstDTS, true) + ", delta: " + toMsFromMpegTsClock(delta, true) + " ms");
  16536. }
  16537. }
  16538. }
  16539. firstDTS = Math.max(0, firstDTS);
  16540. var nbNalu = 0;
  16541. var naluLen = 0;
  16542. var dtsStep = firstDTS;
  16543. for (var _i2 = 0; _i2 < nbSamples; _i2++) {
  16544. // compute total/avc sample length and nb of NAL units
  16545. var _sample = inputSamples[_i2];
  16546. var units = _sample.units;
  16547. var nbUnits = units.length;
  16548. var sampleLen = 0;
  16549. for (var j = 0; j < nbUnits; j++) {
  16550. sampleLen += units[j].data.length;
  16551. }
  16552. naluLen += sampleLen;
  16553. nbNalu += nbUnits;
  16554. _sample.length = sampleLen;
  16555. // ensure sample monotonic DTS
  16556. if (_sample.dts < dtsStep) {
  16557. _sample.dts = dtsStep;
  16558. dtsStep += averageSampleDuration / 4 | 0 || 1;
  16559. } else {
  16560. dtsStep = _sample.dts;
  16561. }
  16562. minPTS = Math.min(_sample.pts, minPTS);
  16563. maxPTS = Math.max(_sample.pts, maxPTS);
  16564. }
  16565. lastDTS = inputSamples[nbSamples - 1].dts;
  16566. /* concatenate the video data and construct the mdat in place
  16567. (need 8 more bytes to fill length and mpdat type) */
  16568. var mdatSize = naluLen + 4 * nbNalu + 8;
  16569. var mdat;
  16570. try {
  16571. mdat = new Uint8Array(mdatSize);
  16572. } catch (err) {
  16573. this.observer.emit(Events.ERROR, Events.ERROR, {
  16574. type: ErrorTypes.MUX_ERROR,
  16575. details: ErrorDetails.REMUX_ALLOC_ERROR,
  16576. fatal: false,
  16577. error: err,
  16578. bytes: mdatSize,
  16579. reason: "fail allocating video mdat " + mdatSize
  16580. });
  16581. return;
  16582. }
  16583. var view = new DataView(mdat.buffer);
  16584. view.setUint32(0, mdatSize);
  16585. mdat.set(MP4.types.mdat, 4);
  16586. var stretchedLastFrame = false;
  16587. var minDtsDelta = Number.POSITIVE_INFINITY;
  16588. var minPtsDelta = Number.POSITIVE_INFINITY;
  16589. var maxDtsDelta = Number.NEGATIVE_INFINITY;
  16590. var maxPtsDelta = Number.NEGATIVE_INFINITY;
  16591. for (var _i3 = 0; _i3 < nbSamples; _i3++) {
  16592. var _VideoSample = inputSamples[_i3];
  16593. var VideoSampleUnits = _VideoSample.units;
  16594. var mp4SampleLength = 0;
  16595. // convert NALU bitstream to MP4 format (prepend NALU with size field)
  16596. for (var _j = 0, _nbUnits = VideoSampleUnits.length; _j < _nbUnits; _j++) {
  16597. var unit = VideoSampleUnits[_j];
  16598. var unitData = unit.data;
  16599. var unitDataLen = unit.data.byteLength;
  16600. view.setUint32(offset, unitDataLen);
  16601. offset += 4;
  16602. mdat.set(unitData, offset);
  16603. offset += unitDataLen;
  16604. mp4SampleLength += 4 + unitDataLen;
  16605. }
  16606. // expected sample duration is the Decoding Timestamp diff of consecutive samples
  16607. var ptsDelta = void 0;
  16608. if (_i3 < nbSamples - 1) {
  16609. mp4SampleDuration = inputSamples[_i3 + 1].dts - _VideoSample.dts;
  16610. ptsDelta = inputSamples[_i3 + 1].pts - _VideoSample.pts;
  16611. } else {
  16612. var config = this.config;
  16613. var lastFrameDuration = _i3 > 0 ? _VideoSample.dts - inputSamples[_i3 - 1].dts : averageSampleDuration;
  16614. ptsDelta = _i3 > 0 ? _VideoSample.pts - inputSamples[_i3 - 1].pts : averageSampleDuration;
  16615. if (config.stretchShortVideoTrack && this.nextAudioPts !== null) {
  16616. // In some cases, a segment's audio track duration may exceed the video track duration.
  16617. // Since we've already remuxed audio, and we know how long the audio track is, we look to
  16618. // see if the delta to the next segment is longer than maxBufferHole.
  16619. // If so, playback would potentially get stuck, so we artificially inflate
  16620. // the duration of the last frame to minimize any potential gap between segments.
  16621. var gapTolerance = Math.floor(config.maxBufferHole * timeScale);
  16622. var deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioPts) - _VideoSample.pts;
  16623. if (deltaToFrameEnd > gapTolerance) {
  16624. // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video
  16625. // frame overlap. maxBufferHole should be >> lastFrameDuration anyway.
  16626. mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
  16627. if (mp4SampleDuration < 0) {
  16628. mp4SampleDuration = lastFrameDuration;
  16629. } else {
  16630. stretchedLastFrame = true;
  16631. }
  16632. logger.log("[mp4-remuxer]: It is approximately " + deltaToFrameEnd / 90 + " ms to the next segment; using duration " + mp4SampleDuration / 90 + " ms for the last video frame.");
  16633. } else {
  16634. mp4SampleDuration = lastFrameDuration;
  16635. }
  16636. } else {
  16637. mp4SampleDuration = lastFrameDuration;
  16638. }
  16639. }
  16640. var compositionTimeOffset = Math.round(_VideoSample.pts - _VideoSample.dts);
  16641. minDtsDelta = Math.min(minDtsDelta, mp4SampleDuration);
  16642. maxDtsDelta = Math.max(maxDtsDelta, mp4SampleDuration);
  16643. minPtsDelta = Math.min(minPtsDelta, ptsDelta);
  16644. maxPtsDelta = Math.max(maxPtsDelta, ptsDelta);
  16645. outputSamples.push(new Mp4Sample(_VideoSample.key, mp4SampleDuration, mp4SampleLength, compositionTimeOffset));
  16646. }
  16647. if (outputSamples.length) {
  16648. if (chromeVersion) {
  16649. if (chromeVersion < 70) {
  16650. // Chrome workaround, mark first sample as being a Random Access Point (keyframe) to avoid sourcebuffer append issue
  16651. // https://code.google.com/p/chromium/issues/detail?id=229412
  16652. var flags = outputSamples[0].flags;
  16653. flags.dependsOn = 2;
  16654. flags.isNonSync = 0;
  16655. }
  16656. } else if (safariWebkitVersion) {
  16657. // Fix for "CNN special report, with CC" in test-streams (Safari browser only)
  16658. // Ignore DTS when frame durations are irregular. Safari MSE does not handle this leading to gaps.
  16659. if (maxPtsDelta - minPtsDelta < maxDtsDelta - minDtsDelta && averageSampleDuration / maxDtsDelta < 0.025 && outputSamples[0].cts === 0) {
  16660. logger.warn('Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.');
  16661. var dts = firstDTS;
  16662. for (var _i4 = 0, len = outputSamples.length; _i4 < len; _i4++) {
  16663. var nextDts = dts + outputSamples[_i4].duration;
  16664. var _pts = dts + outputSamples[_i4].cts;
  16665. if (_i4 < len - 1) {
  16666. var nextPts = nextDts + outputSamples[_i4 + 1].cts;
  16667. outputSamples[_i4].duration = nextPts - _pts;
  16668. } else {
  16669. outputSamples[_i4].duration = _i4 ? outputSamples[_i4 - 1].duration : averageSampleDuration;
  16670. }
  16671. outputSamples[_i4].cts = 0;
  16672. dts = nextDts;
  16673. }
  16674. }
  16675. }
  16676. }
  16677. // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)
  16678. mp4SampleDuration = stretchedLastFrame || !mp4SampleDuration ? averageSampleDuration : mp4SampleDuration;
  16679. this.nextAvcDts = nextAvcDts = lastDTS + mp4SampleDuration;
  16680. this.videoSampleDuration = mp4SampleDuration;
  16681. this.isVideoContiguous = true;
  16682. var moof = MP4.moof(track.sequenceNumber++, firstDTS, _extends({}, track, {
  16683. samples: outputSamples
  16684. }));
  16685. var type = 'video';
  16686. var data = {
  16687. data1: moof,
  16688. data2: mdat,
  16689. startPTS: minPTS / timeScale,
  16690. endPTS: (maxPTS + mp4SampleDuration) / timeScale,
  16691. startDTS: firstDTS / timeScale,
  16692. endDTS: nextAvcDts / timeScale,
  16693. type: type,
  16694. hasAudio: false,
  16695. hasVideo: true,
  16696. nb: outputSamples.length,
  16697. dropped: track.dropped
  16698. };
  16699. track.samples = [];
  16700. track.dropped = 0;
  16701. return data;
  16702. };
  16703. _proto.getSamplesPerFrame = function getSamplesPerFrame(track) {
  16704. switch (track.segmentCodec) {
  16705. case 'mp3':
  16706. return MPEG_AUDIO_SAMPLE_PER_FRAME;
  16707. case 'ac3':
  16708. return AC3_SAMPLES_PER_FRAME;
  16709. default:
  16710. return AAC_SAMPLES_PER_FRAME;
  16711. }
  16712. };
  16713. _proto.remuxAudio = function remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, videoTimeOffset) {
  16714. var inputTimeScale = track.inputTimeScale;
  16715. var mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
  16716. var scaleFactor = inputTimeScale / mp4timeScale;
  16717. var mp4SampleDuration = this.getSamplesPerFrame(track);
  16718. var inputSampleDuration = mp4SampleDuration * scaleFactor;
  16719. var initPTS = this._initPTS;
  16720. var rawMPEG = track.segmentCodec === 'mp3' && this.typeSupported.mpeg;
  16721. var outputSamples = [];
  16722. var alignedWithVideo = videoTimeOffset !== undefined;
  16723. var inputSamples = track.samples;
  16724. var offset = rawMPEG ? 0 : 8;
  16725. var nextAudioPts = this.nextAudioPts || -1;
  16726. // window.audioSamples ? window.audioSamples.push(inputSamples.map(s => s.pts)) : (window.audioSamples = [inputSamples.map(s => s.pts)]);
  16727. // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),
  16728. // for sake of clarity:
  16729. // consecutive fragments are frags with
  16730. // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
  16731. // - less than 20 audio frames distance
  16732. // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
  16733. // this helps ensuring audio continuity
  16734. // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame
  16735. var timeOffsetMpegTS = timeOffset * inputTimeScale;
  16736. var initTime = initPTS.baseTime * inputTimeScale / initPTS.timescale;
  16737. 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);
  16738. // compute normalized PTS
  16739. inputSamples.forEach(function (sample) {
  16740. sample.pts = normalizePts(sample.pts - initTime, timeOffsetMpegTS);
  16741. });
  16742. if (!contiguous || nextAudioPts < 0) {
  16743. // filter out sample with negative PTS that are not playable anyway
  16744. // if we don't remove these negative samples, they will shift all audio samples forward.
  16745. // leading to audio overlap between current / next fragment
  16746. inputSamples = inputSamples.filter(function (sample) {
  16747. return sample.pts >= 0;
  16748. });
  16749. // in case all samples have negative PTS, and have been filtered out, return now
  16750. if (!inputSamples.length) {
  16751. return;
  16752. }
  16753. if (videoTimeOffset === 0) {
  16754. // Set the start to 0 to match video so that start gaps larger than inputSampleDuration are filled with silence
  16755. nextAudioPts = 0;
  16756. } else if (accurateTimeOffset && !alignedWithVideo) {
  16757. // When not seeking, not live, and LevelDetails.PTSKnown, use fragment start as predicted next audio PTS
  16758. nextAudioPts = Math.max(0, timeOffsetMpegTS);
  16759. } else {
  16760. // if frags are not contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS
  16761. nextAudioPts = inputSamples[0].pts;
  16762. }
  16763. }
  16764. // If the audio track is missing samples, the frames seem to get "left-shifted" within the
  16765. // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.
  16766. // In an effort to prevent this from happening, we inject frames here where there are gaps.
  16767. // When possible, we inject a silent frame; when that's not possible, we duplicate the last
  16768. // frame.
  16769. if (track.segmentCodec === 'aac') {
  16770. var maxAudioFramesDrift = this.config.maxAudioFramesDrift;
  16771. for (var i = 0, nextPts = nextAudioPts; i < inputSamples.length; i++) {
  16772. // First, let's see how far off this frame is from where we expect it to be
  16773. var sample = inputSamples[i];
  16774. var pts = sample.pts;
  16775. var delta = pts - nextPts;
  16776. var duration = Math.abs(1000 * delta / inputTimeScale);
  16777. // When remuxing with video, if we're overlapping by more than a duration, drop this sample to stay in sync
  16778. if (delta <= -maxAudioFramesDrift * inputSampleDuration && alignedWithVideo) {
  16779. if (i === 0) {
  16780. logger.warn("Audio frame @ " + (pts / inputTimeScale).toFixed(3) + "s overlaps nextAudioPts by " + Math.round(1000 * delta / inputTimeScale) + " ms.");
  16781. this.nextAudioPts = nextAudioPts = nextPts = pts;
  16782. }
  16783. } // eslint-disable-line brace-style
  16784. // Insert missing frames if:
  16785. // 1: We're more than maxAudioFramesDrift frame away
  16786. // 2: Not more than MAX_SILENT_FRAME_DURATION away
  16787. // 3: currentTime (aka nextPtsNorm) is not 0
  16788. // 4: remuxing with video (videoTimeOffset !== undefined)
  16789. else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && alignedWithVideo) {
  16790. var missing = Math.round(delta / inputSampleDuration);
  16791. // Adjust nextPts so that silent samples are aligned with media pts. This will prevent media samples from
  16792. // later being shifted if nextPts is based on timeOffset and delta is not a multiple of inputSampleDuration.
  16793. nextPts = pts - missing * inputSampleDuration;
  16794. if (nextPts < 0) {
  16795. missing--;
  16796. nextPts += inputSampleDuration;
  16797. }
  16798. if (i === 0) {
  16799. this.nextAudioPts = nextAudioPts = nextPts;
  16800. }
  16801. logger.warn("[mp4-remuxer]: Injecting " + missing + " audio frame @ " + (nextPts / inputTimeScale).toFixed(3) + "s due to " + Math.round(1000 * delta / inputTimeScale) + " ms gap.");
  16802. for (var j = 0; j < missing; j++) {
  16803. var newStamp = Math.max(nextPts, 0);
  16804. var fillFrame = AAC.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  16805. if (!fillFrame) {
  16806. logger.log('[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead.');
  16807. fillFrame = sample.unit.subarray();
  16808. }
  16809. inputSamples.splice(i, 0, {
  16810. unit: fillFrame,
  16811. pts: newStamp
  16812. });
  16813. nextPts += inputSampleDuration;
  16814. i++;
  16815. }
  16816. }
  16817. sample.pts = nextPts;
  16818. nextPts += inputSampleDuration;
  16819. }
  16820. }
  16821. var firstPTS = null;
  16822. var lastPTS = null;
  16823. var mdat;
  16824. var mdatSize = 0;
  16825. var sampleLength = inputSamples.length;
  16826. while (sampleLength--) {
  16827. mdatSize += inputSamples[sampleLength].unit.byteLength;
  16828. }
  16829. for (var _j2 = 0, _nbSamples = inputSamples.length; _j2 < _nbSamples; _j2++) {
  16830. var audioSample = inputSamples[_j2];
  16831. var unit = audioSample.unit;
  16832. var _pts2 = audioSample.pts;
  16833. if (lastPTS !== null) {
  16834. // If we have more than one sample, set the duration of the sample to the "real" duration; the PTS diff with
  16835. // the previous sample
  16836. var prevSample = outputSamples[_j2 - 1];
  16837. prevSample.duration = Math.round((_pts2 - lastPTS) / scaleFactor);
  16838. } else {
  16839. if (contiguous && track.segmentCodec === 'aac') {
  16840. // set PTS/DTS to expected PTS/DTS
  16841. _pts2 = nextAudioPts;
  16842. }
  16843. // remember first PTS of our audioSamples
  16844. firstPTS = _pts2;
  16845. if (mdatSize > 0) {
  16846. /* concatenate the audio data and construct the mdat in place
  16847. (need 8 more bytes to fill length and mdat type) */
  16848. mdatSize += offset;
  16849. try {
  16850. mdat = new Uint8Array(mdatSize);
  16851. } catch (err) {
  16852. this.observer.emit(Events.ERROR, Events.ERROR, {
  16853. type: ErrorTypes.MUX_ERROR,
  16854. details: ErrorDetails.REMUX_ALLOC_ERROR,
  16855. fatal: false,
  16856. error: err,
  16857. bytes: mdatSize,
  16858. reason: "fail allocating audio mdat " + mdatSize
  16859. });
  16860. return;
  16861. }
  16862. if (!rawMPEG) {
  16863. var view = new DataView(mdat.buffer);
  16864. view.setUint32(0, mdatSize);
  16865. mdat.set(MP4.types.mdat, 4);
  16866. }
  16867. } else {
  16868. // no audio samples
  16869. return;
  16870. }
  16871. }
  16872. mdat.set(unit, offset);
  16873. var unitLen = unit.byteLength;
  16874. offset += unitLen;
  16875. // Default the sample's duration to the computed mp4SampleDuration, which will either be 1024 for AAC or 1152 for MPEG
  16876. // In the case that we have 1 sample, this will be the duration. If we have more than one sample, the duration
  16877. // becomes the PTS diff with the previous sample
  16878. outputSamples.push(new Mp4Sample(true, mp4SampleDuration, unitLen, 0));
  16879. lastPTS = _pts2;
  16880. }
  16881. // We could end up with no audio samples if all input samples were overlapping with the previously remuxed ones
  16882. var nbSamples = outputSamples.length;
  16883. if (!nbSamples) {
  16884. return;
  16885. }
  16886. // The next audio sample PTS should be equal to last sample PTS + duration
  16887. var lastSample = outputSamples[outputSamples.length - 1];
  16888. this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSample.duration;
  16889. // Set the track samples from inputSamples to outputSamples before remuxing
  16890. var moof = rawMPEG ? new Uint8Array(0) : MP4.moof(track.sequenceNumber++, firstPTS / scaleFactor, _extends({}, track, {
  16891. samples: outputSamples
  16892. }));
  16893. // Clear the track samples. This also clears the samples array in the demuxer, since the reference is shared
  16894. track.samples = [];
  16895. var start = firstPTS / inputTimeScale;
  16896. var end = nextAudioPts / inputTimeScale;
  16897. var type = 'audio';
  16898. var audioData = {
  16899. data1: moof,
  16900. data2: mdat,
  16901. startPTS: start,
  16902. endPTS: end,
  16903. startDTS: start,
  16904. endDTS: end,
  16905. type: type,
  16906. hasAudio: true,
  16907. hasVideo: false,
  16908. nb: nbSamples
  16909. };
  16910. this.isAudioContiguous = true;
  16911. return audioData;
  16912. };
  16913. _proto.remuxEmptyAudio = function remuxEmptyAudio(track, timeOffset, contiguous, videoData) {
  16914. var inputTimeScale = track.inputTimeScale;
  16915. var mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
  16916. var scaleFactor = inputTimeScale / mp4timeScale;
  16917. var nextAudioPts = this.nextAudioPts;
  16918. // sync with video's timestamp
  16919. var initDTS = this._initDTS;
  16920. var init90kHz = initDTS.baseTime * 90000 / initDTS.timescale;
  16921. var startDTS = (nextAudioPts !== null ? nextAudioPts : videoData.startDTS * inputTimeScale) + init90kHz;
  16922. var endDTS = videoData.endDTS * inputTimeScale + init90kHz;
  16923. // one sample's duration value
  16924. var frameDuration = scaleFactor * AAC_SAMPLES_PER_FRAME;
  16925. // samples count of this segment's duration
  16926. var nbSamples = Math.ceil((endDTS - startDTS) / frameDuration);
  16927. // silent frame
  16928. var silentFrame = AAC.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  16929. logger.warn('[mp4-remuxer]: remux empty Audio');
  16930. // Can't remux if we can't generate a silent frame...
  16931. if (!silentFrame) {
  16932. logger.trace('[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec');
  16933. return;
  16934. }
  16935. var samples = [];
  16936. for (var i = 0; i < nbSamples; i++) {
  16937. var stamp = startDTS + i * frameDuration;
  16938. samples.push({
  16939. unit: silentFrame,
  16940. pts: stamp,
  16941. dts: stamp
  16942. });
  16943. }
  16944. track.samples = samples;
  16945. return this.remuxAudio(track, timeOffset, contiguous, false);
  16946. };
  16947. return MP4Remuxer;
  16948. }();
  16949. function normalizePts(value, reference) {
  16950. var offset;
  16951. if (reference === null) {
  16952. return value;
  16953. }
  16954. if (reference < value) {
  16955. // - 2^33
  16956. offset = -8589934592;
  16957. } else {
  16958. // + 2^33
  16959. offset = 8589934592;
  16960. }
  16961. /* PTS is 33bit (from 0 to 2^33 -1)
  16962. if diff between value and reference is bigger than half of the amplitude (2^32) then it means that
  16963. PTS looping occured. fill the gap */
  16964. while (Math.abs(value - reference) > 4294967296) {
  16965. value += offset;
  16966. }
  16967. return value;
  16968. }
  16969. function findKeyframeIndex(samples) {
  16970. for (var i = 0; i < samples.length; i++) {
  16971. if (samples[i].key) {
  16972. return i;
  16973. }
  16974. }
  16975. return -1;
  16976. }
  16977. function flushTextTrackMetadataCueSamples(track, timeOffset, initPTS, initDTS) {
  16978. var length = track.samples.length;
  16979. if (!length) {
  16980. return;
  16981. }
  16982. var inputTimeScale = track.inputTimeScale;
  16983. for (var index = 0; index < length; index++) {
  16984. var sample = track.samples[index];
  16985. // setting id3 pts, dts to relative time
  16986. // using this._initPTS and this._initDTS to calculate relative time
  16987. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  16988. sample.dts = normalizePts(sample.dts - initDTS.baseTime * inputTimeScale / initDTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  16989. }
  16990. var samples = track.samples;
  16991. track.samples = [];
  16992. return {
  16993. samples: samples
  16994. };
  16995. }
  16996. function flushTextTrackUserdataCueSamples(track, timeOffset, initPTS) {
  16997. var length = track.samples.length;
  16998. if (!length) {
  16999. return;
  17000. }
  17001. var inputTimeScale = track.inputTimeScale;
  17002. for (var index = 0; index < length; index++) {
  17003. var sample = track.samples[index];
  17004. // setting text pts, dts to relative time
  17005. // using this._initPTS and this._initDTS to calculate relative time
  17006. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  17007. }
  17008. track.samples.sort(function (a, b) {
  17009. return a.pts - b.pts;
  17010. });
  17011. var samples = track.samples;
  17012. track.samples = [];
  17013. return {
  17014. samples: samples
  17015. };
  17016. }
  17017. var Mp4Sample = function Mp4Sample(isKeyframe, duration, size, cts) {
  17018. this.size = void 0;
  17019. this.duration = void 0;
  17020. this.cts = void 0;
  17021. this.flags = void 0;
  17022. this.duration = duration;
  17023. this.size = size;
  17024. this.cts = cts;
  17025. this.flags = {
  17026. isLeading: 0,
  17027. isDependedOn: 0,
  17028. hasRedundancy: 0,
  17029. degradPrio: 0,
  17030. dependsOn: isKeyframe ? 2 : 1,
  17031. isNonSync: isKeyframe ? 0 : 1
  17032. };
  17033. };
  17034. var PassThroughRemuxer = /*#__PURE__*/function () {
  17035. function PassThroughRemuxer() {
  17036. this.emitInitSegment = false;
  17037. this.audioCodec = void 0;
  17038. this.videoCodec = void 0;
  17039. this.initData = void 0;
  17040. this.initPTS = null;
  17041. this.initTracks = void 0;
  17042. this.lastEndTime = null;
  17043. }
  17044. var _proto = PassThroughRemuxer.prototype;
  17045. _proto.destroy = function destroy() {};
  17046. _proto.resetTimeStamp = function resetTimeStamp(defaultInitPTS) {
  17047. this.initPTS = defaultInitPTS;
  17048. this.lastEndTime = null;
  17049. };
  17050. _proto.resetNextTimestamp = function resetNextTimestamp() {
  17051. this.lastEndTime = null;
  17052. };
  17053. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, decryptdata) {
  17054. this.audioCodec = audioCodec;
  17055. this.videoCodec = videoCodec;
  17056. this.generateInitSegment(patchEncyptionData(initSegment, decryptdata));
  17057. this.emitInitSegment = true;
  17058. };
  17059. _proto.generateInitSegment = function generateInitSegment(initSegment) {
  17060. var audioCodec = this.audioCodec,
  17061. videoCodec = this.videoCodec;
  17062. if (!(initSegment != null && initSegment.byteLength)) {
  17063. this.initTracks = undefined;
  17064. this.initData = undefined;
  17065. return;
  17066. }
  17067. var initData = this.initData = parseInitSegment(initSegment);
  17068. // Get codec from initSegment or fallback to default
  17069. if (initData.audio) {
  17070. audioCodec = getParsedTrackCodec(initData.audio, ElementaryStreamTypes.AUDIO);
  17071. }
  17072. if (initData.video) {
  17073. videoCodec = getParsedTrackCodec(initData.video, ElementaryStreamTypes.VIDEO);
  17074. }
  17075. var tracks = {};
  17076. if (initData.audio && initData.video) {
  17077. tracks.audiovideo = {
  17078. container: 'video/mp4',
  17079. codec: audioCodec + ',' + videoCodec,
  17080. initSegment: initSegment,
  17081. id: 'main'
  17082. };
  17083. } else if (initData.audio) {
  17084. tracks.audio = {
  17085. container: 'audio/mp4',
  17086. codec: audioCodec,
  17087. initSegment: initSegment,
  17088. id: 'audio'
  17089. };
  17090. } else if (initData.video) {
  17091. tracks.video = {
  17092. container: 'video/mp4',
  17093. codec: videoCodec,
  17094. initSegment: initSegment,
  17095. id: 'main'
  17096. };
  17097. } else {
  17098. logger.warn('[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes.');
  17099. }
  17100. this.initTracks = tracks;
  17101. };
  17102. _proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset) {
  17103. var _initData, _initData2;
  17104. var initPTS = this.initPTS,
  17105. lastEndTime = this.lastEndTime;
  17106. var result = {
  17107. audio: undefined,
  17108. video: undefined,
  17109. text: textTrack,
  17110. id3: id3Track,
  17111. initSegment: undefined
  17112. };
  17113. // If we haven't yet set a lastEndDTS, or it was reset, set it to the provided timeOffset. We want to use the
  17114. // lastEndDTS over timeOffset whenever possible; during progressive playback, the media source will not update
  17115. // the media duration (which is what timeOffset is provided as) before we need to process the next chunk.
  17116. if (!isFiniteNumber(lastEndTime)) {
  17117. lastEndTime = this.lastEndTime = timeOffset || 0;
  17118. }
  17119. // The binary segment data is added to the videoTrack in the mp4demuxer. We don't check to see if the data is only
  17120. // audio or video (or both); adding it to video was an arbitrary choice.
  17121. var data = videoTrack.samples;
  17122. if (!(data != null && data.length)) {
  17123. return result;
  17124. }
  17125. var initSegment = {
  17126. initPTS: undefined,
  17127. timescale: 1
  17128. };
  17129. var initData = this.initData;
  17130. if (!((_initData = initData) != null && _initData.length)) {
  17131. this.generateInitSegment(data);
  17132. initData = this.initData;
  17133. }
  17134. if (!((_initData2 = initData) != null && _initData2.length)) {
  17135. // We can't remux if the initSegment could not be generated
  17136. logger.warn('[passthrough-remuxer.ts]: Failed to generate initSegment.');
  17137. return result;
  17138. }
  17139. if (this.emitInitSegment) {
  17140. initSegment.tracks = this.initTracks;
  17141. this.emitInitSegment = false;
  17142. }
  17143. var duration = getDuration(data, initData);
  17144. var startDTS = getStartDTS(initData, data);
  17145. var decodeTime = startDTS === null ? timeOffset : startDTS;
  17146. if (isInvalidInitPts(initPTS, decodeTime, timeOffset, duration) || initSegment.timescale !== initPTS.timescale && accurateTimeOffset) {
  17147. initSegment.initPTS = decodeTime - timeOffset;
  17148. if (initPTS && initPTS.timescale === 1) {
  17149. logger.warn("Adjusting initPTS by " + (initSegment.initPTS - initPTS.baseTime));
  17150. }
  17151. this.initPTS = initPTS = {
  17152. baseTime: initSegment.initPTS,
  17153. timescale: 1
  17154. };
  17155. }
  17156. var startTime = audioTrack ? decodeTime - initPTS.baseTime / initPTS.timescale : lastEndTime;
  17157. var endTime = startTime + duration;
  17158. offsetStartDTS(initData, data, initPTS.baseTime / initPTS.timescale);
  17159. if (duration > 0) {
  17160. this.lastEndTime = endTime;
  17161. } else {
  17162. logger.warn('Duration parsed from mp4 should be greater than zero');
  17163. this.resetNextTimestamp();
  17164. }
  17165. var hasAudio = !!initData.audio;
  17166. var hasVideo = !!initData.video;
  17167. var type = '';
  17168. if (hasAudio) {
  17169. type += 'audio';
  17170. }
  17171. if (hasVideo) {
  17172. type += 'video';
  17173. }
  17174. var track = {
  17175. data1: data,
  17176. startPTS: startTime,
  17177. startDTS: startTime,
  17178. endPTS: endTime,
  17179. endDTS: endTime,
  17180. type: type,
  17181. hasAudio: hasAudio,
  17182. hasVideo: hasVideo,
  17183. nb: 1,
  17184. dropped: 0
  17185. };
  17186. result.audio = track.type === 'audio' ? track : undefined;
  17187. result.video = track.type !== 'audio' ? track : undefined;
  17188. result.initSegment = initSegment;
  17189. result.id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, initPTS, initPTS);
  17190. if (textTrack.samples.length) {
  17191. result.text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, initPTS);
  17192. }
  17193. return result;
  17194. };
  17195. return PassThroughRemuxer;
  17196. }();
  17197. function isInvalidInitPts(initPTS, startDTS, timeOffset, duration) {
  17198. if (initPTS === null) {
  17199. return true;
  17200. }
  17201. // InitPTS is invalid when distance from program would be more than segment duration or a minimum of one second
  17202. var minDuration = Math.max(duration, 1);
  17203. var startTime = startDTS - initPTS.baseTime / initPTS.timescale;
  17204. return Math.abs(startTime - timeOffset) > minDuration;
  17205. }
  17206. function getParsedTrackCodec(track, type) {
  17207. var parsedCodec = track == null ? void 0 : track.codec;
  17208. if (parsedCodec && parsedCodec.length > 4) {
  17209. return parsedCodec;
  17210. }
  17211. if (type === ElementaryStreamTypes.AUDIO) {
  17212. if (parsedCodec === 'ec-3' || parsedCodec === 'ac-3' || parsedCodec === 'alac') {
  17213. return parsedCodec;
  17214. }
  17215. if (parsedCodec === 'fLaC' || parsedCodec === 'Opus') {
  17216. // Opting not to get `preferManagedMediaSource` from player config for isSupported() check for simplicity
  17217. var preferManagedMediaSource = false;
  17218. return getCodecCompatibleName(parsedCodec, preferManagedMediaSource);
  17219. }
  17220. var result = 'mp4a.40.5';
  17221. logger.info("Parsed audio codec \"" + parsedCodec + "\" or audio object type not handled. Using \"" + result + "\"");
  17222. return result;
  17223. }
  17224. // Provide defaults based on codec type
  17225. // This allows for some playback of some fmp4 playlists without CODECS defined in manifest
  17226. logger.warn("Unhandled video codec \"" + parsedCodec + "\"");
  17227. if (parsedCodec === 'hvc1' || parsedCodec === 'hev1') {
  17228. return 'hvc1.1.6.L120.90';
  17229. }
  17230. if (parsedCodec === 'av01') {
  17231. return 'av01.0.04M.08';
  17232. }
  17233. return 'avc1.42e01e';
  17234. }
  17235. /** returns `undefined` is `self` is missing, e.g. in node */
  17236. var optionalSelf = typeof self !== 'undefined' ? self : undefined;
  17237. var now;
  17238. // performance.now() not available on WebWorker, at least on Safari Desktop
  17239. try {
  17240. now = self.performance.now.bind(self.performance);
  17241. } catch (err) {
  17242. logger.debug('Unable to use Performance API on this environment');
  17243. now = optionalSelf == null ? void 0 : optionalSelf.Date.now;
  17244. }
  17245. var muxConfig = [{
  17246. demux: MP4Demuxer,
  17247. remux: PassThroughRemuxer
  17248. }, {
  17249. demux: TSDemuxer,
  17250. remux: MP4Remuxer
  17251. }, {
  17252. demux: AACDemuxer,
  17253. remux: MP4Remuxer
  17254. }, {
  17255. demux: MP3Demuxer,
  17256. remux: MP4Remuxer
  17257. }];
  17258. var Transmuxer = /*#__PURE__*/function () {
  17259. function Transmuxer(observer, typeSupported, config, vendor, id) {
  17260. this.async = false;
  17261. this.observer = void 0;
  17262. this.typeSupported = void 0;
  17263. this.config = void 0;
  17264. this.vendor = void 0;
  17265. this.id = void 0;
  17266. this.demuxer = void 0;
  17267. this.remuxer = void 0;
  17268. this.decrypter = void 0;
  17269. this.probe = void 0;
  17270. this.decryptionPromise = null;
  17271. this.transmuxConfig = void 0;
  17272. this.currentTransmuxState = void 0;
  17273. this.observer = observer;
  17274. this.typeSupported = typeSupported;
  17275. this.config = config;
  17276. this.vendor = vendor;
  17277. this.id = id;
  17278. }
  17279. var _proto = Transmuxer.prototype;
  17280. _proto.configure = function configure(transmuxConfig) {
  17281. this.transmuxConfig = transmuxConfig;
  17282. if (this.decrypter) {
  17283. this.decrypter.reset();
  17284. }
  17285. };
  17286. _proto.push = function push(data, decryptdata, chunkMeta, state) {
  17287. var _this = this;
  17288. var stats = chunkMeta.transmuxing;
  17289. stats.executeStart = now();
  17290. var uintData = new Uint8Array(data);
  17291. var currentTransmuxState = this.currentTransmuxState,
  17292. transmuxConfig = this.transmuxConfig;
  17293. if (state) {
  17294. this.currentTransmuxState = state;
  17295. }
  17296. var _ref = state || currentTransmuxState,
  17297. contiguous = _ref.contiguous,
  17298. discontinuity = _ref.discontinuity,
  17299. trackSwitch = _ref.trackSwitch,
  17300. accurateTimeOffset = _ref.accurateTimeOffset,
  17301. timeOffset = _ref.timeOffset,
  17302. initSegmentChange = _ref.initSegmentChange;
  17303. var audioCodec = transmuxConfig.audioCodec,
  17304. videoCodec = transmuxConfig.videoCodec,
  17305. defaultInitPts = transmuxConfig.defaultInitPts,
  17306. duration = transmuxConfig.duration,
  17307. initSegmentData = transmuxConfig.initSegmentData;
  17308. var keyData = getEncryptionType(uintData, decryptdata);
  17309. if (keyData && keyData.method === 'AES-128') {
  17310. var decrypter = this.getDecrypter();
  17311. // Software decryption is synchronous; webCrypto is not
  17312. if (decrypter.isSync()) {
  17313. // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
  17314. // data is handled in the flush() call
  17315. var decryptedData = decrypter.softwareDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer);
  17316. // For Low-Latency HLS Parts, decrypt in place, since part parsing is expected on push progress
  17317. var loadingParts = chunkMeta.part > -1;
  17318. if (loadingParts) {
  17319. decryptedData = decrypter.flush();
  17320. }
  17321. if (!decryptedData) {
  17322. stats.executeEnd = now();
  17323. return emptyResult(chunkMeta);
  17324. }
  17325. uintData = new Uint8Array(decryptedData);
  17326. } else {
  17327. this.decryptionPromise = decrypter.webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer).then(function (decryptedData) {
  17328. // Calling push here is important; if flush() is called while this is still resolving, this ensures that
  17329. // the decrypted data has been transmuxed
  17330. var result = _this.push(decryptedData, null, chunkMeta);
  17331. _this.decryptionPromise = null;
  17332. return result;
  17333. });
  17334. return this.decryptionPromise;
  17335. }
  17336. }
  17337. var resetMuxers = this.needsProbing(discontinuity, trackSwitch);
  17338. if (resetMuxers) {
  17339. var error = this.configureTransmuxer(uintData);
  17340. if (error) {
  17341. logger.warn("[transmuxer] " + error.message);
  17342. this.observer.emit(Events.ERROR, Events.ERROR, {
  17343. type: ErrorTypes.MEDIA_ERROR,
  17344. details: ErrorDetails.FRAG_PARSING_ERROR,
  17345. fatal: false,
  17346. error: error,
  17347. reason: error.message
  17348. });
  17349. stats.executeEnd = now();
  17350. return emptyResult(chunkMeta);
  17351. }
  17352. }
  17353. if (discontinuity || trackSwitch || initSegmentChange || resetMuxers) {
  17354. this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration, decryptdata);
  17355. }
  17356. if (discontinuity || initSegmentChange || resetMuxers) {
  17357. this.resetInitialTimestamp(defaultInitPts);
  17358. }
  17359. if (!contiguous) {
  17360. this.resetContiguity();
  17361. }
  17362. var result = this.transmux(uintData, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  17363. var currentState = this.currentTransmuxState;
  17364. currentState.contiguous = true;
  17365. currentState.discontinuity = false;
  17366. currentState.trackSwitch = false;
  17367. stats.executeEnd = now();
  17368. return result;
  17369. }
  17370. // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type)
  17371. ;
  17372. _proto.flush = function flush(chunkMeta) {
  17373. var _this2 = this;
  17374. var stats = chunkMeta.transmuxing;
  17375. stats.executeStart = now();
  17376. var decrypter = this.decrypter,
  17377. currentTransmuxState = this.currentTransmuxState,
  17378. decryptionPromise = this.decryptionPromise;
  17379. if (decryptionPromise) {
  17380. // Upon resolution, the decryption promise calls push() and returns its TransmuxerResult up the stack. Therefore
  17381. // only flushing is required for async decryption
  17382. return decryptionPromise.then(function () {
  17383. return _this2.flush(chunkMeta);
  17384. });
  17385. }
  17386. var transmuxResults = [];
  17387. var timeOffset = currentTransmuxState.timeOffset;
  17388. if (decrypter) {
  17389. // The decrypter may have data cached, which needs to be demuxed. In this case we'll have two TransmuxResults
  17390. // This happens in the case that we receive only 1 push call for a segment (either for non-progressive downloads,
  17391. // or for progressive downloads with small segments)
  17392. var decryptedData = decrypter.flush();
  17393. if (decryptedData) {
  17394. // Push always returns a TransmuxerResult if decryptdata is null
  17395. transmuxResults.push(this.push(decryptedData, null, chunkMeta));
  17396. }
  17397. }
  17398. var demuxer = this.demuxer,
  17399. remuxer = this.remuxer;
  17400. if (!demuxer || !remuxer) {
  17401. // If probing failed, then Hls.js has been given content its not able to handle
  17402. stats.executeEnd = now();
  17403. return [emptyResult(chunkMeta)];
  17404. }
  17405. var demuxResultOrPromise = demuxer.flush(timeOffset);
  17406. if (isPromise(demuxResultOrPromise)) {
  17407. // Decrypt final SAMPLE-AES samples
  17408. return demuxResultOrPromise.then(function (demuxResult) {
  17409. _this2.flushRemux(transmuxResults, demuxResult, chunkMeta);
  17410. return transmuxResults;
  17411. });
  17412. }
  17413. this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta);
  17414. return transmuxResults;
  17415. };
  17416. _proto.flushRemux = function flushRemux(transmuxResults, demuxResult, chunkMeta) {
  17417. var audioTrack = demuxResult.audioTrack,
  17418. videoTrack = demuxResult.videoTrack,
  17419. id3Track = demuxResult.id3Track,
  17420. textTrack = demuxResult.textTrack;
  17421. var _this$currentTransmux = this.currentTransmuxState,
  17422. accurateTimeOffset = _this$currentTransmux.accurateTimeOffset,
  17423. timeOffset = _this$currentTransmux.timeOffset;
  17424. logger.log("[transmuxer.ts]: Flushed fragment " + chunkMeta.sn + (chunkMeta.part > -1 ? ' p: ' + chunkMeta.part : '') + " of level " + chunkMeta.level);
  17425. var remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, true, this.id);
  17426. transmuxResults.push({
  17427. remuxResult: remuxResult,
  17428. chunkMeta: chunkMeta
  17429. });
  17430. chunkMeta.transmuxing.executeEnd = now();
  17431. };
  17432. _proto.resetInitialTimestamp = function resetInitialTimestamp(defaultInitPts) {
  17433. var demuxer = this.demuxer,
  17434. remuxer = this.remuxer;
  17435. if (!demuxer || !remuxer) {
  17436. return;
  17437. }
  17438. demuxer.resetTimeStamp(defaultInitPts);
  17439. remuxer.resetTimeStamp(defaultInitPts);
  17440. };
  17441. _proto.resetContiguity = function resetContiguity() {
  17442. var demuxer = this.demuxer,
  17443. remuxer = this.remuxer;
  17444. if (!demuxer || !remuxer) {
  17445. return;
  17446. }
  17447. demuxer.resetContiguity();
  17448. remuxer.resetNextTimestamp();
  17449. };
  17450. _proto.resetInitSegment = function resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration, decryptdata) {
  17451. var demuxer = this.demuxer,
  17452. remuxer = this.remuxer;
  17453. if (!demuxer || !remuxer) {
  17454. return;
  17455. }
  17456. demuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration);
  17457. remuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, decryptdata);
  17458. };
  17459. _proto.destroy = function destroy() {
  17460. if (this.demuxer) {
  17461. this.demuxer.destroy();
  17462. this.demuxer = undefined;
  17463. }
  17464. if (this.remuxer) {
  17465. this.remuxer.destroy();
  17466. this.remuxer = undefined;
  17467. }
  17468. };
  17469. _proto.transmux = function transmux(data, keyData, timeOffset, accurateTimeOffset, chunkMeta) {
  17470. var result;
  17471. if (keyData && keyData.method === 'SAMPLE-AES') {
  17472. result = this.transmuxSampleAes(data, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  17473. } else {
  17474. result = this.transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta);
  17475. }
  17476. return result;
  17477. };
  17478. _proto.transmuxUnencrypted = function transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta) {
  17479. var _demux = this.demuxer.demux(data, timeOffset, false, !this.config.progressive),
  17480. audioTrack = _demux.audioTrack,
  17481. videoTrack = _demux.videoTrack,
  17482. id3Track = _demux.id3Track,
  17483. textTrack = _demux.textTrack;
  17484. var remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, false, this.id);
  17485. return {
  17486. remuxResult: remuxResult,
  17487. chunkMeta: chunkMeta
  17488. };
  17489. };
  17490. _proto.transmuxSampleAes = function transmuxSampleAes(data, decryptData, timeOffset, accurateTimeOffset, chunkMeta) {
  17491. var _this3 = this;
  17492. return this.demuxer.demuxSampleAes(data, decryptData, timeOffset).then(function (demuxResult) {
  17493. var remuxResult = _this3.remuxer.remux(demuxResult.audioTrack, demuxResult.videoTrack, demuxResult.id3Track, demuxResult.textTrack, timeOffset, accurateTimeOffset, false, _this3.id);
  17494. return {
  17495. remuxResult: remuxResult,
  17496. chunkMeta: chunkMeta
  17497. };
  17498. });
  17499. };
  17500. _proto.configureTransmuxer = function configureTransmuxer(data) {
  17501. var config = this.config,
  17502. observer = this.observer,
  17503. typeSupported = this.typeSupported,
  17504. vendor = this.vendor;
  17505. // probe for content type
  17506. var mux;
  17507. for (var i = 0, len = muxConfig.length; i < len; i++) {
  17508. var _muxConfig$i$demux;
  17509. if ((_muxConfig$i$demux = muxConfig[i].demux) != null && _muxConfig$i$demux.probe(data)) {
  17510. mux = muxConfig[i];
  17511. break;
  17512. }
  17513. }
  17514. if (!mux) {
  17515. return new Error('Failed to find demuxer by probing fragment data');
  17516. }
  17517. // so let's check that current remuxer and demuxer are still valid
  17518. var demuxer = this.demuxer;
  17519. var remuxer = this.remuxer;
  17520. var Remuxer = mux.remux;
  17521. var Demuxer = mux.demux;
  17522. if (!remuxer || !(remuxer instanceof Remuxer)) {
  17523. this.remuxer = new Remuxer(observer, config, typeSupported, vendor);
  17524. }
  17525. if (!demuxer || !(demuxer instanceof Demuxer)) {
  17526. this.demuxer = new Demuxer(observer, config, typeSupported);
  17527. this.probe = Demuxer.probe;
  17528. }
  17529. };
  17530. _proto.needsProbing = function needsProbing(discontinuity, trackSwitch) {
  17531. // in case of continuity change, or track switch
  17532. // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)
  17533. return !this.demuxer || !this.remuxer || discontinuity || trackSwitch;
  17534. };
  17535. _proto.getDecrypter = function getDecrypter() {
  17536. var decrypter = this.decrypter;
  17537. if (!decrypter) {
  17538. decrypter = this.decrypter = new Decrypter(this.config);
  17539. }
  17540. return decrypter;
  17541. };
  17542. return Transmuxer;
  17543. }();
  17544. function getEncryptionType(data, decryptData) {
  17545. var encryptionType = null;
  17546. if (data.byteLength > 0 && (decryptData == null ? void 0 : decryptData.key) != null && decryptData.iv !== null && decryptData.method != null) {
  17547. encryptionType = decryptData;
  17548. }
  17549. return encryptionType;
  17550. }
  17551. var emptyResult = function emptyResult(chunkMeta) {
  17552. return {
  17553. remuxResult: {},
  17554. chunkMeta: chunkMeta
  17555. };
  17556. };
  17557. function isPromise(p) {
  17558. return 'then' in p && p.then instanceof Function;
  17559. }
  17560. var TransmuxConfig = function TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPts) {
  17561. this.audioCodec = void 0;
  17562. this.videoCodec = void 0;
  17563. this.initSegmentData = void 0;
  17564. this.duration = void 0;
  17565. this.defaultInitPts = void 0;
  17566. this.audioCodec = audioCodec;
  17567. this.videoCodec = videoCodec;
  17568. this.initSegmentData = initSegmentData;
  17569. this.duration = duration;
  17570. this.defaultInitPts = defaultInitPts || null;
  17571. };
  17572. var TransmuxState = function TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange) {
  17573. this.discontinuity = void 0;
  17574. this.contiguous = void 0;
  17575. this.accurateTimeOffset = void 0;
  17576. this.trackSwitch = void 0;
  17577. this.timeOffset = void 0;
  17578. this.initSegmentChange = void 0;
  17579. this.discontinuity = discontinuity;
  17580. this.contiguous = contiguous;
  17581. this.accurateTimeOffset = accurateTimeOffset;
  17582. this.trackSwitch = trackSwitch;
  17583. this.timeOffset = timeOffset;
  17584. this.initSegmentChange = initSegmentChange;
  17585. };
  17586. var eventemitter3 = {exports: {}};
  17587. (function (module) {
  17588. var has = Object.prototype.hasOwnProperty
  17589. , prefix = '~';
  17590. /**
  17591. * Constructor to create a storage for our `EE` objects.
  17592. * An `Events` instance is a plain object whose properties are event names.
  17593. *
  17594. * @constructor
  17595. * @private
  17596. */
  17597. function Events() {}
  17598. //
  17599. // We try to not inherit from `Object.prototype`. In some engines creating an
  17600. // instance in this way is faster than calling `Object.create(null)` directly.
  17601. // If `Object.create(null)` is not supported we prefix the event names with a
  17602. // character to make sure that the built-in object properties are not
  17603. // overridden or used as an attack vector.
  17604. //
  17605. if (Object.create) {
  17606. Events.prototype = Object.create(null);
  17607. //
  17608. // This hack is needed because the `__proto__` property is still inherited in
  17609. // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  17610. //
  17611. if (!new Events().__proto__) prefix = false;
  17612. }
  17613. /**
  17614. * Representation of a single event listener.
  17615. *
  17616. * @param {Function} fn The listener function.
  17617. * @param {*} context The context to invoke the listener with.
  17618. * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
  17619. * @constructor
  17620. * @private
  17621. */
  17622. function EE(fn, context, once) {
  17623. this.fn = fn;
  17624. this.context = context;
  17625. this.once = once || false;
  17626. }
  17627. /**
  17628. * Add a listener for a given event.
  17629. *
  17630. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  17631. * @param {(String|Symbol)} event The event name.
  17632. * @param {Function} fn The listener function.
  17633. * @param {*} context The context to invoke the listener with.
  17634. * @param {Boolean} once Specify if the listener is a one-time listener.
  17635. * @returns {EventEmitter}
  17636. * @private
  17637. */
  17638. function addListener(emitter, event, fn, context, once) {
  17639. if (typeof fn !== 'function') {
  17640. throw new TypeError('The listener must be a function');
  17641. }
  17642. var listener = new EE(fn, context || emitter, once)
  17643. , evt = prefix ? prefix + event : event;
  17644. if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
  17645. else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
  17646. else emitter._events[evt] = [emitter._events[evt], listener];
  17647. return emitter;
  17648. }
  17649. /**
  17650. * Clear event by name.
  17651. *
  17652. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  17653. * @param {(String|Symbol)} evt The Event name.
  17654. * @private
  17655. */
  17656. function clearEvent(emitter, evt) {
  17657. if (--emitter._eventsCount === 0) emitter._events = new Events();
  17658. else delete emitter._events[evt];
  17659. }
  17660. /**
  17661. * Minimal `EventEmitter` interface that is molded against the Node.js
  17662. * `EventEmitter` interface.
  17663. *
  17664. * @constructor
  17665. * @public
  17666. */
  17667. function EventEmitter() {
  17668. this._events = new Events();
  17669. this._eventsCount = 0;
  17670. }
  17671. /**
  17672. * Return an array listing the events for which the emitter has registered
  17673. * listeners.
  17674. *
  17675. * @returns {Array}
  17676. * @public
  17677. */
  17678. EventEmitter.prototype.eventNames = function eventNames() {
  17679. var names = []
  17680. , events
  17681. , name;
  17682. if (this._eventsCount === 0) return names;
  17683. for (name in (events = this._events)) {
  17684. if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
  17685. }
  17686. if (Object.getOwnPropertySymbols) {
  17687. return names.concat(Object.getOwnPropertySymbols(events));
  17688. }
  17689. return names;
  17690. };
  17691. /**
  17692. * Return the listeners registered for a given event.
  17693. *
  17694. * @param {(String|Symbol)} event The event name.
  17695. * @returns {Array} The registered listeners.
  17696. * @public
  17697. */
  17698. EventEmitter.prototype.listeners = function listeners(event) {
  17699. var evt = prefix ? prefix + event : event
  17700. , handlers = this._events[evt];
  17701. if (!handlers) return [];
  17702. if (handlers.fn) return [handlers.fn];
  17703. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  17704. ee[i] = handlers[i].fn;
  17705. }
  17706. return ee;
  17707. };
  17708. /**
  17709. * Return the number of listeners listening to a given event.
  17710. *
  17711. * @param {(String|Symbol)} event The event name.
  17712. * @returns {Number} The number of listeners.
  17713. * @public
  17714. */
  17715. EventEmitter.prototype.listenerCount = function listenerCount(event) {
  17716. var evt = prefix ? prefix + event : event
  17717. , listeners = this._events[evt];
  17718. if (!listeners) return 0;
  17719. if (listeners.fn) return 1;
  17720. return listeners.length;
  17721. };
  17722. /**
  17723. * Calls each of the listeners registered for a given event.
  17724. *
  17725. * @param {(String|Symbol)} event The event name.
  17726. * @returns {Boolean} `true` if the event had listeners, else `false`.
  17727. * @public
  17728. */
  17729. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  17730. var evt = prefix ? prefix + event : event;
  17731. if (!this._events[evt]) return false;
  17732. var listeners = this._events[evt]
  17733. , len = arguments.length
  17734. , args
  17735. , i;
  17736. if (listeners.fn) {
  17737. if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  17738. switch (len) {
  17739. case 1: return listeners.fn.call(listeners.context), true;
  17740. case 2: return listeners.fn.call(listeners.context, a1), true;
  17741. case 3: return listeners.fn.call(listeners.context, a1, a2), true;
  17742. case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
  17743. case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  17744. case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  17745. }
  17746. for (i = 1, args = new Array(len -1); i < len; i++) {
  17747. args[i - 1] = arguments[i];
  17748. }
  17749. listeners.fn.apply(listeners.context, args);
  17750. } else {
  17751. var length = listeners.length
  17752. , j;
  17753. for (i = 0; i < length; i++) {
  17754. if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  17755. switch (len) {
  17756. case 1: listeners[i].fn.call(listeners[i].context); break;
  17757. case 2: listeners[i].fn.call(listeners[i].context, a1); break;
  17758. case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
  17759. case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
  17760. default:
  17761. if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
  17762. args[j - 1] = arguments[j];
  17763. }
  17764. listeners[i].fn.apply(listeners[i].context, args);
  17765. }
  17766. }
  17767. }
  17768. return true;
  17769. };
  17770. /**
  17771. * Add a listener for a given event.
  17772. *
  17773. * @param {(String|Symbol)} event The event name.
  17774. * @param {Function} fn The listener function.
  17775. * @param {*} [context=this] The context to invoke the listener with.
  17776. * @returns {EventEmitter} `this`.
  17777. * @public
  17778. */
  17779. EventEmitter.prototype.on = function on(event, fn, context) {
  17780. return addListener(this, event, fn, context, false);
  17781. };
  17782. /**
  17783. * Add a one-time listener for a given event.
  17784. *
  17785. * @param {(String|Symbol)} event The event name.
  17786. * @param {Function} fn The listener function.
  17787. * @param {*} [context=this] The context to invoke the listener with.
  17788. * @returns {EventEmitter} `this`.
  17789. * @public
  17790. */
  17791. EventEmitter.prototype.once = function once(event, fn, context) {
  17792. return addListener(this, event, fn, context, true);
  17793. };
  17794. /**
  17795. * Remove the listeners of a given event.
  17796. *
  17797. * @param {(String|Symbol)} event The event name.
  17798. * @param {Function} fn Only remove the listeners that match this function.
  17799. * @param {*} context Only remove the listeners that have this context.
  17800. * @param {Boolean} once Only remove one-time listeners.
  17801. * @returns {EventEmitter} `this`.
  17802. * @public
  17803. */
  17804. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  17805. var evt = prefix ? prefix + event : event;
  17806. if (!this._events[evt]) return this;
  17807. if (!fn) {
  17808. clearEvent(this, evt);
  17809. return this;
  17810. }
  17811. var listeners = this._events[evt];
  17812. if (listeners.fn) {
  17813. if (
  17814. listeners.fn === fn &&
  17815. (!once || listeners.once) &&
  17816. (!context || listeners.context === context)
  17817. ) {
  17818. clearEvent(this, evt);
  17819. }
  17820. } else {
  17821. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  17822. if (
  17823. listeners[i].fn !== fn ||
  17824. (once && !listeners[i].once) ||
  17825. (context && listeners[i].context !== context)
  17826. ) {
  17827. events.push(listeners[i]);
  17828. }
  17829. }
  17830. //
  17831. // Reset the array, or remove it completely if we have no more listeners.
  17832. //
  17833. if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
  17834. else clearEvent(this, evt);
  17835. }
  17836. return this;
  17837. };
  17838. /**
  17839. * Remove all listeners, or those of the specified event.
  17840. *
  17841. * @param {(String|Symbol)} [event] The event name.
  17842. * @returns {EventEmitter} `this`.
  17843. * @public
  17844. */
  17845. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  17846. var evt;
  17847. if (event) {
  17848. evt = prefix ? prefix + event : event;
  17849. if (this._events[evt]) clearEvent(this, evt);
  17850. } else {
  17851. this._events = new Events();
  17852. this._eventsCount = 0;
  17853. }
  17854. return this;
  17855. };
  17856. //
  17857. // Alias methods names because people roll like that.
  17858. //
  17859. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  17860. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  17861. //
  17862. // Expose the prefix.
  17863. //
  17864. EventEmitter.prefixed = prefix;
  17865. //
  17866. // Allow `EventEmitter` to be imported as module namespace.
  17867. //
  17868. EventEmitter.EventEmitter = EventEmitter;
  17869. //
  17870. // Expose the module.
  17871. //
  17872. {
  17873. module.exports = EventEmitter;
  17874. }
  17875. } (eventemitter3));
  17876. var eventemitter3Exports = eventemitter3.exports;
  17877. var EventEmitter = /*@__PURE__*/getDefaultExportFromCjs(eventemitter3Exports);
  17878. if (typeof __IN_WORKER__ !== 'undefined' && __IN_WORKER__) {
  17879. startWorker(self);
  17880. }
  17881. function startWorker(self) {
  17882. var observer = new EventEmitter();
  17883. var forwardMessage = function forwardMessage(ev, data) {
  17884. self.postMessage({
  17885. event: ev,
  17886. data: data
  17887. });
  17888. };
  17889. // forward events to main thread
  17890. observer.on(Events.FRAG_DECRYPTED, forwardMessage);
  17891. observer.on(Events.ERROR, forwardMessage);
  17892. // forward logger events to main thread
  17893. var forwardWorkerLogs = function forwardWorkerLogs() {
  17894. var _loop = function _loop(logFn) {
  17895. var func = function func(message) {
  17896. forwardMessage('workerLog', {
  17897. logType: logFn,
  17898. message: message
  17899. });
  17900. };
  17901. logger[logFn] = func;
  17902. };
  17903. for (var logFn in logger) {
  17904. _loop(logFn);
  17905. }
  17906. };
  17907. self.addEventListener('message', function (ev) {
  17908. var data = ev.data;
  17909. switch (data.cmd) {
  17910. case 'init':
  17911. {
  17912. var config = JSON.parse(data.config);
  17913. self.transmuxer = new Transmuxer(observer, data.typeSupported, config, '', data.id);
  17914. enableLogs(config.debug, data.id);
  17915. forwardWorkerLogs();
  17916. forwardMessage('init', null);
  17917. break;
  17918. }
  17919. case 'configure':
  17920. {
  17921. self.transmuxer.configure(data.config);
  17922. break;
  17923. }
  17924. case 'demux':
  17925. {
  17926. var transmuxResult = self.transmuxer.push(data.data, data.decryptdata, data.chunkMeta, data.state);
  17927. if (isPromise(transmuxResult)) {
  17928. self.transmuxer.async = true;
  17929. transmuxResult.then(function (data) {
  17930. emitTransmuxComplete(self, data);
  17931. }).catch(function (error) {
  17932. forwardMessage(Events.ERROR, {
  17933. type: ErrorTypes.MEDIA_ERROR,
  17934. details: ErrorDetails.FRAG_PARSING_ERROR,
  17935. chunkMeta: data.chunkMeta,
  17936. fatal: false,
  17937. error: error,
  17938. err: error,
  17939. reason: "transmuxer-worker push error"
  17940. });
  17941. });
  17942. } else {
  17943. self.transmuxer.async = false;
  17944. emitTransmuxComplete(self, transmuxResult);
  17945. }
  17946. break;
  17947. }
  17948. case 'flush':
  17949. {
  17950. var id = data.chunkMeta;
  17951. var _transmuxResult = self.transmuxer.flush(id);
  17952. var asyncFlush = isPromise(_transmuxResult);
  17953. if (asyncFlush || self.transmuxer.async) {
  17954. if (!isPromise(_transmuxResult)) {
  17955. _transmuxResult = Promise.resolve(_transmuxResult);
  17956. }
  17957. _transmuxResult.then(function (results) {
  17958. handleFlushResult(self, results, id);
  17959. }).catch(function (error) {
  17960. forwardMessage(Events.ERROR, {
  17961. type: ErrorTypes.MEDIA_ERROR,
  17962. details: ErrorDetails.FRAG_PARSING_ERROR,
  17963. chunkMeta: data.chunkMeta,
  17964. fatal: false,
  17965. error: error,
  17966. err: error,
  17967. reason: "transmuxer-worker flush error"
  17968. });
  17969. });
  17970. } else {
  17971. handleFlushResult(self, _transmuxResult, id);
  17972. }
  17973. break;
  17974. }
  17975. }
  17976. });
  17977. }
  17978. function emitTransmuxComplete(self, transmuxResult) {
  17979. if (isEmptyResult(transmuxResult.remuxResult)) {
  17980. return false;
  17981. }
  17982. var transferable = [];
  17983. var _transmuxResult$remux = transmuxResult.remuxResult,
  17984. audio = _transmuxResult$remux.audio,
  17985. video = _transmuxResult$remux.video;
  17986. if (audio) {
  17987. addToTransferable(transferable, audio);
  17988. }
  17989. if (video) {
  17990. addToTransferable(transferable, video);
  17991. }
  17992. self.postMessage({
  17993. event: 'transmuxComplete',
  17994. data: transmuxResult
  17995. }, transferable);
  17996. return true;
  17997. }
  17998. // Converts data to a transferable object https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast)
  17999. // in order to minimize message passing overhead
  18000. function addToTransferable(transferable, track) {
  18001. if (track.data1) {
  18002. transferable.push(track.data1.buffer);
  18003. }
  18004. if (track.data2) {
  18005. transferable.push(track.data2.buffer);
  18006. }
  18007. }
  18008. function handleFlushResult(self, results, chunkMeta) {
  18009. var parsed = results.reduce(function (parsed, result) {
  18010. return emitTransmuxComplete(self, result) || parsed;
  18011. }, false);
  18012. if (!parsed) {
  18013. // Emit at least one "transmuxComplete" message even if media is not found to update stream-controller state to PARSING
  18014. self.postMessage({
  18015. event: 'transmuxComplete',
  18016. data: results[0]
  18017. });
  18018. }
  18019. self.postMessage({
  18020. event: 'flush',
  18021. data: chunkMeta
  18022. });
  18023. }
  18024. function isEmptyResult(remuxResult) {
  18025. return !remuxResult.audio && !remuxResult.video && !remuxResult.text && !remuxResult.id3 && !remuxResult.initSegment;
  18026. }
  18027. // ensure the worker ends up in the bundle
  18028. // If the worker should not be included this gets aliased to empty.js
  18029. function hasUMDWorker() {
  18030. return typeof __HLS_WORKER_BUNDLE__ === 'function';
  18031. }
  18032. function injectWorker() {
  18033. var blob = new self.Blob(["var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(" + __HLS_WORKER_BUNDLE__.toString() + ")(true);"], {
  18034. type: 'text/javascript'
  18035. });
  18036. var objectURL = self.URL.createObjectURL(blob);
  18037. var worker = new self.Worker(objectURL);
  18038. return {
  18039. worker: worker,
  18040. objectURL: objectURL
  18041. };
  18042. }
  18043. function loadWorker(path) {
  18044. var scriptURL = new self.URL(path, self.location.href).href;
  18045. var worker = new self.Worker(scriptURL);
  18046. return {
  18047. worker: worker,
  18048. scriptURL: scriptURL
  18049. };
  18050. }
  18051. var TransmuxerInterface = /*#__PURE__*/function () {
  18052. function TransmuxerInterface(hls, id, onTransmuxComplete, onFlush) {
  18053. var _this = this;
  18054. this.error = null;
  18055. this.hls = void 0;
  18056. this.id = void 0;
  18057. this.observer = void 0;
  18058. this.frag = null;
  18059. this.part = null;
  18060. this.useWorker = void 0;
  18061. this.workerContext = null;
  18062. this.onwmsg = void 0;
  18063. this.transmuxer = null;
  18064. this.onTransmuxComplete = void 0;
  18065. this.onFlush = void 0;
  18066. var config = hls.config;
  18067. this.hls = hls;
  18068. this.id = id;
  18069. this.useWorker = !!config.enableWorker;
  18070. this.onTransmuxComplete = onTransmuxComplete;
  18071. this.onFlush = onFlush;
  18072. var forwardMessage = function forwardMessage(ev, data) {
  18073. data = data || {};
  18074. data.frag = _this.frag;
  18075. data.id = _this.id;
  18076. if (ev === Events.ERROR) {
  18077. _this.error = data.error;
  18078. }
  18079. _this.hls.trigger(ev, data);
  18080. };
  18081. // forward events to main thread
  18082. this.observer = new EventEmitter();
  18083. this.observer.on(Events.FRAG_DECRYPTED, forwardMessage);
  18084. this.observer.on(Events.ERROR, forwardMessage);
  18085. var MediaSource = getMediaSource(config.preferManagedMediaSource) || {
  18086. isTypeSupported: function isTypeSupported() {
  18087. return false;
  18088. }
  18089. };
  18090. var m2tsTypeSupported = {
  18091. mpeg: MediaSource.isTypeSupported('audio/mpeg'),
  18092. mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"'),
  18093. ac3: false
  18094. };
  18095. if (this.useWorker && typeof Worker !== 'undefined') {
  18096. var canCreateWorker = config.workerPath || hasUMDWorker();
  18097. if (canCreateWorker) {
  18098. try {
  18099. if (config.workerPath) {
  18100. logger.log("loading Web Worker " + config.workerPath + " for \"" + id + "\"");
  18101. this.workerContext = loadWorker(config.workerPath);
  18102. } else {
  18103. logger.log("injecting Web Worker for \"" + id + "\"");
  18104. this.workerContext = injectWorker();
  18105. }
  18106. this.onwmsg = function (event) {
  18107. return _this.onWorkerMessage(event);
  18108. };
  18109. var worker = this.workerContext.worker;
  18110. worker.addEventListener('message', this.onwmsg);
  18111. worker.onerror = function (event) {
  18112. var error = new Error(event.message + " (" + event.filename + ":" + event.lineno + ")");
  18113. config.enableWorker = false;
  18114. logger.warn("Error in \"" + id + "\" Web Worker, fallback to inline");
  18115. _this.hls.trigger(Events.ERROR, {
  18116. type: ErrorTypes.OTHER_ERROR,
  18117. details: ErrorDetails.INTERNAL_EXCEPTION,
  18118. fatal: false,
  18119. event: 'demuxerWorker',
  18120. error: error
  18121. });
  18122. };
  18123. worker.postMessage({
  18124. cmd: 'init',
  18125. typeSupported: m2tsTypeSupported,
  18126. vendor: '',
  18127. id: id,
  18128. config: JSON.stringify(config)
  18129. });
  18130. } catch (err) {
  18131. logger.warn("Error setting up \"" + id + "\" Web Worker, fallback to inline", err);
  18132. this.resetWorker();
  18133. this.error = null;
  18134. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, '', id);
  18135. }
  18136. return;
  18137. }
  18138. }
  18139. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, '', id);
  18140. }
  18141. var _proto = TransmuxerInterface.prototype;
  18142. _proto.resetWorker = function resetWorker() {
  18143. if (this.workerContext) {
  18144. var _this$workerContext = this.workerContext,
  18145. worker = _this$workerContext.worker,
  18146. objectURL = _this$workerContext.objectURL;
  18147. if (objectURL) {
  18148. // revoke the Object URL that was used to create transmuxer worker, so as not to leak it
  18149. self.URL.revokeObjectURL(objectURL);
  18150. }
  18151. worker.removeEventListener('message', this.onwmsg);
  18152. worker.onerror = null;
  18153. worker.terminate();
  18154. this.workerContext = null;
  18155. }
  18156. };
  18157. _proto.destroy = function destroy() {
  18158. if (this.workerContext) {
  18159. this.resetWorker();
  18160. this.onwmsg = undefined;
  18161. } else {
  18162. var transmuxer = this.transmuxer;
  18163. if (transmuxer) {
  18164. transmuxer.destroy();
  18165. this.transmuxer = null;
  18166. }
  18167. }
  18168. var observer = this.observer;
  18169. if (observer) {
  18170. observer.removeAllListeners();
  18171. }
  18172. this.frag = null;
  18173. // @ts-ignore
  18174. this.observer = null;
  18175. // @ts-ignore
  18176. this.hls = null;
  18177. };
  18178. _proto.push = function push(data, initSegmentData, audioCodec, videoCodec, frag, part, duration, accurateTimeOffset, chunkMeta, defaultInitPTS) {
  18179. var _frag$initSegment,
  18180. _lastFrag$initSegment,
  18181. _this2 = this;
  18182. chunkMeta.transmuxing.start = self.performance.now();
  18183. var transmuxer = this.transmuxer;
  18184. var timeOffset = part ? part.start : frag.start;
  18185. // TODO: push "clear-lead" decrypt data for unencrypted fragments in streams with encrypted ones
  18186. var decryptdata = frag.decryptdata;
  18187. var lastFrag = this.frag;
  18188. var discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
  18189. var trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level);
  18190. var snDiff = lastFrag ? chunkMeta.sn - lastFrag.sn : -1;
  18191. var partDiff = this.part ? chunkMeta.part - this.part.index : -1;
  18192. var progressive = snDiff === 0 && chunkMeta.id > 1 && chunkMeta.id === (lastFrag == null ? void 0 : lastFrag.stats.chunkCount);
  18193. var contiguous = !trackSwitch && (snDiff === 1 || snDiff === 0 && (partDiff === 1 || progressive && partDiff <= 0));
  18194. var now = self.performance.now();
  18195. if (trackSwitch || snDiff || frag.stats.parsing.start === 0) {
  18196. frag.stats.parsing.start = now;
  18197. }
  18198. if (part && (partDiff || !contiguous)) {
  18199. part.stats.parsing.start = now;
  18200. }
  18201. var initSegmentChange = !(lastFrag && ((_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.url) === ((_lastFrag$initSegment = lastFrag.initSegment) == null ? void 0 : _lastFrag$initSegment.url));
  18202. var state = new TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange);
  18203. if (!contiguous || discontinuity || initSegmentChange) {
  18204. 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);
  18205. var config = new TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPTS);
  18206. this.configureTransmuxer(config);
  18207. }
  18208. this.frag = frag;
  18209. this.part = part;
  18210. // Frags with sn of 'initSegment' are not transmuxed
  18211. if (this.workerContext) {
  18212. // post fragment payload as transferable objects for ArrayBuffer (no copy)
  18213. this.workerContext.worker.postMessage({
  18214. cmd: 'demux',
  18215. data: data,
  18216. decryptdata: decryptdata,
  18217. chunkMeta: chunkMeta,
  18218. state: state
  18219. }, data instanceof ArrayBuffer ? [data] : []);
  18220. } else if (transmuxer) {
  18221. var _transmuxResult = transmuxer.push(data, decryptdata, chunkMeta, state);
  18222. if (isPromise(_transmuxResult)) {
  18223. transmuxer.async = true;
  18224. _transmuxResult.then(function (data) {
  18225. _this2.handleTransmuxComplete(data);
  18226. }).catch(function (error) {
  18227. _this2.transmuxerError(error, chunkMeta, 'transmuxer-interface push error');
  18228. });
  18229. } else {
  18230. transmuxer.async = false;
  18231. this.handleTransmuxComplete(_transmuxResult);
  18232. }
  18233. }
  18234. };
  18235. _proto.flush = function flush(chunkMeta) {
  18236. var _this3 = this;
  18237. chunkMeta.transmuxing.start = self.performance.now();
  18238. var transmuxer = this.transmuxer;
  18239. if (this.workerContext) {
  18240. this.workerContext.worker.postMessage({
  18241. cmd: 'flush',
  18242. chunkMeta: chunkMeta
  18243. });
  18244. } else if (transmuxer) {
  18245. var _transmuxResult2 = transmuxer.flush(chunkMeta);
  18246. var asyncFlush = isPromise(_transmuxResult2);
  18247. if (asyncFlush || transmuxer.async) {
  18248. if (!isPromise(_transmuxResult2)) {
  18249. _transmuxResult2 = Promise.resolve(_transmuxResult2);
  18250. }
  18251. _transmuxResult2.then(function (data) {
  18252. _this3.handleFlushResult(data, chunkMeta);
  18253. }).catch(function (error) {
  18254. _this3.transmuxerError(error, chunkMeta, 'transmuxer-interface flush error');
  18255. });
  18256. } else {
  18257. this.handleFlushResult(_transmuxResult2, chunkMeta);
  18258. }
  18259. }
  18260. };
  18261. _proto.transmuxerError = function transmuxerError(error, chunkMeta, reason) {
  18262. if (!this.hls) {
  18263. return;
  18264. }
  18265. this.error = error;
  18266. this.hls.trigger(Events.ERROR, {
  18267. type: ErrorTypes.MEDIA_ERROR,
  18268. details: ErrorDetails.FRAG_PARSING_ERROR,
  18269. chunkMeta: chunkMeta,
  18270. frag: this.frag || undefined,
  18271. fatal: false,
  18272. error: error,
  18273. err: error,
  18274. reason: reason
  18275. });
  18276. };
  18277. _proto.handleFlushResult = function handleFlushResult(results, chunkMeta) {
  18278. var _this4 = this;
  18279. results.forEach(function (result) {
  18280. _this4.handleTransmuxComplete(result);
  18281. });
  18282. this.onFlush(chunkMeta);
  18283. };
  18284. _proto.onWorkerMessage = function onWorkerMessage(event) {
  18285. var data = event.data;
  18286. if (!(data != null && data.event)) {
  18287. logger.warn("worker message received with no " + (data ? 'event name' : 'data'));
  18288. return;
  18289. }
  18290. var hls = this.hls;
  18291. if (!this.hls) {
  18292. return;
  18293. }
  18294. switch (data.event) {
  18295. case 'init':
  18296. {
  18297. var _this$workerContext2;
  18298. var objectURL = (_this$workerContext2 = this.workerContext) == null ? void 0 : _this$workerContext2.objectURL;
  18299. if (objectURL) {
  18300. // revoke the Object URL that was used to create transmuxer worker, so as not to leak it
  18301. self.URL.revokeObjectURL(objectURL);
  18302. }
  18303. break;
  18304. }
  18305. case 'transmuxComplete':
  18306. {
  18307. this.handleTransmuxComplete(data.data);
  18308. break;
  18309. }
  18310. case 'flush':
  18311. {
  18312. this.onFlush(data.data);
  18313. break;
  18314. }
  18315. // pass logs from the worker thread to the main logger
  18316. case 'workerLog':
  18317. if (logger[data.data.logType]) {
  18318. logger[data.data.logType](data.data.message);
  18319. }
  18320. break;
  18321. default:
  18322. {
  18323. data.data = data.data || {};
  18324. data.data.frag = this.frag;
  18325. data.data.id = this.id;
  18326. hls.trigger(data.event, data.data);
  18327. break;
  18328. }
  18329. }
  18330. };
  18331. _proto.configureTransmuxer = function configureTransmuxer(config) {
  18332. var transmuxer = this.transmuxer;
  18333. if (this.workerContext) {
  18334. this.workerContext.worker.postMessage({
  18335. cmd: 'configure',
  18336. config: config
  18337. });
  18338. } else if (transmuxer) {
  18339. transmuxer.configure(config);
  18340. }
  18341. };
  18342. _proto.handleTransmuxComplete = function handleTransmuxComplete(result) {
  18343. result.chunkMeta.transmuxing.end = self.performance.now();
  18344. this.onTransmuxComplete(result);
  18345. };
  18346. return TransmuxerInterface;
  18347. }();
  18348. var STALL_MINIMUM_DURATION_MS = 250;
  18349. var MAX_START_GAP_JUMP = 2.0;
  18350. var SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;
  18351. var SKIP_BUFFER_RANGE_START = 0.05;
  18352. var GapController = /*#__PURE__*/function () {
  18353. function GapController(config, media, fragmentTracker, hls) {
  18354. this.config = void 0;
  18355. this.media = null;
  18356. this.fragmentTracker = void 0;
  18357. this.hls = void 0;
  18358. this.nudgeRetry = 0;
  18359. this.stallReported = false;
  18360. this.stalled = null;
  18361. this.moved = false;
  18362. this.seeking = false;
  18363. this.config = config;
  18364. this.media = media;
  18365. this.fragmentTracker = fragmentTracker;
  18366. this.hls = hls;
  18367. }
  18368. var _proto = GapController.prototype;
  18369. _proto.destroy = function destroy() {
  18370. this.media = null;
  18371. // @ts-ignore
  18372. this.hls = this.fragmentTracker = null;
  18373. }
  18374. /**
  18375. * Checks if the playhead is stuck within a gap, and if so, attempts to free it.
  18376. * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).
  18377. *
  18378. * @param lastCurrentTime - Previously read playhead position
  18379. */;
  18380. _proto.poll = function poll(lastCurrentTime, activeFrag) {
  18381. var config = this.config,
  18382. media = this.media,
  18383. stalled = this.stalled;
  18384. if (media === null) {
  18385. return;
  18386. }
  18387. var currentTime = media.currentTime,
  18388. seeking = media.seeking;
  18389. var seeked = this.seeking && !seeking;
  18390. var beginSeek = !this.seeking && seeking;
  18391. this.seeking = seeking;
  18392. // The playhead is moving, no-op
  18393. if (currentTime !== lastCurrentTime) {
  18394. this.moved = true;
  18395. if (!seeking) {
  18396. this.nudgeRetry = 0;
  18397. }
  18398. if (stalled !== null) {
  18399. // The playhead is now moving, but was previously stalled
  18400. if (this.stallReported) {
  18401. var _stalledDuration = self.performance.now() - stalled;
  18402. logger.warn("playback not stuck anymore @" + currentTime + ", after " + Math.round(_stalledDuration) + "ms");
  18403. this.stallReported = false;
  18404. }
  18405. this.stalled = null;
  18406. }
  18407. return;
  18408. }
  18409. // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek
  18410. if (beginSeek || seeked) {
  18411. this.stalled = null;
  18412. return;
  18413. }
  18414. // The playhead should not be moving
  18415. if (media.paused && !seeking || media.ended || media.playbackRate === 0 || !BufferHelper.getBuffered(media).length) {
  18416. this.nudgeRetry = 0;
  18417. return;
  18418. }
  18419. var bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  18420. var nextStart = bufferInfo.nextStart || 0;
  18421. if (seeking) {
  18422. // Waiting for seeking in a buffered range to complete
  18423. var hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP;
  18424. // Next buffered range is too far ahead to jump to while still seeking
  18425. var noBufferGap = !nextStart || activeFrag && activeFrag.start <= currentTime || nextStart - currentTime > MAX_START_GAP_JUMP && !this.fragmentTracker.getPartialFragment(currentTime);
  18426. if (hasEnoughBuffer || noBufferGap) {
  18427. return;
  18428. }
  18429. // Reset moved state when seeking to a point in or before a gap
  18430. this.moved = false;
  18431. }
  18432. // Skip start gaps if we haven't played, but the last poll detected the start of a stall
  18433. // The addition poll gives the browser a chance to jump the gap for us
  18434. if (!this.moved && this.stalled !== null) {
  18435. var _level$details;
  18436. // There is no playable buffer (seeked, waiting for buffer)
  18437. var isBuffered = bufferInfo.len > 0;
  18438. if (!isBuffered && !nextStart) {
  18439. return;
  18440. }
  18441. // Jump start gaps within jump threshold
  18442. var startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime;
  18443. // When joining a live stream with audio tracks, account for live playlist window sliding by allowing
  18444. // a larger jump over start gaps caused by the audio-stream-controller buffering a start fragment
  18445. // that begins over 1 target duration after the video start position.
  18446. var level = this.hls.levels ? this.hls.levels[this.hls.currentLevel] : null;
  18447. var isLive = level == null ? void 0 : (_level$details = level.details) == null ? void 0 : _level$details.live;
  18448. var maxStartGapJump = isLive ? level.details.targetduration * 2 : MAX_START_GAP_JUMP;
  18449. var partialOrGap = this.fragmentTracker.getPartialFragment(currentTime);
  18450. if (startJump > 0 && (startJump <= maxStartGapJump || partialOrGap)) {
  18451. if (!media.paused) {
  18452. this._trySkipBufferHole(partialOrGap);
  18453. }
  18454. return;
  18455. }
  18456. }
  18457. // Start tracking stall time
  18458. var tnow = self.performance.now();
  18459. if (stalled === null) {
  18460. this.stalled = tnow;
  18461. return;
  18462. }
  18463. var stalledDuration = tnow - stalled;
  18464. if (!seeking && stalledDuration >= STALL_MINIMUM_DURATION_MS) {
  18465. // Report stalling after trying to fix
  18466. this._reportStall(bufferInfo);
  18467. if (!this.media) {
  18468. return;
  18469. }
  18470. }
  18471. var bufferedWithHoles = BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);
  18472. this._tryFixBufferStall(bufferedWithHoles, stalledDuration);
  18473. }
  18474. /**
  18475. * Detects and attempts to fix known buffer stalling issues.
  18476. * @param bufferInfo - The properties of the current buffer.
  18477. * @param stalledDurationMs - The amount of time Hls.js has been stalling for.
  18478. * @private
  18479. */;
  18480. _proto._tryFixBufferStall = function _tryFixBufferStall(bufferInfo, stalledDurationMs) {
  18481. var config = this.config,
  18482. fragmentTracker = this.fragmentTracker,
  18483. media = this.media;
  18484. if (media === null) {
  18485. return;
  18486. }
  18487. var currentTime = media.currentTime;
  18488. var partial = fragmentTracker.getPartialFragment(currentTime);
  18489. if (partial) {
  18490. // Try to skip over the buffer hole caused by a partial fragment
  18491. // This method isn't limited by the size of the gap between buffered ranges
  18492. var targetTime = this._trySkipBufferHole(partial);
  18493. // we return here in this case, meaning
  18494. // the branch below only executes when we haven't seeked to a new position
  18495. if (targetTime || !this.media) {
  18496. return;
  18497. }
  18498. }
  18499. // if we haven't had to skip over a buffer hole of a partial fragment
  18500. // we may just have to "nudge" the playlist as the browser decoding/rendering engine
  18501. // needs to cross some sort of threshold covering all source-buffers content
  18502. // to start playing properly.
  18503. if ((bufferInfo.len > config.maxBufferHole || bufferInfo.nextStart && bufferInfo.nextStart - currentTime < config.maxBufferHole) && stalledDurationMs > config.highBufferWatchdogPeriod * 1000) {
  18504. logger.warn('Trying to nudge playhead over buffer-hole');
  18505. // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds
  18506. // We only try to jump the hole if it's under the configured size
  18507. // Reset stalled so to rearm watchdog timer
  18508. this.stalled = null;
  18509. this._tryNudgeBuffer();
  18510. }
  18511. }
  18512. /**
  18513. * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.
  18514. * @param bufferLen - The playhead distance from the end of the current buffer segment.
  18515. * @private
  18516. */;
  18517. _proto._reportStall = function _reportStall(bufferInfo) {
  18518. var hls = this.hls,
  18519. media = this.media,
  18520. stallReported = this.stallReported;
  18521. if (!stallReported && media) {
  18522. // Report stalled error once
  18523. this.stallReported = true;
  18524. var error = new Error("Playback stalling at @" + media.currentTime + " due to low buffer (" + JSON.stringify(bufferInfo) + ")");
  18525. logger.warn(error.message);
  18526. hls.trigger(Events.ERROR, {
  18527. type: ErrorTypes.MEDIA_ERROR,
  18528. details: ErrorDetails.BUFFER_STALLED_ERROR,
  18529. fatal: false,
  18530. error: error,
  18531. buffer: bufferInfo.len
  18532. });
  18533. }
  18534. }
  18535. /**
  18536. * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
  18537. * @param partial - The partial fragment found at the current time (where playback is stalling).
  18538. * @private
  18539. */;
  18540. _proto._trySkipBufferHole = function _trySkipBufferHole(partial) {
  18541. var config = this.config,
  18542. hls = this.hls,
  18543. media = this.media;
  18544. if (media === null) {
  18545. return 0;
  18546. }
  18547. // Check if currentTime is between unbuffered regions of partial fragments
  18548. var currentTime = media.currentTime;
  18549. var bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  18550. var startTime = currentTime < bufferInfo.start ? bufferInfo.start : bufferInfo.nextStart;
  18551. if (startTime) {
  18552. var bufferStarved = bufferInfo.len <= config.maxBufferHole;
  18553. var waiting = bufferInfo.len > 0 && bufferInfo.len < 1 && media.readyState < 3;
  18554. var gapLength = startTime - currentTime;
  18555. if (gapLength > 0 && (bufferStarved || waiting)) {
  18556. // Only allow large gaps to be skipped if it is a start gap, or all fragments in skip range are partial
  18557. if (gapLength > config.maxBufferHole) {
  18558. var fragmentTracker = this.fragmentTracker;
  18559. var startGap = false;
  18560. if (currentTime === 0) {
  18561. var startFrag = fragmentTracker.getAppendedFrag(0, PlaylistLevelType.MAIN);
  18562. if (startFrag && startTime < startFrag.end) {
  18563. startGap = true;
  18564. }
  18565. }
  18566. if (!startGap) {
  18567. var startProvisioned = partial || fragmentTracker.getAppendedFrag(currentTime, PlaylistLevelType.MAIN);
  18568. if (startProvisioned) {
  18569. var moreToLoad = false;
  18570. var pos = startProvisioned.end;
  18571. while (pos < startTime) {
  18572. var provisioned = fragmentTracker.getPartialFragment(pos);
  18573. if (provisioned) {
  18574. pos += provisioned.duration;
  18575. } else {
  18576. moreToLoad = true;
  18577. break;
  18578. }
  18579. }
  18580. if (moreToLoad) {
  18581. return 0;
  18582. }
  18583. }
  18584. }
  18585. }
  18586. var targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);
  18587. logger.warn("skipping hole, adjusting currentTime from " + currentTime + " to " + targetTime);
  18588. this.moved = true;
  18589. this.stalled = null;
  18590. media.currentTime = targetTime;
  18591. if (partial && !partial.gap) {
  18592. var error = new Error("fragment loaded with buffer holes, seeking from " + currentTime + " to " + targetTime);
  18593. hls.trigger(Events.ERROR, {
  18594. type: ErrorTypes.MEDIA_ERROR,
  18595. details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,
  18596. fatal: false,
  18597. error: error,
  18598. reason: error.message,
  18599. frag: partial
  18600. });
  18601. }
  18602. return targetTime;
  18603. }
  18604. }
  18605. return 0;
  18606. }
  18607. /**
  18608. * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
  18609. * @private
  18610. */;
  18611. _proto._tryNudgeBuffer = function _tryNudgeBuffer() {
  18612. var config = this.config,
  18613. hls = this.hls,
  18614. media = this.media,
  18615. nudgeRetry = this.nudgeRetry;
  18616. if (media === null) {
  18617. return;
  18618. }
  18619. var currentTime = media.currentTime;
  18620. this.nudgeRetry++;
  18621. if (nudgeRetry < config.nudgeMaxRetry) {
  18622. var targetTime = currentTime + (nudgeRetry + 1) * config.nudgeOffset;
  18623. // playback stalled in buffered area ... let's nudge currentTime to try to overcome this
  18624. var error = new Error("Nudging 'currentTime' from " + currentTime + " to " + targetTime);
  18625. logger.warn(error.message);
  18626. media.currentTime = targetTime;
  18627. hls.trigger(Events.ERROR, {
  18628. type: ErrorTypes.MEDIA_ERROR,
  18629. details: ErrorDetails.BUFFER_NUDGE_ON_STALL,
  18630. error: error,
  18631. fatal: false
  18632. });
  18633. } else {
  18634. var _error = new Error("Playhead still not moving while enough data buffered @" + currentTime + " after " + config.nudgeMaxRetry + " nudges");
  18635. logger.error(_error.message);
  18636. hls.trigger(Events.ERROR, {
  18637. type: ErrorTypes.MEDIA_ERROR,
  18638. details: ErrorDetails.BUFFER_STALLED_ERROR,
  18639. error: _error,
  18640. fatal: true
  18641. });
  18642. }
  18643. };
  18644. return GapController;
  18645. }();
  18646. var TICK_INTERVAL = 100; // how often to tick in ms
  18647. var StreamController = /*#__PURE__*/function (_BaseStreamController) {
  18648. _inheritsLoose(StreamController, _BaseStreamController);
  18649. function StreamController(hls, fragmentTracker, keyLoader) {
  18650. var _this;
  18651. _this = _BaseStreamController.call(this, hls, fragmentTracker, keyLoader, '[stream-controller]', PlaylistLevelType.MAIN) || this;
  18652. _this.audioCodecSwap = false;
  18653. _this.gapController = null;
  18654. _this.level = -1;
  18655. _this._forceStartLoad = false;
  18656. _this.altAudio = false;
  18657. _this.audioOnly = false;
  18658. _this.fragPlaying = null;
  18659. _this.onvplaying = null;
  18660. _this.onvseeked = null;
  18661. _this.fragLastKbps = 0;
  18662. _this.couldBacktrack = false;
  18663. _this.backtrackFragment = null;
  18664. _this.audioCodecSwitch = false;
  18665. _this.videoBuffer = null;
  18666. _this._registerListeners();
  18667. return _this;
  18668. }
  18669. var _proto = StreamController.prototype;
  18670. _proto._registerListeners = function _registerListeners() {
  18671. var hls = this.hls;
  18672. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  18673. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  18674. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  18675. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  18676. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  18677. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  18678. hls.on(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  18679. hls.on(Events.ERROR, this.onError, this);
  18680. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  18681. hls.on(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  18682. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  18683. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  18684. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  18685. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  18686. };
  18687. _proto._unregisterListeners = function _unregisterListeners() {
  18688. var hls = this.hls;
  18689. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  18690. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  18691. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  18692. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  18693. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  18694. hls.off(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  18695. hls.off(Events.ERROR, this.onError, this);
  18696. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  18697. hls.off(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  18698. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  18699. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  18700. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  18701. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  18702. };
  18703. _proto.onHandlerDestroying = function onHandlerDestroying() {
  18704. this._unregisterListeners();
  18705. _BaseStreamController.prototype.onHandlerDestroying.call(this);
  18706. };
  18707. _proto.startLoad = function startLoad(startPosition) {
  18708. if (this.levels) {
  18709. var lastCurrentTime = this.lastCurrentTime,
  18710. hls = this.hls;
  18711. this.stopLoad();
  18712. this.setInterval(TICK_INTERVAL);
  18713. this.level = -1;
  18714. if (!this.startFragRequested) {
  18715. // determine load level
  18716. var startLevel = hls.startLevel;
  18717. if (startLevel === -1) {
  18718. if (hls.config.testBandwidth && this.levels.length > 1) {
  18719. // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
  18720. startLevel = 0;
  18721. this.bitrateTest = true;
  18722. } else {
  18723. startLevel = hls.firstAutoLevel;
  18724. }
  18725. }
  18726. // set new level to playlist loader : this will trigger start level load
  18727. // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
  18728. hls.nextLoadLevel = startLevel;
  18729. this.level = hls.loadLevel;
  18730. this.loadedmetadata = false;
  18731. }
  18732. // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime
  18733. if (lastCurrentTime > 0 && startPosition === -1) {
  18734. this.log("Override startPosition with lastCurrentTime @" + lastCurrentTime.toFixed(3));
  18735. startPosition = lastCurrentTime;
  18736. }
  18737. this.state = State.IDLE;
  18738. this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
  18739. this.tick();
  18740. } else {
  18741. this._forceStartLoad = true;
  18742. this.state = State.STOPPED;
  18743. }
  18744. };
  18745. _proto.stopLoad = function stopLoad() {
  18746. this._forceStartLoad = false;
  18747. _BaseStreamController.prototype.stopLoad.call(this);
  18748. };
  18749. _proto.doTick = function doTick() {
  18750. switch (this.state) {
  18751. case State.WAITING_LEVEL:
  18752. {
  18753. var levels = this.levels,
  18754. level = this.level;
  18755. var currentLevel = levels == null ? void 0 : levels[level];
  18756. var details = currentLevel == null ? void 0 : currentLevel.details;
  18757. if (details && (!details.live || this.levelLastLoaded === currentLevel)) {
  18758. if (this.waitForCdnTuneIn(details)) {
  18759. break;
  18760. }
  18761. this.state = State.IDLE;
  18762. break;
  18763. } else if (this.hls.nextLoadLevel !== this.level) {
  18764. this.state = State.IDLE;
  18765. break;
  18766. }
  18767. break;
  18768. }
  18769. case State.FRAG_LOADING_WAITING_RETRY:
  18770. {
  18771. var _this$media;
  18772. var now = self.performance.now();
  18773. var retryDate = this.retryDate;
  18774. // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  18775. if (!retryDate || now >= retryDate || (_this$media = this.media) != null && _this$media.seeking) {
  18776. var _levels = this.levels,
  18777. _level = this.level;
  18778. var _currentLevel = _levels == null ? void 0 : _levels[_level];
  18779. this.resetStartWhenNotLoaded(_currentLevel || null);
  18780. this.state = State.IDLE;
  18781. }
  18782. }
  18783. break;
  18784. }
  18785. if (this.state === State.IDLE) {
  18786. this.doTickIdle();
  18787. }
  18788. this.onTickEnd();
  18789. };
  18790. _proto.onTickEnd = function onTickEnd() {
  18791. _BaseStreamController.prototype.onTickEnd.call(this);
  18792. this.checkBuffer();
  18793. this.checkFragmentChanged();
  18794. };
  18795. _proto.doTickIdle = function doTickIdle() {
  18796. var hls = this.hls,
  18797. levelLastLoaded = this.levelLastLoaded,
  18798. levels = this.levels,
  18799. media = this.media;
  18800. // if start level not parsed yet OR
  18801. // if video not attached AND start fragment already requested OR start frag prefetch not enabled
  18802. // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment
  18803. if (levelLastLoaded === null || !media && (this.startFragRequested || !hls.config.startFragPrefetch)) {
  18804. return;
  18805. }
  18806. // If the "main" level is audio-only but we are loading an alternate track in the same group, do not load anything
  18807. if (this.altAudio && this.audioOnly) {
  18808. return;
  18809. }
  18810. var level = hls.nextLoadLevel;
  18811. if (!(levels != null && levels[level])) {
  18812. return;
  18813. }
  18814. var levelInfo = levels[level];
  18815. // if buffer length is less than maxBufLen try to load a new fragment
  18816. var bufferInfo = this.getMainFwdBufferInfo();
  18817. if (bufferInfo === null) {
  18818. return;
  18819. }
  18820. var lastDetails = this.getLevelDetails();
  18821. if (lastDetails && this._streamEnded(bufferInfo, lastDetails)) {
  18822. var data = {};
  18823. if (this.altAudio) {
  18824. data.type = 'video';
  18825. }
  18826. this.hls.trigger(Events.BUFFER_EOS, data);
  18827. this.state = State.ENDED;
  18828. return;
  18829. }
  18830. // set next load level : this will trigger a playlist load if needed
  18831. if (hls.loadLevel !== level && hls.manualLevel === -1) {
  18832. this.log("Adapting to level " + level + " from level " + this.level);
  18833. }
  18834. this.level = hls.nextLoadLevel = level;
  18835. var levelDetails = levelInfo.details;
  18836. // if level info not retrieved yet, switch state and wait for level retrieval
  18837. // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
  18838. // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
  18839. if (!levelDetails || this.state === State.WAITING_LEVEL || levelDetails.live && this.levelLastLoaded !== levelInfo) {
  18840. this.level = level;
  18841. this.state = State.WAITING_LEVEL;
  18842. return;
  18843. }
  18844. var bufferLen = bufferInfo.len;
  18845. // 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
  18846. var maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate);
  18847. // Stay idle if we are still with buffer margins
  18848. if (bufferLen >= maxBufLen) {
  18849. return;
  18850. }
  18851. if (this.backtrackFragment && this.backtrackFragment.start > bufferInfo.end) {
  18852. this.backtrackFragment = null;
  18853. }
  18854. var targetBufferTime = this.backtrackFragment ? this.backtrackFragment.start : bufferInfo.end;
  18855. var frag = this.getNextFragment(targetBufferTime, levelDetails);
  18856. // Avoid backtracking by loading an earlier segment in streams with segments that do not start with a key frame (flagged by `couldBacktrack`)
  18857. if (this.couldBacktrack && !this.fragPrevious && frag && frag.sn !== 'initSegment' && this.fragmentTracker.getState(frag) !== FragmentState.OK) {
  18858. var _this$backtrackFragme;
  18859. var backtrackSn = ((_this$backtrackFragme = this.backtrackFragment) != null ? _this$backtrackFragme : frag).sn;
  18860. var fragIdx = backtrackSn - levelDetails.startSN;
  18861. var backtrackFrag = levelDetails.fragments[fragIdx - 1];
  18862. if (backtrackFrag && frag.cc === backtrackFrag.cc) {
  18863. frag = backtrackFrag;
  18864. this.fragmentTracker.removeFragment(backtrackFrag);
  18865. }
  18866. } else if (this.backtrackFragment && bufferInfo.len) {
  18867. this.backtrackFragment = null;
  18868. }
  18869. // Avoid loop loading by using nextLoadPosition set for backtracking and skipping consecutive GAP tags
  18870. if (frag && this.isLoopLoading(frag, targetBufferTime)) {
  18871. var gapStart = frag.gap;
  18872. if (!gapStart) {
  18873. // Cleanup the fragment tracker before trying to find the next unbuffered fragment
  18874. var type = this.audioOnly && !this.altAudio ? ElementaryStreamTypes.AUDIO : ElementaryStreamTypes.VIDEO;
  18875. var mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  18876. if (mediaBuffer) {
  18877. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  18878. }
  18879. }
  18880. frag = this.getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen);
  18881. }
  18882. if (!frag) {
  18883. return;
  18884. }
  18885. if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) {
  18886. frag = frag.initSegment;
  18887. }
  18888. this.loadFragment(frag, levelInfo, targetBufferTime);
  18889. };
  18890. _proto.loadFragment = function loadFragment(frag, level, targetBufferTime) {
  18891. // Check if fragment is not loaded
  18892. var fragState = this.fragmentTracker.getState(frag);
  18893. this.fragCurrent = frag;
  18894. if (fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
  18895. if (frag.sn === 'initSegment') {
  18896. this._loadInitSegment(frag, level);
  18897. } else if (this.bitrateTest) {
  18898. this.log("Fragment " + frag.sn + " of level " + frag.level + " is being downloaded to test bitrate and will not be buffered");
  18899. this._loadBitrateTestFrag(frag, level);
  18900. } else {
  18901. this.startFragRequested = true;
  18902. _BaseStreamController.prototype.loadFragment.call(this, frag, level, targetBufferTime);
  18903. }
  18904. } else {
  18905. this.clearTrackerIfNeeded(frag);
  18906. }
  18907. };
  18908. _proto.getBufferedFrag = function getBufferedFrag(position) {
  18909. return this.fragmentTracker.getBufferedFrag(position, PlaylistLevelType.MAIN);
  18910. };
  18911. _proto.followingBufferedFrag = function followingBufferedFrag(frag) {
  18912. if (frag) {
  18913. // try to get range of next fragment (500ms after this range)
  18914. return this.getBufferedFrag(frag.end + 0.5);
  18915. }
  18916. return null;
  18917. }
  18918. /*
  18919. on immediate level switch :
  18920. - pause playback if playing
  18921. - cancel any pending load request
  18922. - and trigger a buffer flush
  18923. */;
  18924. _proto.immediateLevelSwitch = function immediateLevelSwitch() {
  18925. this.abortCurrentFrag();
  18926. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  18927. }
  18928. /**
  18929. * try to switch ASAP without breaking video playback:
  18930. * in order to ensure smooth but quick level switching,
  18931. * we need to find the next flushable buffer range
  18932. * we should take into account new segment fetch time
  18933. */;
  18934. _proto.nextLevelSwitch = function nextLevelSwitch() {
  18935. var levels = this.levels,
  18936. media = this.media;
  18937. // ensure that media is defined and that metadata are available (to retrieve currentTime)
  18938. if (media != null && media.readyState) {
  18939. var fetchdelay;
  18940. var fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
  18941. if (fragPlayingCurrent && fragPlayingCurrent.start > 1) {
  18942. // flush buffer preceding current fragment (flush until current fragment start offset)
  18943. // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
  18944. this.flushMainBuffer(0, fragPlayingCurrent.start - 1);
  18945. }
  18946. var levelDetails = this.getLevelDetails();
  18947. if (levelDetails != null && levelDetails.live) {
  18948. var bufferInfo = this.getMainFwdBufferInfo();
  18949. // Do not flush in live stream with low buffer
  18950. if (!bufferInfo || bufferInfo.len < levelDetails.targetduration * 2) {
  18951. return;
  18952. }
  18953. }
  18954. if (!media.paused && levels) {
  18955. // add a safety delay of 1s
  18956. var nextLevelId = this.hls.nextLoadLevel;
  18957. var nextLevel = levels[nextLevelId];
  18958. var fragLastKbps = this.fragLastKbps;
  18959. if (fragLastKbps && this.fragCurrent) {
  18960. fetchdelay = this.fragCurrent.duration * nextLevel.maxBitrate / (1000 * fragLastKbps) + 1;
  18961. } else {
  18962. fetchdelay = 0;
  18963. }
  18964. } else {
  18965. fetchdelay = 0;
  18966. }
  18967. // this.log('fetchdelay:'+fetchdelay);
  18968. // find buffer range that will be reached once new fragment will be fetched
  18969. var bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
  18970. if (bufferedFrag) {
  18971. // we can flush buffer range following this one without stalling playback
  18972. var nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);
  18973. if (nextBufferedFrag) {
  18974. // if we are here, we can also cancel any loading/demuxing in progress, as they are useless
  18975. this.abortCurrentFrag();
  18976. // start flush position is in next buffered frag. Leave some padding for non-independent segments and smoother playback.
  18977. var maxStart = nextBufferedFrag.maxStartPTS ? nextBufferedFrag.maxStartPTS : nextBufferedFrag.start;
  18978. var fragDuration = nextBufferedFrag.duration;
  18979. 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)));
  18980. this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);
  18981. }
  18982. }
  18983. }
  18984. };
  18985. _proto.abortCurrentFrag = function abortCurrentFrag() {
  18986. var fragCurrent = this.fragCurrent;
  18987. this.fragCurrent = null;
  18988. this.backtrackFragment = null;
  18989. if (fragCurrent) {
  18990. fragCurrent.abortRequests();
  18991. this.fragmentTracker.removeFragment(fragCurrent);
  18992. }
  18993. switch (this.state) {
  18994. case State.KEY_LOADING:
  18995. case State.FRAG_LOADING:
  18996. case State.FRAG_LOADING_WAITING_RETRY:
  18997. case State.PARSING:
  18998. case State.PARSED:
  18999. this.state = State.IDLE;
  19000. break;
  19001. }
  19002. this.nextLoadPosition = this.getLoadPosition();
  19003. };
  19004. _proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset) {
  19005. _BaseStreamController.prototype.flushMainBuffer.call(this, startOffset, endOffset, this.altAudio ? 'video' : null);
  19006. };
  19007. _proto.onMediaAttached = function onMediaAttached(event, data) {
  19008. _BaseStreamController.prototype.onMediaAttached.call(this, event, data);
  19009. var media = data.media;
  19010. this.onvplaying = this.onMediaPlaying.bind(this);
  19011. this.onvseeked = this.onMediaSeeked.bind(this);
  19012. media.addEventListener('playing', this.onvplaying);
  19013. media.addEventListener('seeked', this.onvseeked);
  19014. this.gapController = new GapController(this.config, media, this.fragmentTracker, this.hls);
  19015. };
  19016. _proto.onMediaDetaching = function onMediaDetaching() {
  19017. var media = this.media;
  19018. if (media && this.onvplaying && this.onvseeked) {
  19019. media.removeEventListener('playing', this.onvplaying);
  19020. media.removeEventListener('seeked', this.onvseeked);
  19021. this.onvplaying = this.onvseeked = null;
  19022. this.videoBuffer = null;
  19023. }
  19024. this.fragPlaying = null;
  19025. if (this.gapController) {
  19026. this.gapController.destroy();
  19027. this.gapController = null;
  19028. }
  19029. _BaseStreamController.prototype.onMediaDetaching.call(this);
  19030. };
  19031. _proto.onMediaPlaying = function onMediaPlaying() {
  19032. // tick to speed up FRAG_CHANGED triggering
  19033. this.tick();
  19034. };
  19035. _proto.onMediaSeeked = function onMediaSeeked() {
  19036. var media = this.media;
  19037. var currentTime = media ? media.currentTime : null;
  19038. if (isFiniteNumber(currentTime)) {
  19039. this.log("Media seeked to " + currentTime.toFixed(3));
  19040. }
  19041. // If seeked was issued before buffer was appended do not tick immediately
  19042. var bufferInfo = this.getMainFwdBufferInfo();
  19043. if (bufferInfo === null || bufferInfo.len === 0) {
  19044. this.warn("Main forward buffer length on \"seeked\" event " + (bufferInfo ? bufferInfo.len : 'empty') + ")");
  19045. return;
  19046. }
  19047. // tick to speed up FRAG_CHANGED triggering
  19048. this.tick();
  19049. };
  19050. _proto.onManifestLoading = function onManifestLoading() {
  19051. // reset buffer on manifest loading
  19052. this.log('Trigger BUFFER_RESET');
  19053. this.hls.trigger(Events.BUFFER_RESET, undefined);
  19054. this.fragmentTracker.removeAllFragments();
  19055. this.couldBacktrack = false;
  19056. this.startPosition = this.lastCurrentTime = this.fragLastKbps = 0;
  19057. this.levels = this.fragPlaying = this.backtrackFragment = this.levelLastLoaded = null;
  19058. this.altAudio = this.audioOnly = this.startFragRequested = false;
  19059. };
  19060. _proto.onManifestParsed = function onManifestParsed(event, data) {
  19061. // detect if we have different kind of audio codecs used amongst playlists
  19062. var aac = false;
  19063. var heaac = false;
  19064. data.levels.forEach(function (level) {
  19065. var codec = level.audioCodec;
  19066. if (codec) {
  19067. aac = aac || codec.indexOf('mp4a.40.2') !== -1;
  19068. heaac = heaac || codec.indexOf('mp4a.40.5') !== -1;
  19069. }
  19070. });
  19071. this.audioCodecSwitch = aac && heaac && !changeTypeSupported();
  19072. if (this.audioCodecSwitch) {
  19073. this.log('Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
  19074. }
  19075. this.levels = data.levels;
  19076. this.startFragRequested = false;
  19077. };
  19078. _proto.onLevelLoading = function onLevelLoading(event, data) {
  19079. var levels = this.levels;
  19080. if (!levels || this.state !== State.IDLE) {
  19081. return;
  19082. }
  19083. var level = levels[data.level];
  19084. if (!level.details || level.details.live && this.levelLastLoaded !== level || this.waitForCdnTuneIn(level.details)) {
  19085. this.state = State.WAITING_LEVEL;
  19086. }
  19087. };
  19088. _proto.onLevelLoaded = function onLevelLoaded(event, data) {
  19089. var _curLevel$details;
  19090. var levels = this.levels;
  19091. var newLevelId = data.level;
  19092. var newDetails = data.details;
  19093. var duration = newDetails.totalduration;
  19094. if (!levels) {
  19095. this.warn("Levels were reset while loading level " + newLevelId);
  19096. return;
  19097. }
  19098. this.log("Level " + newLevelId + " loaded [" + newDetails.startSN + "," + newDetails.endSN + "]" + (newDetails.lastPartSn ? "[part-" + newDetails.lastPartSn + "-" + newDetails.lastPartIndex + "]" : '') + ", cc [" + newDetails.startCC + ", " + newDetails.endCC + "] duration:" + duration);
  19099. var curLevel = levels[newLevelId];
  19100. var fragCurrent = this.fragCurrent;
  19101. if (fragCurrent && (this.state === State.FRAG_LOADING || this.state === State.FRAG_LOADING_WAITING_RETRY)) {
  19102. if (fragCurrent.level !== data.level && fragCurrent.loader) {
  19103. this.abortCurrentFrag();
  19104. }
  19105. }
  19106. var sliding = 0;
  19107. if (newDetails.live || (_curLevel$details = curLevel.details) != null && _curLevel$details.live) {
  19108. var _this$levelLastLoaded;
  19109. this.checkLiveUpdate(newDetails);
  19110. if (newDetails.deltaUpdateFailed) {
  19111. return;
  19112. }
  19113. sliding = this.alignPlaylists(newDetails, curLevel.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  19114. }
  19115. // override level info
  19116. curLevel.details = newDetails;
  19117. this.levelLastLoaded = curLevel;
  19118. this.hls.trigger(Events.LEVEL_UPDATED, {
  19119. details: newDetails,
  19120. level: newLevelId
  19121. });
  19122. // only switch back to IDLE state if we were waiting for level to start downloading a new fragment
  19123. if (this.state === State.WAITING_LEVEL) {
  19124. if (this.waitForCdnTuneIn(newDetails)) {
  19125. // Wait for Low-Latency CDN Tune-in
  19126. return;
  19127. }
  19128. this.state = State.IDLE;
  19129. }
  19130. if (!this.startFragRequested) {
  19131. this.setStartPosition(newDetails, sliding);
  19132. } else if (newDetails.live) {
  19133. this.synchronizeToLiveEdge(newDetails);
  19134. }
  19135. // trigger handler right now
  19136. this.tick();
  19137. };
  19138. _proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(data) {
  19139. var _frag$initSegment;
  19140. var frag = data.frag,
  19141. part = data.part,
  19142. payload = data.payload;
  19143. var levels = this.levels;
  19144. if (!levels) {
  19145. this.warn("Levels were reset while fragment load was in progress. Fragment " + frag.sn + " of level " + frag.level + " will not be buffered");
  19146. return;
  19147. }
  19148. var currentLevel = levels[frag.level];
  19149. var details = currentLevel.details;
  19150. if (!details) {
  19151. this.warn("Dropping fragment " + frag.sn + " of level " + frag.level + " after level details were reset");
  19152. this.fragmentTracker.removeFragment(frag);
  19153. return;
  19154. }
  19155. var videoCodec = currentLevel.videoCodec;
  19156. // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
  19157. var accurateTimeOffset = details.PTSKnown || !details.live;
  19158. var initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data;
  19159. var audioCodec = this._getAudioCodec(currentLevel);
  19160. // transmux the MPEG-TS data to ISO-BMFF segments
  19161. // this.log(`Transmuxing ${frag.sn} of [${details.startSN} ,${details.endSN}],level ${frag.level}, cc ${frag.cc}`);
  19162. var transmuxer = this.transmuxer = this.transmuxer || new TransmuxerInterface(this.hls, PlaylistLevelType.MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
  19163. var partIndex = part ? part.index : -1;
  19164. var partial = partIndex !== -1;
  19165. var chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
  19166. var initPTS = this.initPTS[frag.cc];
  19167. transmuxer.push(payload, initSegmentData, audioCodec, videoCodec, frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
  19168. };
  19169. _proto.onAudioTrackSwitching = function onAudioTrackSwitching(event, data) {
  19170. // if any URL found on new audio track, it is an alternate audio track
  19171. var fromAltAudio = this.altAudio;
  19172. var altAudio = !!data.url;
  19173. // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered
  19174. // don't do anything if we switch to alt audio: audio stream controller is handling it.
  19175. // we will just have to change buffer scheduling on audioTrackSwitched
  19176. if (!altAudio) {
  19177. if (this.mediaBuffer !== this.media) {
  19178. this.log('Switching on main audio, use media.buffered to schedule main fragment loading');
  19179. this.mediaBuffer = this.media;
  19180. var fragCurrent = this.fragCurrent;
  19181. // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch
  19182. if (fragCurrent) {
  19183. this.log('Switching to main audio track, cancel main fragment load');
  19184. fragCurrent.abortRequests();
  19185. this.fragmentTracker.removeFragment(fragCurrent);
  19186. }
  19187. // destroy transmuxer to force init segment generation (following audio switch)
  19188. this.resetTransmuxer();
  19189. // switch to IDLE state to load new fragment
  19190. this.resetLoadingState();
  19191. } else if (this.audioOnly) {
  19192. // Reset audio transmuxer so when switching back to main audio we're not still appending where we left off
  19193. this.resetTransmuxer();
  19194. }
  19195. var hls = this.hls;
  19196. // If switching from alt to main audio, flush all audio and trigger track switched
  19197. if (fromAltAudio) {
  19198. hls.trigger(Events.BUFFER_FLUSHING, {
  19199. startOffset: 0,
  19200. endOffset: Number.POSITIVE_INFINITY,
  19201. type: null
  19202. });
  19203. this.fragmentTracker.removeAllFragments();
  19204. }
  19205. hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);
  19206. }
  19207. };
  19208. _proto.onAudioTrackSwitched = function onAudioTrackSwitched(event, data) {
  19209. var trackId = data.id;
  19210. var altAudio = !!this.hls.audioTracks[trackId].url;
  19211. if (altAudio) {
  19212. var videoBuffer = this.videoBuffer;
  19213. // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered
  19214. if (videoBuffer && this.mediaBuffer !== videoBuffer) {
  19215. this.log('Switching on alternate audio, use video.buffered to schedule main fragment loading');
  19216. this.mediaBuffer = videoBuffer;
  19217. }
  19218. }
  19219. this.altAudio = altAudio;
  19220. this.tick();
  19221. };
  19222. _proto.onBufferCreated = function onBufferCreated(event, data) {
  19223. var tracks = data.tracks;
  19224. var mediaTrack;
  19225. var name;
  19226. var alternate = false;
  19227. for (var type in tracks) {
  19228. var track = tracks[type];
  19229. if (track.id === 'main') {
  19230. name = type;
  19231. mediaTrack = track;
  19232. // keep video source buffer reference
  19233. if (type === 'video') {
  19234. var videoTrack = tracks[type];
  19235. if (videoTrack) {
  19236. this.videoBuffer = videoTrack.buffer;
  19237. }
  19238. }
  19239. } else {
  19240. alternate = true;
  19241. }
  19242. }
  19243. if (alternate && mediaTrack) {
  19244. this.log("Alternate track found, use " + name + ".buffered to schedule main fragment loading");
  19245. this.mediaBuffer = mediaTrack.buffer;
  19246. } else {
  19247. this.mediaBuffer = this.media;
  19248. }
  19249. };
  19250. _proto.onFragBuffered = function onFragBuffered(event, data) {
  19251. var frag = data.frag,
  19252. part = data.part;
  19253. if (frag && frag.type !== PlaylistLevelType.MAIN) {
  19254. return;
  19255. }
  19256. if (this.fragContextChanged(frag)) {
  19257. // If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion
  19258. // Avoid setting state back to IDLE, since that will interfere with a level switch
  19259. this.warn("Fragment " + frag.sn + (part ? ' p: ' + part.index : '') + " of level " + frag.level + " finished buffering, but was aborted. state: " + this.state);
  19260. if (this.state === State.PARSED) {
  19261. this.state = State.IDLE;
  19262. }
  19263. return;
  19264. }
  19265. var stats = part ? part.stats : frag.stats;
  19266. this.fragLastKbps = Math.round(8 * stats.total / (stats.buffering.end - stats.loading.first));
  19267. if (frag.sn !== 'initSegment') {
  19268. this.fragPrevious = frag;
  19269. }
  19270. this.fragBufferedComplete(frag, part);
  19271. };
  19272. _proto.onError = function onError(event, data) {
  19273. var _data$context;
  19274. if (data.fatal) {
  19275. this.state = State.ERROR;
  19276. return;
  19277. }
  19278. switch (data.details) {
  19279. case ErrorDetails.FRAG_GAP:
  19280. case ErrorDetails.FRAG_PARSING_ERROR:
  19281. case ErrorDetails.FRAG_DECRYPT_ERROR:
  19282. case ErrorDetails.FRAG_LOAD_ERROR:
  19283. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  19284. case ErrorDetails.KEY_LOAD_ERROR:
  19285. case ErrorDetails.KEY_LOAD_TIMEOUT:
  19286. this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN, data);
  19287. break;
  19288. case ErrorDetails.LEVEL_LOAD_ERROR:
  19289. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  19290. case ErrorDetails.LEVEL_PARSING_ERROR:
  19291. // in case of non fatal error while loading level, if level controller is not retrying to load level, switch back to IDLE
  19292. if (!data.levelRetry && this.state === State.WAITING_LEVEL && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.LEVEL) {
  19293. this.state = State.IDLE;
  19294. }
  19295. break;
  19296. case ErrorDetails.BUFFER_APPEND_ERROR:
  19297. case ErrorDetails.BUFFER_FULL_ERROR:
  19298. if (!data.parent || data.parent !== 'main') {
  19299. return;
  19300. }
  19301. if (data.details === ErrorDetails.BUFFER_APPEND_ERROR) {
  19302. this.resetLoadingState();
  19303. return;
  19304. }
  19305. if (this.reduceLengthAndFlushBuffer(data)) {
  19306. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  19307. }
  19308. break;
  19309. case ErrorDetails.INTERNAL_EXCEPTION:
  19310. this.recoverWorkerError(data);
  19311. break;
  19312. }
  19313. }
  19314. // Checks the health of the buffer and attempts to resolve playback stalls.
  19315. ;
  19316. _proto.checkBuffer = function checkBuffer() {
  19317. var media = this.media,
  19318. gapController = this.gapController;
  19319. if (!media || !gapController || !media.readyState) {
  19320. // Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)
  19321. return;
  19322. }
  19323. if (this.loadedmetadata || !BufferHelper.getBuffered(media).length) {
  19324. // Resolve gaps using the main buffer, whose ranges are the intersections of the A/V sourcebuffers
  19325. var activeFrag = this.state !== State.IDLE ? this.fragCurrent : null;
  19326. gapController.poll(this.lastCurrentTime, activeFrag);
  19327. }
  19328. this.lastCurrentTime = media.currentTime;
  19329. };
  19330. _proto.onFragLoadEmergencyAborted = function onFragLoadEmergencyAborted() {
  19331. this.state = State.IDLE;
  19332. // if loadedmetadata is not set, it means that we are emergency switch down on first frag
  19333. // in that case, reset startFragRequested flag
  19334. if (!this.loadedmetadata) {
  19335. this.startFragRequested = false;
  19336. this.nextLoadPosition = this.startPosition;
  19337. }
  19338. this.tickImmediate();
  19339. };
  19340. _proto.onBufferFlushed = function onBufferFlushed(event, _ref) {
  19341. var type = _ref.type;
  19342. if (type !== ElementaryStreamTypes.AUDIO || this.audioOnly && !this.altAudio) {
  19343. var mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  19344. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  19345. this.tick();
  19346. }
  19347. };
  19348. _proto.onLevelsUpdated = function onLevelsUpdated(event, data) {
  19349. if (this.level > -1 && this.fragCurrent) {
  19350. this.level = this.fragCurrent.level;
  19351. }
  19352. this.levels = data.levels;
  19353. };
  19354. _proto.swapAudioCodec = function swapAudioCodec() {
  19355. this.audioCodecSwap = !this.audioCodecSwap;
  19356. }
  19357. /**
  19358. * Seeks to the set startPosition if not equal to the mediaElement's current time.
  19359. */;
  19360. _proto.seekToStartPos = function seekToStartPos() {
  19361. var media = this.media;
  19362. if (!media) {
  19363. return;
  19364. }
  19365. var currentTime = media.currentTime;
  19366. var startPosition = this.startPosition;
  19367. // only adjust currentTime if different from startPosition or if startPosition not buffered
  19368. // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered
  19369. if (startPosition >= 0 && currentTime < startPosition) {
  19370. if (media.seeking) {
  19371. this.log("could not seek to " + startPosition + ", already seeking at " + currentTime);
  19372. return;
  19373. }
  19374. var buffered = BufferHelper.getBuffered(media);
  19375. var bufferStart = buffered.length ? buffered.start(0) : 0;
  19376. var delta = bufferStart - startPosition;
  19377. if (delta > 0 && (delta < this.config.maxBufferHole || delta < this.config.maxFragLookUpTolerance)) {
  19378. this.log("adjusting start position by " + delta + " to match buffer start");
  19379. startPosition += delta;
  19380. this.startPosition = startPosition;
  19381. }
  19382. this.log("seek to target start position " + startPosition + " from current time " + currentTime);
  19383. media.currentTime = startPosition;
  19384. }
  19385. };
  19386. _proto._getAudioCodec = function _getAudioCodec(currentLevel) {
  19387. var audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
  19388. if (this.audioCodecSwap && audioCodec) {
  19389. this.log('Swapping audio codec');
  19390. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  19391. audioCodec = 'mp4a.40.2';
  19392. } else {
  19393. audioCodec = 'mp4a.40.5';
  19394. }
  19395. }
  19396. return audioCodec;
  19397. };
  19398. _proto._loadBitrateTestFrag = function _loadBitrateTestFrag(frag, level) {
  19399. var _this2 = this;
  19400. frag.bitrateTest = true;
  19401. this._doFragLoad(frag, level).then(function (data) {
  19402. var hls = _this2.hls;
  19403. if (!data || _this2.fragContextChanged(frag)) {
  19404. return;
  19405. }
  19406. level.fragmentError = 0;
  19407. _this2.state = State.IDLE;
  19408. _this2.startFragRequested = false;
  19409. _this2.bitrateTest = false;
  19410. var stats = frag.stats;
  19411. // Bitrate tests fragments are neither parsed nor buffered
  19412. stats.parsing.start = stats.parsing.end = stats.buffering.start = stats.buffering.end = self.performance.now();
  19413. hls.trigger(Events.FRAG_LOADED, data);
  19414. frag.bitrateTest = false;
  19415. });
  19416. };
  19417. _proto._handleTransmuxComplete = function _handleTransmuxComplete(transmuxResult) {
  19418. var _id3$samples;
  19419. var id = 'main';
  19420. var hls = this.hls;
  19421. var remuxResult = transmuxResult.remuxResult,
  19422. chunkMeta = transmuxResult.chunkMeta;
  19423. var context = this.getCurrentContext(chunkMeta);
  19424. if (!context) {
  19425. this.resetWhenMissingContext(chunkMeta);
  19426. return;
  19427. }
  19428. var frag = context.frag,
  19429. part = context.part,
  19430. level = context.level;
  19431. var video = remuxResult.video,
  19432. text = remuxResult.text,
  19433. id3 = remuxResult.id3,
  19434. initSegment = remuxResult.initSegment;
  19435. var details = level.details;
  19436. // The audio-stream-controller handles audio buffering if Hls.js is playing an alternate audio track
  19437. var audio = this.altAudio ? undefined : remuxResult.audio;
  19438. // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.
  19439. // If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.
  19440. if (this.fragContextChanged(frag)) {
  19441. this.fragmentTracker.removeFragment(frag);
  19442. return;
  19443. }
  19444. this.state = State.PARSING;
  19445. if (initSegment) {
  19446. if (initSegment != null && initSegment.tracks) {
  19447. var mapFragment = frag.initSegment || frag;
  19448. this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta);
  19449. hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {
  19450. frag: mapFragment,
  19451. id: id,
  19452. tracks: initSegment.tracks
  19453. });
  19454. }
  19455. // This would be nice if Number.isFinite acted as a typeguard, but it doesn't. See: https://github.com/Microsoft/TypeScript/issues/10038
  19456. var initPTS = initSegment.initPTS;
  19457. var timescale = initSegment.timescale;
  19458. if (isFiniteNumber(initPTS)) {
  19459. this.initPTS[frag.cc] = {
  19460. baseTime: initPTS,
  19461. timescale: timescale
  19462. };
  19463. hls.trigger(Events.INIT_PTS_FOUND, {
  19464. frag: frag,
  19465. id: id,
  19466. initPTS: initPTS,
  19467. timescale: timescale
  19468. });
  19469. }
  19470. }
  19471. // Avoid buffering if backtracking this fragment
  19472. if (video && details && frag.sn !== 'initSegment') {
  19473. var prevFrag = details.fragments[frag.sn - 1 - details.startSN];
  19474. var isFirstFragment = frag.sn === details.startSN;
  19475. var isFirstInDiscontinuity = !prevFrag || frag.cc > prevFrag.cc;
  19476. if (remuxResult.independent !== false) {
  19477. var startPTS = video.startPTS,
  19478. endPTS = video.endPTS,
  19479. startDTS = video.startDTS,
  19480. endDTS = video.endDTS;
  19481. if (part) {
  19482. part.elementaryStreams[video.type] = {
  19483. startPTS: startPTS,
  19484. endPTS: endPTS,
  19485. startDTS: startDTS,
  19486. endDTS: endDTS
  19487. };
  19488. } else {
  19489. if (video.firstKeyFrame && video.independent && chunkMeta.id === 1 && !isFirstInDiscontinuity) {
  19490. this.couldBacktrack = true;
  19491. }
  19492. if (video.dropped && video.independent) {
  19493. // Backtrack if dropped frames create a gap after currentTime
  19494. var bufferInfo = this.getMainFwdBufferInfo();
  19495. var targetBufferTime = (bufferInfo ? bufferInfo.end : this.getLoadPosition()) + this.config.maxBufferHole;
  19496. var startTime = video.firstKeyFramePTS ? video.firstKeyFramePTS : startPTS;
  19497. if (!isFirstFragment && targetBufferTime < startTime - this.config.maxBufferHole && !isFirstInDiscontinuity) {
  19498. this.backtrack(frag);
  19499. return;
  19500. } else if (isFirstInDiscontinuity) {
  19501. // Mark segment with a gap to avoid loop loading
  19502. frag.gap = true;
  19503. }
  19504. // Set video stream start to fragment start so that truncated samples do not distort the timeline, and mark it partial
  19505. frag.setElementaryStreamInfo(video.type, frag.start, endPTS, frag.start, endDTS, true);
  19506. } else if (isFirstFragment && startPTS > MAX_START_GAP_JUMP) {
  19507. // Mark segment with a gap to skip large start gap
  19508. frag.gap = true;
  19509. }
  19510. }
  19511. frag.setElementaryStreamInfo(video.type, startPTS, endPTS, startDTS, endDTS);
  19512. if (this.backtrackFragment) {
  19513. this.backtrackFragment = frag;
  19514. }
  19515. this.bufferFragmentData(video, frag, part, chunkMeta, isFirstFragment || isFirstInDiscontinuity);
  19516. } else if (isFirstFragment || isFirstInDiscontinuity) {
  19517. // Mark segment with a gap to avoid loop loading
  19518. frag.gap = true;
  19519. } else {
  19520. this.backtrack(frag);
  19521. return;
  19522. }
  19523. }
  19524. if (audio) {
  19525. var _startPTS = audio.startPTS,
  19526. _endPTS = audio.endPTS,
  19527. _startDTS = audio.startDTS,
  19528. _endDTS = audio.endDTS;
  19529. if (part) {
  19530. part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {
  19531. startPTS: _startPTS,
  19532. endPTS: _endPTS,
  19533. startDTS: _startDTS,
  19534. endDTS: _endDTS
  19535. };
  19536. }
  19537. frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, _startPTS, _endPTS, _startDTS, _endDTS);
  19538. this.bufferFragmentData(audio, frag, part, chunkMeta);
  19539. }
  19540. if (details && id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) {
  19541. var emittedID3 = {
  19542. id: id,
  19543. frag: frag,
  19544. details: details,
  19545. samples: id3.samples
  19546. };
  19547. hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);
  19548. }
  19549. if (details && text) {
  19550. var emittedText = {
  19551. id: id,
  19552. frag: frag,
  19553. details: details,
  19554. samples: text.samples
  19555. };
  19556. hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);
  19557. }
  19558. };
  19559. _proto._bufferInitSegment = function _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
  19560. var _this3 = this;
  19561. if (this.state !== State.PARSING) {
  19562. return;
  19563. }
  19564. this.audioOnly = !!tracks.audio && !tracks.video;
  19565. // if audio track is expected to come from audio stream controller, discard any coming from main
  19566. if (this.altAudio && !this.audioOnly) {
  19567. delete tracks.audio;
  19568. }
  19569. // include levelCodec in audio and video tracks
  19570. var audio = tracks.audio,
  19571. video = tracks.video,
  19572. audiovideo = tracks.audiovideo;
  19573. if (audio) {
  19574. var audioCodec = currentLevel.audioCodec;
  19575. var ua = navigator.userAgent.toLowerCase();
  19576. if (this.audioCodecSwitch) {
  19577. if (audioCodec) {
  19578. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  19579. audioCodec = 'mp4a.40.2';
  19580. } else {
  19581. audioCodec = 'mp4a.40.5';
  19582. }
  19583. }
  19584. // In the case that AAC and HE-AAC audio codecs are signalled in manifest,
  19585. // force HE-AAC, as it seems that most browsers prefers it.
  19586. // don't force HE-AAC if mono stream, or in Firefox
  19587. var audioMetadata = audio.metadata;
  19588. if (audioMetadata && 'channelCount' in audioMetadata && (audioMetadata.channelCount || 1) !== 1 && ua.indexOf('firefox') === -1) {
  19589. audioCodec = 'mp4a.40.5';
  19590. }
  19591. }
  19592. // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise
  19593. if (audioCodec && audioCodec.indexOf('mp4a.40.5') !== -1 && ua.indexOf('android') !== -1 && audio.container !== 'audio/mpeg') {
  19594. // Exclude mpeg audio
  19595. audioCodec = 'mp4a.40.2';
  19596. this.log("Android: force audio codec to " + audioCodec);
  19597. }
  19598. if (currentLevel.audioCodec && currentLevel.audioCodec !== audioCodec) {
  19599. this.log("Swapping manifest audio codec \"" + currentLevel.audioCodec + "\" for \"" + audioCodec + "\"");
  19600. }
  19601. audio.levelCodec = audioCodec;
  19602. audio.id = 'main';
  19603. this.log("Init audio buffer, container:" + audio.container + ", codecs[selected/level/parsed]=[" + (audioCodec || '') + "/" + (currentLevel.audioCodec || '') + "/" + audio.codec + "]");
  19604. }
  19605. if (video) {
  19606. video.levelCodec = currentLevel.videoCodec;
  19607. video.id = 'main';
  19608. this.log("Init video buffer, container:" + video.container + ", codecs[level/parsed]=[" + (currentLevel.videoCodec || '') + "/" + video.codec + "]");
  19609. }
  19610. if (audiovideo) {
  19611. this.log("Init audiovideo buffer, container:" + audiovideo.container + ", codecs[level/parsed]=[" + currentLevel.codecs + "/" + audiovideo.codec + "]");
  19612. }
  19613. this.hls.trigger(Events.BUFFER_CODECS, tracks);
  19614. // loop through tracks that are going to be provided to bufferController
  19615. Object.keys(tracks).forEach(function (trackName) {
  19616. var track = tracks[trackName];
  19617. var initSegment = track.initSegment;
  19618. if (initSegment != null && initSegment.byteLength) {
  19619. _this3.hls.trigger(Events.BUFFER_APPENDING, {
  19620. type: trackName,
  19621. data: initSegment,
  19622. frag: frag,
  19623. part: null,
  19624. chunkMeta: chunkMeta,
  19625. parent: frag.type
  19626. });
  19627. }
  19628. });
  19629. // trigger handler right now
  19630. this.tickImmediate();
  19631. };
  19632. _proto.getMainFwdBufferInfo = function getMainFwdBufferInfo() {
  19633. return this.getFwdBufferInfo(this.mediaBuffer ? this.mediaBuffer : this.media, PlaylistLevelType.MAIN);
  19634. };
  19635. _proto.backtrack = function backtrack(frag) {
  19636. this.couldBacktrack = true;
  19637. // Causes findFragments to backtrack through fragments to find the keyframe
  19638. this.backtrackFragment = frag;
  19639. this.resetTransmuxer();
  19640. this.flushBufferGap(frag);
  19641. this.fragmentTracker.removeFragment(frag);
  19642. this.fragPrevious = null;
  19643. this.nextLoadPosition = frag.start;
  19644. this.state = State.IDLE;
  19645. };
  19646. _proto.checkFragmentChanged = function checkFragmentChanged() {
  19647. var video = this.media;
  19648. var fragPlayingCurrent = null;
  19649. if (video && video.readyState > 1 && video.seeking === false) {
  19650. var currentTime = video.currentTime;
  19651. /* if video element is in seeked state, currentTime can only increase.
  19652. (assuming that playback rate is positive ...)
  19653. As sometimes currentTime jumps back to zero after a
  19654. media decode error, check this, to avoid seeking back to
  19655. wrong position after a media decode error
  19656. */
  19657. if (BufferHelper.isBuffered(video, currentTime)) {
  19658. fragPlayingCurrent = this.getAppendedFrag(currentTime);
  19659. } else if (BufferHelper.isBuffered(video, currentTime + 0.1)) {
  19660. /* ensure that FRAG_CHANGED event is triggered at startup,
  19661. when first video frame is displayed and playback is paused.
  19662. add a tolerance of 100ms, in case current position is not buffered,
  19663. check if current pos+100ms is buffered and use that buffer range
  19664. for FRAG_CHANGED event reporting */
  19665. fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1);
  19666. }
  19667. if (fragPlayingCurrent) {
  19668. this.backtrackFragment = null;
  19669. var fragPlaying = this.fragPlaying;
  19670. var fragCurrentLevel = fragPlayingCurrent.level;
  19671. if (!fragPlaying || fragPlayingCurrent.sn !== fragPlaying.sn || fragPlaying.level !== fragCurrentLevel) {
  19672. this.fragPlaying = fragPlayingCurrent;
  19673. this.hls.trigger(Events.FRAG_CHANGED, {
  19674. frag: fragPlayingCurrent
  19675. });
  19676. if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) {
  19677. this.hls.trigger(Events.LEVEL_SWITCHED, {
  19678. level: fragCurrentLevel
  19679. });
  19680. }
  19681. }
  19682. }
  19683. }
  19684. };
  19685. _createClass(StreamController, [{
  19686. key: "nextLevel",
  19687. get: function get() {
  19688. var frag = this.nextBufferedFrag;
  19689. if (frag) {
  19690. return frag.level;
  19691. }
  19692. return -1;
  19693. }
  19694. }, {
  19695. key: "currentFrag",
  19696. get: function get() {
  19697. var media = this.media;
  19698. if (media) {
  19699. return this.fragPlaying || this.getAppendedFrag(media.currentTime);
  19700. }
  19701. return null;
  19702. }
  19703. }, {
  19704. key: "currentProgramDateTime",
  19705. get: function get() {
  19706. var media = this.media;
  19707. if (media) {
  19708. var currentTime = media.currentTime;
  19709. var frag = this.currentFrag;
  19710. if (frag && isFiniteNumber(currentTime) && isFiniteNumber(frag.programDateTime)) {
  19711. var epocMs = frag.programDateTime + (currentTime - frag.start) * 1000;
  19712. return new Date(epocMs);
  19713. }
  19714. }
  19715. return null;
  19716. }
  19717. }, {
  19718. key: "currentLevel",
  19719. get: function get() {
  19720. var frag = this.currentFrag;
  19721. if (frag) {
  19722. return frag.level;
  19723. }
  19724. return -1;
  19725. }
  19726. }, {
  19727. key: "nextBufferedFrag",
  19728. get: function get() {
  19729. var frag = this.currentFrag;
  19730. if (frag) {
  19731. return this.followingBufferedFrag(frag);
  19732. }
  19733. return null;
  19734. }
  19735. }, {
  19736. key: "forceStartLoad",
  19737. get: function get() {
  19738. return this._forceStartLoad;
  19739. }
  19740. }]);
  19741. return StreamController;
  19742. }(BaseStreamController);
  19743. /**
  19744. * The `Hls` class is the core of the HLS.js library used to instantiate player instances.
  19745. * @public
  19746. */
  19747. var Hls = /*#__PURE__*/function () {
  19748. /**
  19749. * Check if the required MediaSource Extensions are available.
  19750. */
  19751. Hls.isMSESupported = function isMSESupported$1() {
  19752. return isMSESupported();
  19753. }
  19754. /**
  19755. * Check if MediaSource Extensions are available and isTypeSupported checks pass for any baseline codecs.
  19756. */;
  19757. Hls.isSupported = function isSupported$1() {
  19758. return isSupported();
  19759. }
  19760. /**
  19761. * Get the MediaSource global used for MSE playback (ManagedMediaSource, MediaSource, or WebKitMediaSource).
  19762. */;
  19763. Hls.getMediaSource = function getMediaSource$1() {
  19764. return getMediaSource();
  19765. };
  19766. /**
  19767. * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
  19768. * @param userConfig - Configuration options applied over `Hls.DefaultConfig`
  19769. */
  19770. function Hls(userConfig) {
  19771. if (userConfig === void 0) {
  19772. userConfig = {};
  19773. }
  19774. /**
  19775. * The runtime configuration used by the player. At instantiation this is combination of `hls.userConfig` merged over `Hls.DefaultConfig`.
  19776. */
  19777. this.config = void 0;
  19778. /**
  19779. * The configuration object provided on player instantiation.
  19780. */
  19781. this.userConfig = void 0;
  19782. this.coreComponents = void 0;
  19783. this.networkControllers = void 0;
  19784. this.started = false;
  19785. this._emitter = new EventEmitter();
  19786. this._autoLevelCapping = -1;
  19787. this._maxHdcpLevel = null;
  19788. this.abrController = void 0;
  19789. this.bufferController = void 0;
  19790. this.capLevelController = void 0;
  19791. this.latencyController = void 0;
  19792. this.levelController = void 0;
  19793. this.streamController = void 0;
  19794. this.audioTrackController = void 0;
  19795. this.subtitleTrackController = void 0;
  19796. this.emeController = void 0;
  19797. this.cmcdController = void 0;
  19798. this._media = null;
  19799. this.url = null;
  19800. this.triggeringException = void 0;
  19801. enableLogs(userConfig.debug || false, 'Hls instance');
  19802. var config = this.config = mergeConfig(Hls.DefaultConfig, userConfig);
  19803. this.userConfig = userConfig;
  19804. if (config.progressive) {
  19805. enableStreamingMode(config);
  19806. }
  19807. // core controllers and network loaders
  19808. var ConfigAbrController = config.abrController,
  19809. ConfigBufferController = config.bufferController,
  19810. ConfigCapLevelController = config.capLevelController,
  19811. ConfigErrorController = config.errorController,
  19812. ConfigFpsController = config.fpsController;
  19813. var errorController = new ConfigErrorController(this);
  19814. var abrController = this.abrController = new ConfigAbrController(this);
  19815. var bufferController = this.bufferController = new ConfigBufferController(this);
  19816. var capLevelController = this.capLevelController = new ConfigCapLevelController(this);
  19817. var fpsController = new ConfigFpsController(this);
  19818. var playListLoader = new PlaylistLoader(this);
  19819. var id3TrackController = new ID3TrackController(this);
  19820. var ConfigContentSteeringController = config.contentSteeringController;
  19821. // ConentSteeringController is defined before LevelController to receive Multivariant Playlist events first
  19822. var contentSteering = ConfigContentSteeringController ? new ConfigContentSteeringController(this) : null;
  19823. var levelController = this.levelController = new LevelController(this, contentSteering);
  19824. // FragmentTracker must be defined before StreamController because the order of event handling is important
  19825. var fragmentTracker = new FragmentTracker(this);
  19826. var keyLoader = new KeyLoader(this.config);
  19827. var streamController = this.streamController = new StreamController(this, fragmentTracker, keyLoader);
  19828. // Cap level controller uses streamController to flush the buffer
  19829. capLevelController.setStreamController(streamController);
  19830. // fpsController uses streamController to switch when frames are being dropped
  19831. fpsController.setStreamController(streamController);
  19832. var networkControllers = [playListLoader, levelController, streamController];
  19833. if (contentSteering) {
  19834. networkControllers.splice(1, 0, contentSteering);
  19835. }
  19836. this.networkControllers = networkControllers;
  19837. var coreComponents = [abrController, bufferController, capLevelController, fpsController, id3TrackController, fragmentTracker];
  19838. this.audioTrackController = this.createController(config.audioTrackController, networkControllers);
  19839. var AudioStreamControllerClass = config.audioStreamController;
  19840. if (AudioStreamControllerClass) {
  19841. networkControllers.push(new AudioStreamControllerClass(this, fragmentTracker, keyLoader));
  19842. }
  19843. // subtitleTrackController must be defined before subtitleStreamController because the order of event handling is important
  19844. this.subtitleTrackController = this.createController(config.subtitleTrackController, networkControllers);
  19845. var SubtitleStreamControllerClass = config.subtitleStreamController;
  19846. if (SubtitleStreamControllerClass) {
  19847. networkControllers.push(new SubtitleStreamControllerClass(this, fragmentTracker, keyLoader));
  19848. }
  19849. this.createController(config.timelineController, coreComponents);
  19850. keyLoader.emeController = this.emeController = this.createController(config.emeController, coreComponents);
  19851. this.cmcdController = this.createController(config.cmcdController, coreComponents);
  19852. this.latencyController = this.createController(LatencyController, coreComponents);
  19853. this.coreComponents = coreComponents;
  19854. // Error controller handles errors before and after all other controllers
  19855. // This listener will be invoked after all other controllers error listeners
  19856. networkControllers.push(errorController);
  19857. var onErrorOut = errorController.onErrorOut;
  19858. if (typeof onErrorOut === 'function') {
  19859. this.on(Events.ERROR, onErrorOut, errorController);
  19860. }
  19861. }
  19862. var _proto = Hls.prototype;
  19863. _proto.createController = function createController(ControllerClass, components) {
  19864. if (ControllerClass) {
  19865. var controllerInstance = new ControllerClass(this);
  19866. if (components) {
  19867. components.push(controllerInstance);
  19868. }
  19869. return controllerInstance;
  19870. }
  19871. return null;
  19872. }
  19873. // Delegate the EventEmitter through the public API of Hls.js
  19874. ;
  19875. _proto.on = function on(event, listener, context) {
  19876. if (context === void 0) {
  19877. context = this;
  19878. }
  19879. this._emitter.on(event, listener, context);
  19880. };
  19881. _proto.once = function once(event, listener, context) {
  19882. if (context === void 0) {
  19883. context = this;
  19884. }
  19885. this._emitter.once(event, listener, context);
  19886. };
  19887. _proto.removeAllListeners = function removeAllListeners(event) {
  19888. this._emitter.removeAllListeners(event);
  19889. };
  19890. _proto.off = function off(event, listener, context, once) {
  19891. if (context === void 0) {
  19892. context = this;
  19893. }
  19894. this._emitter.off(event, listener, context, once);
  19895. };
  19896. _proto.listeners = function listeners(event) {
  19897. return this._emitter.listeners(event);
  19898. };
  19899. _proto.emit = function emit(event, name, eventObject) {
  19900. return this._emitter.emit(event, name, eventObject);
  19901. };
  19902. _proto.trigger = function trigger(event, eventObject) {
  19903. if (this.config.debug) {
  19904. return this.emit(event, event, eventObject);
  19905. } else {
  19906. try {
  19907. return this.emit(event, event, eventObject);
  19908. } catch (error) {
  19909. logger.error('An internal error happened while handling event ' + event + '. Error message: "' + error.message + '". Here is a stacktrace:', error);
  19910. // Prevent recursion in error event handlers that throw #5497
  19911. if (!this.triggeringException) {
  19912. this.triggeringException = true;
  19913. var fatal = event === Events.ERROR;
  19914. this.trigger(Events.ERROR, {
  19915. type: ErrorTypes.OTHER_ERROR,
  19916. details: ErrorDetails.INTERNAL_EXCEPTION,
  19917. fatal: fatal,
  19918. event: event,
  19919. error: error
  19920. });
  19921. this.triggeringException = false;
  19922. }
  19923. }
  19924. }
  19925. return false;
  19926. };
  19927. _proto.listenerCount = function listenerCount(event) {
  19928. return this._emitter.listenerCount(event);
  19929. }
  19930. /**
  19931. * Dispose of the instance
  19932. */;
  19933. _proto.destroy = function destroy() {
  19934. logger.log('destroy');
  19935. this.trigger(Events.DESTROYING, undefined);
  19936. this.detachMedia();
  19937. this.removeAllListeners();
  19938. this._autoLevelCapping = -1;
  19939. this.url = null;
  19940. this.networkControllers.forEach(function (component) {
  19941. return component.destroy();
  19942. });
  19943. this.networkControllers.length = 0;
  19944. this.coreComponents.forEach(function (component) {
  19945. return component.destroy();
  19946. });
  19947. this.coreComponents.length = 0;
  19948. // Remove any references that could be held in config options or callbacks
  19949. var config = this.config;
  19950. config.xhrSetup = config.fetchSetup = undefined;
  19951. // @ts-ignore
  19952. this.userConfig = null;
  19953. }
  19954. /**
  19955. * Attaches Hls.js to a media element
  19956. */;
  19957. _proto.attachMedia = function attachMedia(media) {
  19958. logger.log('attachMedia');
  19959. this._media = media;
  19960. this.trigger(Events.MEDIA_ATTACHING, {
  19961. media: media
  19962. });
  19963. }
  19964. /**
  19965. * Detach Hls.js from the media
  19966. */;
  19967. _proto.detachMedia = function detachMedia() {
  19968. logger.log('detachMedia');
  19969. this.trigger(Events.MEDIA_DETACHING, undefined);
  19970. this._media = null;
  19971. }
  19972. /**
  19973. * Set the source URL. Can be relative or absolute.
  19974. */;
  19975. _proto.loadSource = function loadSource(url) {
  19976. this.stopLoad();
  19977. var media = this.media;
  19978. var loadedSource = this.url;
  19979. var loadingSource = this.url = urlToolkitExports.buildAbsoluteURL(self.location.href, url, {
  19980. alwaysNormalize: true
  19981. });
  19982. this._autoLevelCapping = -1;
  19983. this._maxHdcpLevel = null;
  19984. logger.log("loadSource:" + loadingSource);
  19985. if (media && loadedSource && (loadedSource !== loadingSource || this.bufferController.hasSourceTypes())) {
  19986. this.detachMedia();
  19987. this.attachMedia(media);
  19988. }
  19989. // when attaching to a source URL, trigger a playlist load
  19990. this.trigger(Events.MANIFEST_LOADING, {
  19991. url: url
  19992. });
  19993. }
  19994. /**
  19995. * Start loading data from the stream source.
  19996. * Depending on default config, client starts loading automatically when a source is set.
  19997. *
  19998. * @param startPosition - Set the start position to stream from.
  19999. * Defaults to -1 (None: starts from earliest point)
  20000. */;
  20001. _proto.startLoad = function startLoad(startPosition) {
  20002. if (startPosition === void 0) {
  20003. startPosition = -1;
  20004. }
  20005. logger.log("startLoad(" + startPosition + ")");
  20006. this.started = true;
  20007. this.networkControllers.forEach(function (controller) {
  20008. controller.startLoad(startPosition);
  20009. });
  20010. }
  20011. /**
  20012. * Stop loading of any stream data.
  20013. */;
  20014. _proto.stopLoad = function stopLoad() {
  20015. logger.log('stopLoad');
  20016. this.started = false;
  20017. this.networkControllers.forEach(function (controller) {
  20018. controller.stopLoad();
  20019. });
  20020. }
  20021. /**
  20022. * Resumes stream controller segment loading if previously started.
  20023. */;
  20024. _proto.resumeBuffering = function resumeBuffering() {
  20025. if (this.started) {
  20026. this.networkControllers.forEach(function (controller) {
  20027. if ('fragmentLoader' in controller) {
  20028. controller.startLoad(-1);
  20029. }
  20030. });
  20031. }
  20032. }
  20033. /**
  20034. * Stops stream controller segment loading without changing 'started' state like stopLoad().
  20035. * This allows for media buffering to be paused without interupting playlist loading.
  20036. */;
  20037. _proto.pauseBuffering = function pauseBuffering() {
  20038. this.networkControllers.forEach(function (controller) {
  20039. if ('fragmentLoader' in controller) {
  20040. controller.stopLoad();
  20041. }
  20042. });
  20043. }
  20044. /**
  20045. * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
  20046. */;
  20047. _proto.swapAudioCodec = function swapAudioCodec() {
  20048. logger.log('swapAudioCodec');
  20049. this.streamController.swapAudioCodec();
  20050. }
  20051. /**
  20052. * When the media-element fails, this allows to detach and then re-attach it
  20053. * as one call (convenience method).
  20054. *
  20055. * Automatic recovery of media-errors by this process is configurable.
  20056. */;
  20057. _proto.recoverMediaError = function recoverMediaError() {
  20058. logger.log('recoverMediaError');
  20059. var media = this._media;
  20060. this.detachMedia();
  20061. if (media) {
  20062. this.attachMedia(media);
  20063. }
  20064. };
  20065. _proto.removeLevel = function removeLevel(levelIndex) {
  20066. this.levelController.removeLevel(levelIndex);
  20067. }
  20068. /**
  20069. * @returns an array of levels (variants) sorted by HDCP-LEVEL, RESOLUTION (height), FRAME-RATE, CODECS, VIDEO-RANGE, and BANDWIDTH
  20070. */;
  20071. /**
  20072. * Find and select the best matching audio track, making a level switch when a Group change is necessary.
  20073. * Updates `hls.config.audioPreference`. Returns the selected track, or null when no matching track is found.
  20074. */
  20075. _proto.setAudioOption = function setAudioOption(audioOption) {
  20076. var _this$audioTrackContr;
  20077. return (_this$audioTrackContr = this.audioTrackController) == null ? void 0 : _this$audioTrackContr.setAudioOption(audioOption);
  20078. }
  20079. /**
  20080. * Find and select the best matching subtitle track, making a level switch when a Group change is necessary.
  20081. * Updates `hls.config.subtitlePreference`. Returns the selected track, or null when no matching track is found.
  20082. */;
  20083. _proto.setSubtitleOption = function setSubtitleOption(subtitleOption) {
  20084. var _this$subtitleTrackCo;
  20085. (_this$subtitleTrackCo = this.subtitleTrackController) == null ? void 0 : _this$subtitleTrackCo.setSubtitleOption(subtitleOption);
  20086. return null;
  20087. }
  20088. /**
  20089. * Get the complete list of audio tracks across all media groups
  20090. */;
  20091. _createClass(Hls, [{
  20092. key: "levels",
  20093. get: function get() {
  20094. var levels = this.levelController.levels;
  20095. return levels ? levels : [];
  20096. }
  20097. /**
  20098. * Index of quality level (variant) currently played
  20099. */
  20100. }, {
  20101. key: "currentLevel",
  20102. get: function get() {
  20103. return this.streamController.currentLevel;
  20104. }
  20105. /**
  20106. * 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.
  20107. */,
  20108. set: function set(newLevel) {
  20109. logger.log("set currentLevel:" + newLevel);
  20110. this.levelController.manualLevel = newLevel;
  20111. this.streamController.immediateLevelSwitch();
  20112. }
  20113. /**
  20114. * Index of next quality level loaded as scheduled by stream controller.
  20115. */
  20116. }, {
  20117. key: "nextLevel",
  20118. get: function get() {
  20119. return this.streamController.nextLevel;
  20120. }
  20121. /**
  20122. * Set quality level index for next loaded data.
  20123. * This will switch the video quality asap, without interrupting playback.
  20124. * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
  20125. * @param newLevel - Pass -1 for automatic level selection
  20126. */,
  20127. set: function set(newLevel) {
  20128. logger.log("set nextLevel:" + newLevel);
  20129. this.levelController.manualLevel = newLevel;
  20130. this.streamController.nextLevelSwitch();
  20131. }
  20132. /**
  20133. * Return the quality level of the currently or last (of none is loaded currently) segment
  20134. */
  20135. }, {
  20136. key: "loadLevel",
  20137. get: function get() {
  20138. return this.levelController.level;
  20139. }
  20140. /**
  20141. * Set quality level index for next loaded data in a conservative way.
  20142. * This will switch the quality without flushing, but interrupt current loading.
  20143. * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
  20144. * @param newLevel - Pass -1 for automatic level selection
  20145. */,
  20146. set: function set(newLevel) {
  20147. logger.log("set loadLevel:" + newLevel);
  20148. this.levelController.manualLevel = newLevel;
  20149. }
  20150. /**
  20151. * get next quality level loaded
  20152. */
  20153. }, {
  20154. key: "nextLoadLevel",
  20155. get: function get() {
  20156. return this.levelController.nextLoadLevel;
  20157. }
  20158. /**
  20159. * Set quality level of next loaded segment in a fully "non-destructive" way.
  20160. * Same as `loadLevel` but will wait for next switch (until current loading is done).
  20161. */,
  20162. set: function set(level) {
  20163. this.levelController.nextLoadLevel = level;
  20164. }
  20165. /**
  20166. * Return "first level": like a default level, if not set,
  20167. * falls back to index of first level referenced in manifest
  20168. */
  20169. }, {
  20170. key: "firstLevel",
  20171. get: function get() {
  20172. return Math.max(this.levelController.firstLevel, this.minAutoLevel);
  20173. }
  20174. /**
  20175. * Sets "first-level", see getter.
  20176. */,
  20177. set: function set(newLevel) {
  20178. logger.log("set firstLevel:" + newLevel);
  20179. this.levelController.firstLevel = newLevel;
  20180. }
  20181. /**
  20182. * Return the desired start level for the first fragment that will be loaded.
  20183. * The default value of -1 indicates automatic start level selection.
  20184. * Setting hls.nextAutoLevel without setting a startLevel will result in
  20185. * the nextAutoLevel value being used for one fragment load.
  20186. */
  20187. }, {
  20188. key: "startLevel",
  20189. get: function get() {
  20190. var startLevel = this.levelController.startLevel;
  20191. if (startLevel === -1 && this.abrController.forcedAutoLevel > -1) {
  20192. return this.abrController.forcedAutoLevel;
  20193. }
  20194. return startLevel;
  20195. }
  20196. /**
  20197. * set start level (level of first fragment that will be played back)
  20198. * if not overrided by user, first level appearing in manifest will be used as start level
  20199. * if -1 : automatic start level selection, playback will start from level matching download bandwidth
  20200. * (determined from download of first segment)
  20201. */,
  20202. set: function set(newLevel) {
  20203. logger.log("set startLevel:" + newLevel);
  20204. // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel
  20205. if (newLevel !== -1) {
  20206. newLevel = Math.max(newLevel, this.minAutoLevel);
  20207. }
  20208. this.levelController.startLevel = newLevel;
  20209. }
  20210. /**
  20211. * Whether level capping is enabled.
  20212. * Default value is set via `config.capLevelToPlayerSize`.
  20213. */
  20214. }, {
  20215. key: "capLevelToPlayerSize",
  20216. get: function get() {
  20217. return this.config.capLevelToPlayerSize;
  20218. }
  20219. /**
  20220. * Enables or disables level capping. If disabled after previously enabled, `nextLevelSwitch` will be immediately called.
  20221. */,
  20222. set: function set(shouldStartCapping) {
  20223. var newCapLevelToPlayerSize = !!shouldStartCapping;
  20224. if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {
  20225. if (newCapLevelToPlayerSize) {
  20226. this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size.
  20227. } else {
  20228. this.capLevelController.stopCapping();
  20229. this.autoLevelCapping = -1;
  20230. this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap.
  20231. }
  20232. this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;
  20233. }
  20234. }
  20235. /**
  20236. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  20237. */
  20238. }, {
  20239. key: "autoLevelCapping",
  20240. get: function get() {
  20241. return this._autoLevelCapping;
  20242. }
  20243. /**
  20244. * Returns the current bandwidth estimate in bits per second, when available. Otherwise, `NaN` is returned.
  20245. */,
  20246. set:
  20247. /**
  20248. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  20249. */
  20250. function set(newLevel) {
  20251. if (this._autoLevelCapping !== newLevel) {
  20252. logger.log("set autoLevelCapping:" + newLevel);
  20253. this._autoLevelCapping = newLevel;
  20254. this.levelController.checkMaxAutoUpdated();
  20255. }
  20256. }
  20257. }, {
  20258. key: "bandwidthEstimate",
  20259. get: function get() {
  20260. var bwEstimator = this.abrController.bwEstimator;
  20261. if (!bwEstimator) {
  20262. return NaN;
  20263. }
  20264. return bwEstimator.getEstimate();
  20265. },
  20266. set: function set(abrEwmaDefaultEstimate) {
  20267. this.abrController.resetEstimator(abrEwmaDefaultEstimate);
  20268. }
  20269. /**
  20270. * get time to first byte estimate
  20271. * @type {number}
  20272. */
  20273. }, {
  20274. key: "ttfbEstimate",
  20275. get: function get() {
  20276. var bwEstimator = this.abrController.bwEstimator;
  20277. if (!bwEstimator) {
  20278. return NaN;
  20279. }
  20280. return bwEstimator.getEstimateTTFB();
  20281. }
  20282. }, {
  20283. key: "maxHdcpLevel",
  20284. get: function get() {
  20285. return this._maxHdcpLevel;
  20286. },
  20287. set: function set(value) {
  20288. if (isHdcpLevel(value) && this._maxHdcpLevel !== value) {
  20289. this._maxHdcpLevel = value;
  20290. this.levelController.checkMaxAutoUpdated();
  20291. }
  20292. }
  20293. /**
  20294. * True when automatic level selection enabled
  20295. */
  20296. }, {
  20297. key: "autoLevelEnabled",
  20298. get: function get() {
  20299. return this.levelController.manualLevel === -1;
  20300. }
  20301. /**
  20302. * Level set manually (if any)
  20303. */
  20304. }, {
  20305. key: "manualLevel",
  20306. get: function get() {
  20307. return this.levelController.manualLevel;
  20308. }
  20309. /**
  20310. * min level selectable in auto mode according to config.minAutoBitrate
  20311. */
  20312. }, {
  20313. key: "minAutoLevel",
  20314. get: function get() {
  20315. var levels = this.levels,
  20316. minAutoBitrate = this.config.minAutoBitrate;
  20317. if (!levels) return 0;
  20318. var len = levels.length;
  20319. for (var i = 0; i < len; i++) {
  20320. if (levels[i].maxBitrate >= minAutoBitrate) {
  20321. return i;
  20322. }
  20323. }
  20324. return 0;
  20325. }
  20326. /**
  20327. * max level selectable in auto mode according to autoLevelCapping
  20328. */
  20329. }, {
  20330. key: "maxAutoLevel",
  20331. get: function get() {
  20332. var levels = this.levels,
  20333. autoLevelCapping = this.autoLevelCapping,
  20334. maxHdcpLevel = this.maxHdcpLevel;
  20335. var maxAutoLevel;
  20336. if (autoLevelCapping === -1 && levels != null && levels.length) {
  20337. maxAutoLevel = levels.length - 1;
  20338. } else {
  20339. maxAutoLevel = autoLevelCapping;
  20340. }
  20341. if (maxHdcpLevel) {
  20342. for (var i = maxAutoLevel; i--;) {
  20343. var hdcpLevel = levels[i].attrs['HDCP-LEVEL'];
  20344. if (hdcpLevel && hdcpLevel <= maxHdcpLevel) {
  20345. return i;
  20346. }
  20347. }
  20348. }
  20349. return maxAutoLevel;
  20350. }
  20351. }, {
  20352. key: "firstAutoLevel",
  20353. get: function get() {
  20354. return this.abrController.firstAutoLevel;
  20355. }
  20356. /**
  20357. * next automatically selected quality level
  20358. */
  20359. }, {
  20360. key: "nextAutoLevel",
  20361. get: function get() {
  20362. return this.abrController.nextAutoLevel;
  20363. }
  20364. /**
  20365. * this setter is used to force next auto level.
  20366. * this is useful to force a switch down in auto mode:
  20367. * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
  20368. * forced value is valid for one fragment. upon successful frag loading at forced level,
  20369. * this value will be resetted to -1 by ABR controller.
  20370. */,
  20371. set: function set(nextLevel) {
  20372. this.abrController.nextAutoLevel = nextLevel;
  20373. }
  20374. /**
  20375. * get the datetime value relative to media.currentTime for the active level Program Date Time if present
  20376. */
  20377. }, {
  20378. key: "playingDate",
  20379. get: function get() {
  20380. return this.streamController.currentProgramDateTime;
  20381. }
  20382. }, {
  20383. key: "mainForwardBufferInfo",
  20384. get: function get() {
  20385. return this.streamController.getMainFwdBufferInfo();
  20386. }
  20387. }, {
  20388. key: "allAudioTracks",
  20389. get: function get() {
  20390. var audioTrackController = this.audioTrackController;
  20391. return audioTrackController ? audioTrackController.allAudioTracks : [];
  20392. }
  20393. /**
  20394. * Get the list of selectable audio tracks
  20395. */
  20396. }, {
  20397. key: "audioTracks",
  20398. get: function get() {
  20399. var audioTrackController = this.audioTrackController;
  20400. return audioTrackController ? audioTrackController.audioTracks : [];
  20401. }
  20402. /**
  20403. * index of the selected audio track (index in audio track lists)
  20404. */
  20405. }, {
  20406. key: "audioTrack",
  20407. get: function get() {
  20408. var audioTrackController = this.audioTrackController;
  20409. return audioTrackController ? audioTrackController.audioTrack : -1;
  20410. }
  20411. /**
  20412. * selects an audio track, based on its index in audio track lists
  20413. */,
  20414. set: function set(audioTrackId) {
  20415. var audioTrackController = this.audioTrackController;
  20416. if (audioTrackController) {
  20417. audioTrackController.audioTrack = audioTrackId;
  20418. }
  20419. }
  20420. /**
  20421. * get the complete list of subtitle tracks across all media groups
  20422. */
  20423. }, {
  20424. key: "allSubtitleTracks",
  20425. get: function get() {
  20426. var subtitleTrackController = this.subtitleTrackController;
  20427. return subtitleTrackController ? subtitleTrackController.allSubtitleTracks : [];
  20428. }
  20429. /**
  20430. * get alternate subtitle tracks list from playlist
  20431. */
  20432. }, {
  20433. key: "subtitleTracks",
  20434. get: function get() {
  20435. var subtitleTrackController = this.subtitleTrackController;
  20436. return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
  20437. }
  20438. /**
  20439. * index of the selected subtitle track (index in subtitle track lists)
  20440. */
  20441. }, {
  20442. key: "subtitleTrack",
  20443. get: function get() {
  20444. var subtitleTrackController = this.subtitleTrackController;
  20445. return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
  20446. },
  20447. set:
  20448. /**
  20449. * select an subtitle track, based on its index in subtitle track lists
  20450. */
  20451. function set(subtitleTrackId) {
  20452. var subtitleTrackController = this.subtitleTrackController;
  20453. if (subtitleTrackController) {
  20454. subtitleTrackController.subtitleTrack = subtitleTrackId;
  20455. }
  20456. }
  20457. /**
  20458. * Whether subtitle display is enabled or not
  20459. */
  20460. }, {
  20461. key: "media",
  20462. get: function get() {
  20463. return this._media;
  20464. }
  20465. }, {
  20466. key: "subtitleDisplay",
  20467. get: function get() {
  20468. var subtitleTrackController = this.subtitleTrackController;
  20469. return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
  20470. }
  20471. /**
  20472. * Enable/disable subtitle display rendering
  20473. */,
  20474. set: function set(value) {
  20475. var subtitleTrackController = this.subtitleTrackController;
  20476. if (subtitleTrackController) {
  20477. subtitleTrackController.subtitleDisplay = value;
  20478. }
  20479. }
  20480. /**
  20481. * get mode for Low-Latency HLS loading
  20482. */
  20483. }, {
  20484. key: "lowLatencyMode",
  20485. get: function get() {
  20486. return this.config.lowLatencyMode;
  20487. }
  20488. /**
  20489. * Enable/disable Low-Latency HLS part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK.
  20490. */,
  20491. set: function set(mode) {
  20492. this.config.lowLatencyMode = mode;
  20493. }
  20494. /**
  20495. * Position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```hls.config.liveSyncDuration```)
  20496. * @returns null prior to loading live Playlist
  20497. */
  20498. }, {
  20499. key: "liveSyncPosition",
  20500. get: function get() {
  20501. return this.latencyController.liveSyncPosition;
  20502. }
  20503. /**
  20504. * Estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced)
  20505. * @returns 0 before first playlist is loaded
  20506. */
  20507. }, {
  20508. key: "latency",
  20509. get: function get() {
  20510. return this.latencyController.latency;
  20511. }
  20512. /**
  20513. * maximum distance from the edge before the player seeks forward to ```hls.liveSyncPosition```
  20514. * configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration```
  20515. * @returns 0 before first playlist is loaded
  20516. */
  20517. }, {
  20518. key: "maxLatency",
  20519. get: function get() {
  20520. return this.latencyController.maxLatency;
  20521. }
  20522. /**
  20523. * target distance from the edge as calculated by the latency controller
  20524. */
  20525. }, {
  20526. key: "targetLatency",
  20527. get: function get() {
  20528. return this.latencyController.targetLatency;
  20529. }
  20530. /**
  20531. * the rate at which the edge of the current live playlist is advancing or 1 if there is none
  20532. */
  20533. }, {
  20534. key: "drift",
  20535. get: function get() {
  20536. return this.latencyController.drift;
  20537. }
  20538. /**
  20539. * set to true when startLoad is called before MANIFEST_PARSED event
  20540. */
  20541. }, {
  20542. key: "forceStartLoad",
  20543. get: function get() {
  20544. return this.streamController.forceStartLoad;
  20545. }
  20546. }], [{
  20547. key: "version",
  20548. get:
  20549. /**
  20550. * Get the video-dev/hls.js package version.
  20551. */
  20552. function get() {
  20553. return "1.5.11";
  20554. }
  20555. }, {
  20556. key: "Events",
  20557. get: function get() {
  20558. return Events;
  20559. }
  20560. }, {
  20561. key: "ErrorTypes",
  20562. get: function get() {
  20563. return ErrorTypes;
  20564. }
  20565. }, {
  20566. key: "ErrorDetails",
  20567. get: function get() {
  20568. return ErrorDetails;
  20569. }
  20570. /**
  20571. * Get the default configuration applied to new instances.
  20572. */
  20573. }, {
  20574. key: "DefaultConfig",
  20575. get: function get() {
  20576. if (!Hls.defaultConfig) {
  20577. return hlsDefaultConfig;
  20578. }
  20579. return Hls.defaultConfig;
  20580. }
  20581. /**
  20582. * Replace the default configuration applied to new instances.
  20583. */,
  20584. set: function set(defaultConfig) {
  20585. Hls.defaultConfig = defaultConfig;
  20586. }
  20587. }]);
  20588. return Hls;
  20589. }();
  20590. Hls.defaultConfig = void 0;
  20591. return Hls;
  20592. }));
  20593. })(false);
  20594. //# sourceMappingURL=hls.light.js.map